Maps Google API returns wrong coordinates
P粉773659687
P粉773659687 2023-07-26 15:39:29
0
1
455
<p>I use this PHP function to get the coordinates but they are always wrong. Sometimes close, sometimes far from the right spot. </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>I tried using the parameters in many ways but always got the same result: wrong coordinates. </p><p>The test parameters are as follows:</p><p><br /></p> <pre class="brush:php;toolbar:false;">$address = 'VIA DUCHESSA JOLANDA' $city = 'MONCRIVELLO' $province = 'VC' $postalcode = '13040'</pre> <p>The result is latitude: 45.0742756, longitude: 7.6613655</p><p>The correct one should be: latitude: 45.3307055, longitude: 7.9960788</p><p><strong>< /strong></p>
P粉773659687
P粉773659687

reply all(1)
P粉386318086

Sorry, the coordinates look correct after using this new version.

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;
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!