Xinee
Xinee

Reputation: 61

Converting GPS coordinates captured to address in PHP

I want to change real-time coordinates captured from my google maps to address.

I've tried the following code:

<?php

$lat="9.102097";
$long="-40.187988";
geo2address($lat,$long);

function geo2address($lat,$long) {

$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&sensor=false";
$curlData=file_get_contents(    $url);
$address = json_decode($curlData);
$a=$address->results[0];
return explode(",",$a->formatted_address);
print_r($address);
}

?>

P.S. I'm testing with a fixed coordinates but will capture coordinates from my application when I success

I referenced the code from How to convert GPS coordinates to a full address with php? but it is not working.

Upvotes: 2

Views: 1904

Answers (1)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

There are few issues with the $url itself, such as:

  • You're using http in the URL, whereas you should use https.
  • You're not using key parameter in the URL. Sign up for an API KEY and use it in the URL.

Here's an example of one such URL:

https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY`

Here's the documentation of reverse geocoding:

So your code should be like this:

$lat="40.714224";
$long="-73.961452";
geo2address($lat,$long);

function geo2address($lat,$long) {
    $url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&key=YOUR_API_KEY";
    $json = json_decode(file_get_contents($url), true);
    $a = $json['results'][0]['formatted_address'];
    print_r(explode(",",$a));
}

Few points to note here is:

  • The latitude and longitude are taken from the documentation itself.
  • Pass the second parameter as true in the json_decode() function to convert it into associative array. It will be then easy for you to access individual components.

Upvotes: 1

Related Questions