views:

54

answers:

2

I'm placing a number of markers on a map. When the user clicks on one of them, I'd like to do a callback to get some information, and display it in the popup.

My code to place the markers on the map works, and looks like:

GEvent.addListener(marker, "click", function() {
  html = getDetails(id);
  marker.openInfoWindowHtml(html);
});

My getDetails function:

  function getDetails(did) {
    var desc;
    desc = "Nothing here";
    var path = '/path/GetDetails';
    $.post(path, {id:did}, function(data, status) {
      desc = data
    });
    return desc;
  }

GetDetails get called, receives the correct value, and returns the right thing, but I seem to be missing a way to get that data from the callback function into my local var - how can I do this?

A: 

Your .post method call is asynchronous and returns immediately, your desc variable is still without a return value.

You should change to use $.ajax() so that you can specify a synchronous call, OR you should pass a reference to the openInfoWindowHtml method into your getDetails function so that the results can be sent along, ala:

GEvent.addListener(marker, "click", function() { 
    getDetails(id, marker.openInfoWindowHtml);
});

function getDetails(did, fInfoWindowMethod) {
    var path = '/path/GetDetails';
    $.post(path, {id:did}, function(data, status) {
        fInfoWindowMethod(data);
    }
}
great_llama
A: 

I think the problem comes from the fact that you're making an asynchronous Ajax call, and so getDetails is returning the value before the Ajax call returns. I would try changing the getDetails method to modify the value of the marker rather than returning a value:

function getDetails(did, marker) {
  var path = '/path/GetDetails';
  $.post(path, {id:did}, function(data, status) {
    marker.openInfoWindowHtml(data);
  });
}

Then changing the event listener:

GEvent.addListener(marker, "click", function() {
  getDetails(id, marker);
});
Hooray Im Helping
Thanks - you certainly helped in this case!
chris