Google Maps with multiple geocode locations and alerts on click

扶醉桌前 提交于 2019-12-02 13:18:04

Geocoding is asynchronous. When the loop ends i=locations.length; which is when all the geocoding callbacks run.

Use anonymous function closure on i for the geocoder, as well as the marker click event handler:

for (i = 0; i < locations.length; i++) {
  geocoder.geocode({
    'address': locations[i][1]
  }, (function(i) {
    return function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        marker = new google.maps.Marker({
          position: results[0].geometry.location,
          icon: image,
          map: map
        });
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
          return function() {
            alert(locationContent[i][1]);
          };
        })(marker, i));
      } else {
        alert("some problem in geocode" + status);
      }
    };
  })(i));
}

working fiddle

code snippet:

function initialize() {
  var locations = [
    ['Loughbourough University', 'LE11 3TU'],
    ['Durham School', 'DH1 4SZ'],
    ['Oxford University', 'OX4 1EQ']
  ];

  // Alert Content
  var locationContent = [
    ['wow1', 'alert1'],
    ['wow2', 'alert2'],
    ['wow3', 'alert3']
  ];

  // var image = 'icon.png';
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: new google.maps.LatLng(43.253205, -80.480347),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

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

  for (i = 0; i < locations.length; i++) {

    geocoder.geocode({
      'address': locations[i][1]
    }, (function(i) {
      return function(results, status) {
        //alert(status);
        if (status == google.maps.GeocoderStatus.OK) {

          //alert(results[0].geometry.location);
          map.setCenter(results[0].geometry.location);
          marker = new google.maps.Marker({
            position: results[0].geometry.location,
            // icon: image,
            map: map
          });

          google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
              alert(locationContent[i][1]);
            };
          })(marker, i));

        } else {
          alert("some problem in geocode" + status);
        }
      };
    })(i));

  }
}

google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map" style="border: 2px solid #3872ac;"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!