我有一个函数试图从json数组中获取坐标。它让我难倒了,所以我希望有人能看到我的错误。
function getCoords($location){
$loc = urlencode($location);
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$loc&sensor=false";
//echo $url;
//echo file_get_contents($geo_url);
$json_result = json_decode(file_get_contents($url));
$geo_result = $json_result->results[0];
$aCsv = $geo_result->geometry->location;
//see if the it is locating the real address or just apox location, or in most cases a bad address
if($aCsv->location[0] == 200) {
return array('lat'=>(float)$aCsv[2], 'lng'=>(float)$aCsv[3], 'prec'=>(int)$aCsv[1]);
}
var_dump($aCsv);
}
var 转储在下面,我需要以这种格式提取 lat 和 lng 42.3584308,-71.0597732、21.3069444、-157.8583333
object(stdClass)#12 (2) { ["lat"]=> float(42.3584308) ["lng"]=> float(-71.0597732) } object(stdClass)#6 (2) { ["lat"]=> float(21.3069444) ["lng"]=> float(-157.8583333) }
我认为这部分是我遇到问题的地方
if($aCsv->location[0] == 200) {
return array('lat'=>(float)$aCsv[2], 'lng'=>(float)$aCsv[3], 'prec'=>(int)$aCsv[1]);
蒂亚·史蒂夫
伙计们有没有办法在函数之外访问 JSON 数据?我想获取正在解析的实际地址,并在结果计算中显示出来。
有时谷歌地图不使用确切的位置,例如,如果我输入KLAX - 洛杉矶机场,如果使用德国的地址,但如果我输入LAX,它使用洛杉矶机场,所以很高兴看到解析的地址。
我可以回显在函数内解析的地址,但是当我尝试在函数外部使用它时,它是 NULL。再次感谢您的帮助。史蒂夫
树木和树林?你已经有了!!
function getCoords($location){
$loc = urlencode($location);
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$loc&sensor=false";
$json_result = json_decode(file_get_contents($url));
$geo_result = $json_result->results[0];
$aCsv = $geo_result->geometry->location;
echo 'lat : '.$aCsv->lat.'<br>';
echo 'lng : '.$aCsv->lng.'<br>';
}
getCoords('alabama');
输出
纬度 : 32.3182314
液化天然气 : -86.902298
试试这个
$data = json_decode($ResponseData);
if('OK' === $data->status){
$latitude = $data->results['0']->geometry->location->lat;
$longitude = $data->results['0']->geometry->location->lng;
}
使用关联数组更容易,因此您可以使用以下内容:
$json_result = json_decode(file_get_contents($url),true)
(http://php.net/manual/de/function.json-decode.php)
然后,这些值可用于:
$json_result["lng"]
等。
使用这个
$geocode = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$loc.'&sensor=true');
$output = json_decode($geocode);
if($output->results)
{
foreach($output as $data)
{
$lat = $data[0]->geometry->location->lat;
$long = $data[0]->geometry->location->lng;
$location = $data[0]->formatted_address;
}
}