[英]Map marker getPosition() not working for google maps on first call of function
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.
但是,marker.getPosition()似乎最初并不返回值。 I would need to call the function again to get the previous marker position.
我将需要再次调用该函数以获取先前的标记位置。 Does anyone have any suggestions as to why this is
有谁对这是为什么有任何建议
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 maps is using callbacks, ( see parameter 2 in the documentation ) because its not synchronous . Google Maps使用回调,( 请参阅文档中的参数2 ),因为它不同步 。 The
function(results,status)
bit is where the magic happens. function(results,status)
位是发生魔术的地方。 It is run when Google has geocoded the address. 它在Google对地址进行地理编码后运行。 Untill then you have nothing to display.
在此之前,您什么也没显示。
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")
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());
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.