Google Maps with multiple geocode locations and alerts on click

折月煮酒 提交于 2019-12-04 07:25:32

问题


I am trying to create a Google Map with multiple geocode locations and a unique alert for each location.

Eventually, the locations and locations content will be dynamically generated, but right now, I am just trying to get it working with static content.

My map points are appearing properly, however, I am having a problem with the alerts which will not appear with the incrementing variable in place.

As far as I can tell, the var [i] in locationContent[i][0] is not being replaced with a number.

http://jsfiddle.net/rum0gxtw/

When I replace the code with locationContent[0][1] for example, it returns alert1 (on all 3 markers).

http://jsfiddle.net/rum0gxtw/1/

I need it to increment so it returns alert1, alert2, alert3 for the respective marker.

I've been staring at the code for hours now trying various things to solve it. I think I am just missing something fundamental. Here is my code:

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(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(i) {
                return function() {
                    alert(locationContent[i][1]);
                }
            })(i));

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

Would highly appreciate if someone could help me out with this.

Thanks.


回答1:


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>


来源:https://stackoverflow.com/questions/29195868/google-maps-with-multiple-geocode-locations-and-alerts-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!