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
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
}
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
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
}
Share
Improve this question
asked Apr 12, 2012 at 21:04
user1330217user1330217
2432 gold badges4 silver badges14 bronze badges
2 Answers
Reset to default 4Google 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.
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")
You could take advantage of $.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());
});
}