JS Geocoder cannot assign Global Variable for Google Maps Variable

倾然丶 夕夏残阳落幕 提交于 2019-12-04 19:11:56

The geocoder is asynchronous. One option is to use function closure to associate the variables in the request with the callback function:

for (var i = 0; i < data.length; i++) {
    geocoder.geocode({
        'address': data[i] + ", indonesia"
    }, (function(data, i) { return function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {

            locations[i] = [data, results[0].geometry.location.lat(), results[0].geometry.location.lng()];
            var mark = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map,
                title: data
            });
            // alert(locations[i]);
        } else {
            alert("Something got wrong " + status);
        }
    }}(data[i], i))); // has function closure on data[i] as data, i (as i)
}

working fiddle

code snippet:

var geocoder = new google.maps.Geocoder();
var map;
var data = ["Terogong, Indonesia", "Blok M, Indonesia", "Cipinang, Indonesia"];

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var bounds = new google.maps.LatLngBounds();
  var locations = new Array(3);
  for (var i = 0; i < 3; i++) {
    locations[i] = ['1', '2', '3'];
  }
  for (var i = 0; i < data.length; i++) {
    geocoder.geocode({
      'address': data[i] + ", indonesia"
    }, (function(data, i) {
      return function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          bounds.extend(results[0].geometry.location);
          map.fitBounds(bounds);
          locations[i] = [data, results[0].geometry.location.lat(), results[0].geometry.location.lng()];
          var mark = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: data
          });
        } else {
          alert("Something got wrong " + status);
        }
      }
    }(data[i], i)));
  }

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