Skip to content Skip to sidebar Skip to footer

Multi Address Array Google Maps Uncaught Typeerror: Cannot Read Property '0' Of Undefined

There is something wrong with my for loop or array but I don't know where. Uncaught TypeError: Cannot read property '0' of undefined How does the loop should be to work properly?

Solution 1:

The geocoder is asynchronous. When the callback runs i==addresses.length which is not a valid entry in your array. This is usually solved using function closure.

code snippet:

var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
  mapTypeId: 'roadmap'
};

// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);

// Multiple addressesvar addresses = [
  ["First Place", "Colonia providencia, Guadalajara, Jalisco, México"],
  ["Second Place", "Colonia Ayuntamiento, Guadalajara, Jalisco, Mexico"],
  ["Third Place", "Colonia Moderna, Guadalajara, Jalisco, Mexico"],
  ["Fourth Place", "Colonia Santa Edwiges, Jalisco, Mexico"]
];

var geocoder = new google.maps.Geocoder();

// Loop through our array of addresses & place each one on the map  for (var i = 0; i < addresses.length; i++) {
  createMarker(i);

  // Automatically center the map fitting all addresses on the screen
  map.fitBounds(bounds);
};
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
  this.setZoom(5);
  google.maps.event.removeListener(boundsListener);
});

functioncreateMarker(i) {
  geocoder.geocode({
    "address": addresses[i][1]
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK && results.length > 0) {

      var location = results[0].geometry.location;
      var lat = location.lat();
      var lng = location.lng();
      var position = new google.maps.LatLng(lat, lng);
      bounds.extend(position);
      marker = new google.maps.Marker({
        position: position,
        map: map,
        title: addresses[i][0],
        // icon: icon
      });
      map.fitBounds(bounds);

    };
  });
}
#map_canvas {
  width: 535px;
  height: 600px;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://maps.googleapis.com/maps/api/js"></script><divid="map_canvas"></div>

Post a Comment for "Multi Address Array Google Maps Uncaught Typeerror: Cannot Read Property '0' Of Undefined"