PHP + Google API Geocode

Asked

Viewed 1,621 times

5

Follow the method code:

function GetGeoCode($address) {
    $geo= array();

    $geocode = file_get_html('http://maps.google.com/maps/api/geocode/json?address=' . $address . '&sensor=false');
    $output = json_decode($geocode);
    echo 'http://maps.google.com/maps/api/geocode/json?address=' . $address . '&sensor=false';
    $lat = $output->results[0]->geometry->location->lat;
    $long = $output->results[0]->geometry->location->lng;

    $geo['lat']=$lat;
    $geo['long']=$long;

    return $geo;
}

The objective of this method is to return the latitude and longitude according to a given address inserted as parameter. However, after performing the test with some addresses the error of not returning the data. I performed the test to copy the created url and paste in the browser, which worked correctly.

Can anyone tell me why this happens ?

1 answer

2


I performed some tests, first, instead of file_get_html I used in the code below file_get_contents, but what I realized in the test at least using this method, is that you need to send the parameter with the spaces replaced by +, I also noticed that using accents returns NULL, this way was solved with the code below with explanation in own comment.

$geo= array();
$a = "Rua Paulo Guimarães, São Paulo - SP"; // Pega parâmetro
$addr = str_replace(" ", "+", $a); // Substitui os espaços por + "Rua+Paulo+Guimarães,+São+Paulo+-+SP" conforme padrão 'maps.google.com'
$address = utf8_encode($addr); // Codifica para UTF-8 para não dar 'pau' no envio do parâmetro

// Daqui em diante é o seu código original
$geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address=' . $address . '&sensor=false');
$output = json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;

$geo['lat']=$lat;
$geo['long']=$long;

echo "<pre> Latitude: ";
print_r($geo['lat']);
echo "<br /> Longitude: ";
print_r($geo['long']);
echo "<br /><br /> Resultado completo JSON: <br /><br />";
print_r($output);

I did not test your code to understand what was happening, but from what I could see the problem should be in the sending (format) of the parameter.

Anyway, I suggest you take a little time to read this so that we don’t have to do this type of 'gambiarra' and there is a fully documented API with numerous possibilities, so also it will not be limited if you want to increase its functionality.

Suggested reading: The Google Mas Geocoding API

  • Thanks. I made some changes here according to what you sent me and it worked. However I will even follow the dirt of reading the documentation as there are still some exceptions that still do not return. My code is very ugly and very funny.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.