Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

javascript - 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? http://jsfiddle.net/hugpablo/uLza5va6/1/

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 addresses
        var 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++ ) {
            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
                });
            };
        });
            // 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);
    });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 addresses
var 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);
});

function createMarker(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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...