Google映射api和地理编码api - 添加标记的问题

时间:2017-01-25 13:11:22

标签: javascript arrays google-maps google-maps-api-3

我首先要说的是我对JS比较陌生,所以如果这很明显,请原谅我的无知。

我正在尝试将标记添加到Google地图中。我创建了一个数组coordList,然后使用地理编码api从地址中获取滞后和长并将它们推入coordList。

我现在正在尝试使用coordList数组在地图上绘制标记,但是我似乎无法从coordList数组中获取值。当我运行console.log(typeof coordList)时 - 它告诉我它是一个对象,但是当我用console.log(coordList)查看数组时,它看起来像一个普通的数组?

  var coordList = [];
  var address = [];

 address.push('52+Kalynda+pde,+bohle+plains,+QLD')
 address.push('51+Frank+St,+Kirwan+QLD+4817');

  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 12,
      center: new google.maps.LatLng(-19.259854,146.8001348),
      mapTypeId: 'roadmap'
    });


  }

   function getLatLong(address){
    var index;
    for (index = 0; index < address.length; ++index) {

    var request = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address[index] + '&key=[MY_key]';

    $.getJSON( request, function( data ) {

    var lat = data.results[0].geometry.location.lat;
    var lng = data.results[0].geometry.location.lng;

        var coords = [];
        coords.push(lat);
        coords.push(lng);
        //push coords into coordList
        coordList.push(coords);

  });
    }
  }


  // Loop through the results array and place a marker for each
  // set of coordinates.
  function addMarkers(coordList) {

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

      var coords = coordList[i];
      var latLng = new google.maps.LatLng(coords[0],coords[1]);
      var marker = new google.maps.Marker({
        position: latLng,
        map: map
      });
    }
  }
  getLatLong(address);
  addMarkers(coordList);

1 个答案:

答案 0 :(得分:1)

你的问题是$ .getJSON()是一个异步请求,你的代码在$ .getJSON()完成之前执行addMarkers(),所以coordList为空。

您可以在$ .getJSON()回调中添加标记。例如:

var address = [];

address.push('52+Kalynda+pde,+bohle+plains,+QLD')
address.push('51+Frank+St,+Kirwan+QLD+4817');

function initMap() {
   map = new google.maps.Map(document.getElementById('map'), {
      zoom: 12,
      center: new google.maps.LatLng(-19.259854,146.8001348),
      mapTypeId: 'roadmap'
   });
}

function getLatLongAndAddMarkers(address){
  var index;
  for (index = 0; index < address.length; ++index) {
     var request = 'https://maps.googleapis.com/maps/api/geocode/json?dress=' + address[index] + '&key=[MY_key]';
     $.getJSON( request, function( data ) {
        var latLong = new google.maps.LatLng(data.results[0].geometry.location);
        //add markers here
        var marker = new google.maps.Marker({
            position: latLong,
            map: map
         });
     });
  }
}

getLatLongAndAddMarkers(address);