使用Google地图API和PHP进行反向地理编码以获取最近位置的经纬度坐标

15

我需要一个使用Google地图API逆向地理编码和PHP获取最近地址或城市的函数...请提供一些示例代码

1个回答

34

你需要在GClientGeocoder对象上使用getLocations方法,在Google Maps API中。

var point = new GLatLng (43,-75);
var geocoder = new GClientGeocoder();
geocoder.getLocations (point, function(result) {
    // access the address from the placemarks object
    alert (result.address);
    });

编辑: 好的,你正在服务器端执行此操作。这意味着你需要使用HTTP地理编码服务。要做到这一点,你需要使用链接文章中描述的URL格式进行HTTP请求。你可以解析HTTP响应并提取地址:

// set your API key here
$api_key = "";
// format this string with the appropriate latitude longitude
$url = 'http://maps.google.com/maps/geo?q=40.714224,-73.961452&output=json&sensor=true_or_false&key=' . $api_key;
// make the HTTP request
$data = @file_get_contents($url);
// parse the json response
$jsondata = json_decode($data,true);
// if we get a placemark array and the status was good, get the addres
if(is_array($jsondata )&& $jsondata ['Status']['code']==200)
{
      $addr = $jsondata ['Placemark'][0]['address'];
}

注意:Google Maps服务条款明确规定,未将地理编码数据显示在Google Map上是被禁止的。

您可以在Google Map上显示Geocoding API结果,也可以不用地图直接显示。如果您想在地图上显示Geocoding API结果,则这些结果必须显示在Google Map上。禁止在非Google地图上使用Geocoding API数据。


8
作为程序员的一部分,能够将源代码抽象化到你所使用的编程语言是很重要的。Google位置API在所有使用的编程语言中基本上是相同的(包括GLatLng语法)。 - Henrik P. Hessel
谢谢 Henrik。我看到的那些似乎只是封装了HTTP请求。我会尽快发布一个样例,如果你有时间,请随意发布 :)。 - RedBlueThing
1
这段代码对我非常有用。我是 PHP 的新手,所以我想问一下如何将地址语言转换为另一种语言? - iremce
1
请看这里:https://developers.google.com/maps/documentation/geocoding/?csw=1#ReverseGeocoding API已经更改。 - Parixit
谢谢,只是一个升级... $lat = $_SESSION['lat']; $lng = $_SESSION['lng']; $googleURL = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$lng.'&key='. $api_key; - Carlos Galeano
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接