Google Geocode Javascript API - 如何获取坐标?

时间:2015-11-07 05:26:11

标签: javascript google-maps google-maps-api-3 geocoding

我希望Google地图将用户提交的地址转换为地图坐标。我只希望将这些坐标存储在一个变量中,以便稍后访问:

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

    ...
}

我这样设置:

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

这可以达到定义var seachCoords的程度。在控制台中,它只是打印为undefined

其他Google地图功能在此页面上成功运行。 我的JavaScript是错误的,还是我不正确地使用了这个地理编码器?

2 个答案:

答案 0 :(得分:1)

来自https://developers.google.com/maps/documentation/javascript/geocoding

的文档
  

地理编码服务要求在检索地理编码器结果时执行回调方法。此回调应传递两个参数以按顺序保存结果和状态代码。

示例:

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

注意:这本质上是异步,所以不要试图将它放在一个在return语句中返回results[0].geometry.location的函数中

答案 1 :(得分:-1)

试试这个php脚本:

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']);

}

如何在php中调用该函数:

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