javascript 地图标记 getPosition() 在第一次调用函数时不适用于谷歌地图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10131815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Map marker getPosition() not working for google maps on first call of function
提问by user1330217
I'm trying to place a marker on my map and then use the position of that marker to draw some polygons. However, marker.getPosition() does not seem to return a value initially. I would need to call the function again to get the previous marker position. Does anyone have any suggestions as to why this is
我试图在我的地图上放置一个标记,然后使用该标记的位置来绘制一些多边形。但是,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
}
回答by Kristoffer Sall-Storgaard
Google maps is using callbacks, (see parameter 2 in the documentation) because its not synchronous. The function(results,status)
bit is where the magic happens. It is run when Google has geocoded the address. Untill then you have nothing to display.
Google 地图正在使用回调(请参阅文档中的参数 2),因为它不是同步的。该function(results,status)
位是神奇在哪里发生。当 Google 对地址进行地理编码时运行它。在那之前你没有什么可显示的。
try this:
试试这个:
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");
}
And you will see that alert("Alert 2")
appears before alert("Alert 1")
你会看到alert("Alert 2")
之前出现的alert("Alert 1")
回答by Drauka
You could take advantage of $.Deferred()
你可以利用 $.Deferred()
function codeAddress() {
var address = fubar;
var d = $.Deferred();
var marker;
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);
d.resolve();
});
d.done(function(){
document.write(marker.getPosition());
});
}