简体   繁体   中英

Google Geocode Javascript API - How to get coordinates?

I would like Google Maps to convert a user submitted address into map coordinates. I only want these coordinates to be stored in a variable, to be accessed later:

function map_search() {
    console.log("search form functional"); // sanity check
    var searchLoc = $('#search_location').val();
    console.log(searchLoc);
    var searchCoords = geocoder.geocode( {'address': searchLoc});
    console.log(searchCoords);

    ...
}

I am setting it up like so:

var geocoder = new google.maps.Geocoder();

This works up to the point where var seachCoords is defined. In console, it simply prints as undefined .

Other Google Maps functions are operating successfully on this page. Is my JavaScript wrong, or am I using this geocoder improperly?

From the documentation at https://developers.google.com/maps/documentation/javascript/geocoding

The Geocoding service requires a callback method to execute upon retrieval of the geocoder's results. This callback should pass two parameters to hold the results and a status code, in that order.

example:

geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        console.log(results); // all results
        console.log(results[0].geometry.location); // "first" location
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });

NOTE: this is by it's nature asynchronous , so don't try to put this in a function that returns results[0].geometry.location in a return statement

Try this php script:

function getCoordinates($address){

$address = str_replace(" ", "+", $address); // replace all the white space with "+" sign to match with google search pattern

$url = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=$address";

$response = file_get_contents($url);

$json = json_decode($response,TRUE); //generate array object from the response from the web

return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geometry']['location']['lng']);

}

How to call the function in php:

echo getCoordinates('740 Story Rd San Jose CA 95122');
Result : 37.328865,-121.8581845

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