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'});
}
由于某种原因,尽管console.log(位置)显示正在正确附加数组,但每次刷新页面时,只显示数组中的少数随机标记。每次页面刷新时标记都会更改。我感到很困惑。您可以在redditglobe.me
自己查看答案 0 :(得分:1)
您立即调用initMap,然后尝试使用locations
数组添加标记。
但是,只有在locations
函数中每次调用axios.get
请求完成后,才会填充geocode
。
每次调用geocode
函数只会在您为posts_replied_to.txt
文件发出ajax请求后才会发生。所以这可能发生在initMap
函数之后。
您应该将代码添加到then
块中。或者也许在success
请求的$.ajax()
处理程序的末尾。