简体   繁体   中英

how to get latitude longitude from function and send it to new google.maps.LatLng( latitude ,longitude ) javascript

I am using this script to get latitude longitude from an address,

var latitude="";
var longitude ="";


function codeAddress(address) {

  var geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == 'OK') {


    latitude = results[0].geometry.location.lat();
    longitude = results[0].geometry.location.lng();
    //  myAfterFunction();
    //  console.log(this.latitude);

    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });

}

var center = new google.maps.LatLng(latitude,longitude );

my problem is i cant get the latitude and longitude values from this function, i tried using another function

function myAfterFunction(){
  console.log(latitude);
}

so my question is how to get latitude and longitude from my function? thank you

Based on your title (I could be wrong, you should clearly indicate what your code does in the question), it sounds like you are successfully getting the latitude and longitude, but then failing to send it to the map.

The issue likely lies in the fact:

Accessing the Geocoding service is asynchronous, since the Google Maps API needs to make a call to an external server. For that reason, you need to pass a callback method to execute upon completion of the request. This callback method processes the result(s). Note that the geocoder may return more than one result. ( API docs )

The asynchronous nature of this means that while your call back function ( function(results, status) {...}) ) is waiting on a response, you're also executing this line:

var center = new google.maps.LatLng(latitude,longitude );

But, of course, latitude and longitude have not yet been defined as we have no response yet.

To see this in action explicitly, replace the code defining center with an alert() or console.log() , and place another in the call back function and see what triggers first:

function codeAddress(address) {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': address}, function(results, status) {
    console.log("Response recieved");
    }
  });

}
console.log("Tried to use response");

The simplest solution might be to place the code that requires this specific longitude and latitude inside the callback function, so that it doesn't execute until you have a response and by extension a latitude and longitude.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM