我正在尝试在 map 上放置一个标记,然后使用该标记的位置来绘制一些多边形。但是,marker.getPosition() 最初似乎没有返回值。我需要再次调用该函数来获取之前的标记位置。有谁对为什么会这样有任何建议
function codeAddress() {
var address = fubar;
geocoder.geocode( { 'address': address}, function(results, status) {
map.setCenter(results[0].geometry.location);
map.setZoom(1);
if (marker == null){
marker = new google.maps.Marker({
map: map,
});
}
marker.setPosition(results[0].geometry.location);
});
document.write(marker.getPosition()); //this displays nothing
}
最佳答案
Google map 正在使用回调 ( see parameter 2 in the documentation ),因为它的 not synchronous 。 function(results,status)
位是神奇发生的地方。它在 Google 对地址进行地理编码后运行。在那之前你没有什么可显示的。
试试这个:
function codeAddress() {
var address = fubar;
geocoder.geocode( { 'address': address}, function(results, status) {
map.setCenter(results[0].geometry.location);
map.setZoom(1);
if (marker == null){
marker = new google.maps.Marker({
map: map,
});
}
marker.setPosition(results[0].geometry.location);
alert("Alert 1");
alert(marker.getPosition());
});
alert("Alert 2");
}
你会看到alert("Alert 2")
出现在alert("Alert 1")
关于javascript - map 标记 getPosition() 在第一次调用函数时不适用于谷歌地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10131815/