Home  >  Q&A  >  body text

Maps Google API returns wrong coordinates

<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粉773659687P粉773659687428 days ago414

reply all(1)I'll reply

  • P粉386318086

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

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

    reply
    0
  • Cancelreply