I'm trying to build a little app with the Google Map API, and since it's my first javascript app (I already know about the language, but I almost never use it), I'm struggling with a little problem.
I'm trying to get the elevation related to a marker, using the ElevationService, in order to push the two datas ({marker, elevation}) into an array. However, the line where I push the datas into the array is hit before the callback function for getElevationForLocations
has been called, resulting in the push of an undefined data (elevation).
I think I should use an asynchronous function in order to wait for the callback to be executed before the data has been pushed, but I don't know how to use it.
Could anyone give me indications on that ?
Thanks a lot, Méta
P.S.: Here is my script
var markers = [];
function initMap()
{
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -25.363882, lng: 131.044922 },
mapTypeId: 'terrain'
});
var elevator = new google.maps.ElevationService;
map.addListener('click', function(e) {
addMarker(e.latLng, map, elevator);
});
}
function getElevation(location, elevator) {
var elevation;
// Initiate the location request
elevator.getElevationForLocations({
'locations': [location]
}, function(results, status)
{
if (status === 'OK') {
// Retrieve the first result
if (results[0]) {
return results[0].elevation;
}
}
});
}
function placeMarkerAndPanTo(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
map.panTo(latLng);
return marker;
//markers.push(marker);
}
function addMarker(location, map, elevator)
{ var marker = placeMarkerAndPanTo(location, map);
var elevation = getElevation(location, elevator);
markers.push({marker, elevation});
}
答案 0 :(得分:0)
以下是您的代码的简化版本,使用我在评论中描述的内容。
var markers = [];
var elevator = new google.maps.ElevationService;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: -25.363882,
lng: 131.044922
},
mapTypeId: 'terrain'
});
map.addListener('click', function(e) {
addMarker(e.latLng);
});
}
function addMarker(location) {
elevator.getElevationForLocations({
'locations': [location]
}, function(results, status) {
if (status === 'OK') {
// Retrieve the first result
if (results[0]) {
var marker = new google.maps.Marker({
position: location,
map: map
});
map.panTo(location);
markers.push({
marker: marker,
elevation: results[0].elevation
});
console.log(markers);
}
}
});
}
google.maps.event.addDomListener(window, 'load', initMap);

#map {
height: 200px;
}

<script src="//maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
&#13;
修改:似乎此刻从代码段加载API时出现问题(至少对我来说,这会让我的浏览器崩溃),所以这里有一个正常的JSFiddle好。