Multi address array Google maps Uncaught TypeError: Cannot read property '0' of undefined

前端 未结 1 1570
一整个雨季
一整个雨季 2020-12-22 14:50

There is something wrong with my for loop or array but I don\'t know where.

Uncaught TypeError: Cannot read property \'0\' of undefined

相关标签:
1条回答
  • 2020-12-22 14:55

    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>

    0 讨论(0)
提交回复
热议问题