var address = "Boston";
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.bounds);
createLatLng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
function createLatLng() {
var MapCenter=map.getCenter();
var x=MapCenter.lat(), y=MapCenter.lng(), z=0;
}
right now I have this code, mostly taken from this example at google: https://developers.google.com/maps/documentation/javascript/geocoding .
Right now the x and y variables are undefined. Why is this and how can I get the x and y variables correctly?
also here is demo if it helps: http://jsbin.com/ilOTIQIn/1/edit
Because geocode
is asynchronous you're not going to be able to set MapCenter
at the place you want to because the results of the API call won't have returned at that point. I suggest you use a callback
to help you manage the call:
var MapCenter, map, x, y, z;
function geocode(callback) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.bounds);
callback();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
geocode(function () {
MapCenter = map.getCenter();
x = MapCenter.lat(), y = MapCenter.lng(), z = 0;
});
Javascript is an asynchronous language. Your geocode request gets sent off, and while that's happening, your x,y, and z vars are evaluated. Your geocode result then returns, but the x, y and z vars have already been set. I would define your x,y,z vars above the function, then , where you check if the status is 'ok' set them there.
perceived order of events:
actual order of events:
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.