将捕获的GPS坐标转换为地址为PHP
问题描述:
我想将从我的谷歌地图捕获的实时坐标更改为地址。将捕获的GPS坐标转换为地址为PHP
我试过下面的代码:
<?php
$lat="9.102097";
$long="-40.187988";
geo2address($lat,$long);
function geo2address($lat,$long) {
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&sensor=false";
$curlData=file_get_contents( $url);
$address = json_decode($curlData);
$a=$address->results[0];
return explode(",",$a->formatted_address);
print_r($address);
}
?>
附:我使用固定坐标进行测试,但在成功时会从我的应用程序捕获坐标
我引用了How to convert GPS coordinates to a full address with php?的代码,但它不起作用。
答
没有与$url
本身一些问题,如:您使用的URL http
,而应该使用https
- 。
- 您没有在URL中使用
key
参数。注册一个API KEY并在URL中使用它。
这里有一个这样的URL的一个例子:
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY`
这里的反向地理编码的文档:
所以,你的代码应该是这样的:
$lat="40.714224";
$long="-73.961452";
geo2address($lat,$long);
function geo2address($lat,$long) {
$url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&key=YOUR_API_KEY";
$json = json_decode(file_get_contents($url), true);
$a = $json['results'][0]['formatted_address'];
print_r(explode(",",$a));
}
几点这里需要注意的是:
- 的经度和纬度,从文档本身服用。
- 将
true
中的第二个参数传递给json_decode()
函数,将其转换为关联数组。您将可以轻松访问各个组件。
@Xinee是的,你可以做到这一点。只要您调用此函数,只需将动态纬度和经度参数传递给'geo2address()'函数即可。 –
非常感谢!这个解决方案完美运作 – Xinee
@ Xinee很高兴我能帮到你。如果解决了您的问题,请*接受*答案。 [如何接受Stack Overflow的答案?](http://meta.stackexchange.com/a/5235) –