首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Google地理代码API - PHP中的Echo特定细节

Google地理代码API - PHP中的Echo特定细节
EN

Stack Overflow用户
提问于 2013-08-31 17:13:20
回答 2查看 1.3K关注 0票数 2

我正在使用这个脚本从Google获取地理代码信息,但我不知道如何过滤掉一些细节,比如Lat、Lon、Town、County。下面是我的代码(我认为它将在新的API-3下工作):

代码语言:javascript
复制
<?php
$address="LS1 7AS";
$result=file_get_contents("http://maps.google.com/maps/api/geocode/json?address=" . urlencode($address) . "&sensor=false" );
    $geocodedinfo=json_decode($result);

print_r($geocodedinfo);
?>

这会打印出我需要的所有信息,但作为一个块,我只想要其中的一些信息,这样我就可以将其插入到一个表中,例如:

代码语言:javascript
复制
$town = "town from result";
$county = "county from result";
$lat = "lat from result";
$lon = "lon from result";
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-08-31 17:55:53

首先,您需要修改API输出format.Use输出格式json,因为您已经使用了json_decode函数。

代码语言:javascript
复制
$address="LS1 7AS";
"http://maps.google.com/maps/api/geocode/json?address=" . urlencode($address) . "&sensor=false";

你的变量看起来应该是:

代码语言:javascript
复制
$geocodedinfo=json_decode($result);

您必须检查返回状态:

代码语言:javascript
复制
if($geocodedinfo->status == 'OK') {
     $country = $geocodeinfo->results[0]->address_components[3]->long_name;
     $town = $geocodeinfo->results[0]->address_components[2]->long_name;
     $lat = $geocodeinfo->results[0]->geometry->location->lat;
     $lon = $geocodeinfo->results[0]->geometry->location->lng;
}
票数 4
EN

Stack Overflow用户

发布于 2017-11-17 00:02:46

请试试这个:

代码语言:javascript
复制
$address="LS1 7AS";
$result = @file_get_contents("http://maps.google.com/maps/api/geocode/json?address=" . urlencode($address) . "&sensor=false" );
if ($result === FALSE) {
    //manage exception from file_get_contents call
} else {
    $geocodedinfo = json_decode($result);
    if ($geocodedinfo->status == "OK") {
        $county = "";
        $town = "";
        foreach ($geocodedinfo->results[0]->address_components as $addrcomps) {
            if ( $addrcomps->types[0] == 'postal_town')
                $town = $addrcomps->long_name;
            if ( $addrcomps->types[0] == 'administrative_area_level_2')
                $county = $addrcomps->long_name;
        }
        $lat = $geocodedinfo->results[0]->geometry->location->lat;
        $lon = $geocodedinfo->results[0]->geometry->location->lng;
    }
}

有时,file_get_contents函数调用会返回异常。因此,您应该在调用它之前使用@。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18550740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档