Maps Google API返回错误的坐标
P粉773659687
P粉773659687 2023-07-26 15:39:29
0
1
457
<p>我使用这个PHP函数来获取坐标,但它们总是错误的。有时候接近,有时候离正确的位置很远。</p> <pre class="brush:php;toolbar:false;">function getCoordinates($address, $city, $postalCode, $region, $province) { $url = 'https://maps.googleapis.com/maps/api/geocode/json?'; $params = array( 'address' => urlencode($address), 'components' => urlencode("locality:$city|administrative_area:$province"), 'key' => 'my_key' ); $url .= http_build_query($params); $response = file_get_contents($url); $data = json_decode($response, true); if ($data['status'] === 'OK') { $latitude = $data['results'][0]['geometry']['location']['lat']; $longitude = $data['results'][0]['geometry']['location']['lng']; return array('latitude' => $latitude, 'longitude' => $longitude); } else { return false; } }</pre> <p>我尝试以多种方式使用参数,但始终得到相同的结果:错误的坐标。</p><p>测试参数如下:</p><p><br /></p> <pre class="brush:php;toolbar:false;">$address = 'VIA DUCHESSA JOLANDA' $city = 'MONCRIVELLO' $province = 'VC' $postalcode = '13040'</pre> <p>结果是纬度:45.0742756,经度:7.6613655</p><p>而正确的应该是:纬度:45.3307055,经度:7.9960788</p><p><strong></strong></p>
P粉773659687
P粉773659687

全部回复(1)
P粉386318086

很抱歉,使用这个新版本后,坐标看起来是正确的。

function getCoordinates1($address, $city, $postalCode, $region, $province)
{
    $url = 'https://maps.googleapis.com/maps/api/geocode/json?';
    $addressString = "$address, $postalCode, $city, $province, $region";
    $params = array(
        'address' => urlencode($addressString),
        'key' => 'my-code'
    );
    $url .= http_build_query($params);
    $response = file_get_contents($url);
    $data = json_decode($response, true);
    if ($data['status'] === 'OK') {
        $latitude = $data['results'][0]['geometry']['location']['lat'];
        $longitude = $data['results'][0]['geometry']['location']['lng'];
        return array('latitude' => $latitude, 'longitude' => $longitude);
    } else {
        return false;
    }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!