I'm trying to work with the google maps API and am having some trouble. I've created a function called getPoint which accepts an address. It uses the google api to turn that address into a GPoint object using the GClientGeocoder.getLatLng(address,callback) function. The getLatLng() is passed the address and a callback function as you can see below. I want the getPoint() function I've written to return the "point" variable passed to the callback function from the getLatLng() call. I am struggling to figure out how to do this or even if it can be done?
function getPoint(address) {
var geocoder = new GClientGeocoder();
return geocoder.getLatLng(
address,
function(point){
return point;
}
);
}
Thanks in advance for the help!
GClientGeocoder.getLatLng is an asynchronous operation, so you cannot have a return statement in getPoint actually do what you expect.
You have to restructure your code to take a callback function, which you call when the asynchronous operation completes:
function getPoint(address, callback) {
var geocoder = new GClientGeocoder();
geocoder.getLatLng(
address,
function(point){
/* asynch operation complete.
* Call the callback with the results */
callback(point)
}
);
}
or even better (albeit a touch more esoteric):
function getPoint(address, callback) {
var geocoder = new GClientGeocoder();
geocoder.getLatLng(
address,
callback // GClientGeocoder will call the callback for you
);
}
Edit re your comment question:
OK that is a whole other question, but in a nutshell, the JavaScript function callback you pass will have access to your map instance as long as you define the function in the same scope as the map instance is defined:
var map = new GMap2(/*...*/);
var addresses = []; // list of address strings
for(var i=0; i < addresses.length; i++) {
getPoint(addresses[i], function(point) { // pass the callback function
map.addOverlay(/*...*/); // map variable is in scope
})
}
This style of function is called a closure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With