Domanda

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

È stato utile?

Soluzione

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

Altri suggerimenti

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:

  1. send off request
  2. request returns
  3. set variables x, y z

actual order of events:

  1. Send off request
  2. Set variables x, y, z
  3. result returns
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top