【发布时间】:2017-03-16 09:40:10
【问题描述】:
我正在尝试从谷歌反向地理编码 api 获取城市名称,我的代码显示该位置的完整地址,但我只需要城市。下面是我的代码
<?php
session_start();
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
//Send request and receive json data by latitude and longitude
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
$json = @file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if($status=="OK"){
//Get address from json data
//$location = $data->results[0]->formatted_address;
$location = $data->results[0]->address_components;
}else{
$location = '';
}
//Print city
$_SESSION['getgeoloc']=$location[6]->long_name;
echo $location;
}
?>
我尝试使用以下代码显示城市,但有时显示邮政编码,有时显示城市名称
$_SESSION['getgeoloc']=$location[6]->long_name;
有没有最好的方法?
【问题讨论】:
-
我认为这是因为每个位置都有不同类型的数据,并且在其中形成不同的数组。不是吗?
-
是的,那么如何从中获取应用城市名称
-
这是一个有点困难的任务,因为你必须做一些正则表达式的事情
标签: php google-maps reverse-geocoding