谷歌地理代码Javascript API-如何获得坐标

Google Geocode Javascript API - How to get coordinates?

本文关键字:何获得 坐标 API- Javascript 代码 谷歌      更新时间:2023-09-26

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

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

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

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

注意:这是异步的本质,所以不要试图将其放在返回语句

中返回results[0].geometry.location的函数中

试试这个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