0
votes

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
}
2

2 Answers

4
votes

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.

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")

1
votes

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());
  });
}