搜索

首页  >  问答  >  正文

Maps Google API返回错误的坐标

<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粉773659687P粉773659687476 天前464

全部回复(1)我来回复

  • P粉386318086

    P粉3863180862023-07-27 14:56:55

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

    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;
        }
    }

    回复
    0
  • 取消回复