So I have
function find_coord(lat, lng) {
var smart_loc;
var latlng = new google.maps.LatLng(lat, lng);
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'latLng': latlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
smart_loc = new smart_loc_obj(results);
} else {
smart_loc = null;
}
});
return smart_loc;
}
I want to return the smart_loc variable/object but it is always null because the scope of the function(results, status) doesn't reach the smart_loc declared in the find_coord function. So how do you get a variable inside the function(results, status) out?
You can do:
var smart_loc;
function find_coord(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'latLng': latlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
smart_loc = new smart_loc_obj(results);
} else {
smart_loc = null;
}
});
}
Or if you need to run a function when smart_loc changes:
function find_coord(lat, lng, cb) {
var smart_loc;
var latlng = new google.maps.LatLng(lat, lng);
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'latLng': latlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
smart_loc = new smart_loc_obj(results);
} else {
smart_loc = null;
}
cb(smart_loc);
});
}
then call:
find_coord(lat, lng, function (smart_loc) {
//
// YOUR CODE WITH 'smart_loc' HERE
//
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.