Javascript 谷歌地图API标记随机显示

Javascript 谷歌地图API标记随机显示,javascript,google-maps,Javascript,Google Maps,出于某种原因,尽管console.log(locations)显示数组被正确附加到,但每次我刷新页面时,都只会显示数组中的少数随机标记。每次刷新页面时,标记都会更改。我很困惑。您可以自己在redditglobe.me查看它,您将立即调用initMap,然后尝试使用位置数组添加标记 但是,locations仅在每次调用axios后填充。在geocode函数中获取请求完成 每次调用geocode函数都是在您对posts\u reply\u to.txt文件发出ajax请求之后进行的。因此,这可能发生

出于某种原因,尽管console.log(locations)显示数组被正确附加到,但每次我刷新页面时,都只会显示数组中的少数随机标记。每次刷新页面时,标记都会更改。我很困惑。您可以自己在redditglobe.me查看它,您将立即调用initMap,然后尝试使用
位置数组添加标记

但是,
locations
仅在每次调用
axios后填充。在
geocode
函数中获取
请求完成

每次调用
geocode
函数都是在您对
posts\u reply\u to.txt
文件发出ajax请求之后进行的。因此,这可能发生在
initMap
函数之后

您应该将添加标记的代码移动到
,然后移动到
块中。或者在
$.ajax()
请求的
成功
处理程序的末尾

function geocode(wordOne, wordTwo) {
  axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
    params: {
      address:wordOne + ' ' + wordTwo,
      key:'BLAH'
    }
  })
  .then(function(response){
    console.log("geocode success");
    //get long and lat JSON data and append locations array
    var latandlong = response.data.results[0].geometry.location;
    locations.push(latandlong);
    console.log(locations);

  })
  .catch(function(error){
    console.log("geocode error");
  });
}

function initMap() {

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 2,
    center: {lat: -28.024, lng: 140.887}
  });

  var markers = locations.map(function(location, i) {
    return new google.maps.Marker({
      position: location,
    });
  });

  // Add a marker clusterer to manage the markers.
  var markerCluster = new MarkerClusterer(map, markers,
      {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}