Reputation: 61
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
Reputation: 16963
There are few issues with the $url
itself, such as:
http
in the URL, whereas you should use https
.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:
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