Get address from latlng php
Show
Hi! Today let's see how to get address from latitude and longitude using PHP and Google Maps Geocoding API. In general, the process of converting geometric coordinates such as latitude and longitude into address is called reverse geocoding. And the geocoding is just the opposite, converting address into latitude and longitude which we have seen in our previous tutorial. Google Maps provides a separate Geocoding API for the purpose and let's see how to use it with php. To obtain physical addresses from the API, you have to send http request along with latitude and longitude values. Getting Address from Latitude and Longitude using Google Maps:To access Google Maps Geocoding API, you need an http interface through which you can send and receive an http request/response from the api. Here is the sample request you should send to the web service. http://maps.google.com/maps/api/geocode/json?latlng=40.6781784,-73.9441579 The 'latlng' parameter must be used to provide latitude, longitude values in the url. Also, to get the response as json, you must be specific on your api call. Below is the reverse geocoding sample response that we get for the above api request, {
"results" : [
{
"address_components" : [
{
"long_name" : "58",
"short_name" : "58",
"types" : [ "street_number" ]
},
{
"long_name" : "Brooklyn Avenue",
"short_name" : "Brooklyn Ave",
"types" : [ "route" ]
},
{
"long_name" : "Crown Heights",
"short_name" : "Crown Heights",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "Brooklyn",
"short_name" : "Brooklyn",
"types" : [ "political", "sublocality", "sublocality_level_1" ]
},
{
"long_name" : "Kings County",
"short_name" : "Kings County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "New York",
"short_name" : "NY",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "11216",
"short_name" : "11216",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "58 Brooklyn Ave, Brooklyn, NY 11216, USA",
"geometry" : {
"location" : {
"lat" : 40.677978,
"lng" : -73.94438700000001
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 40.67932698029149,
"lng" : -73.94303801970851
},
"southwest" : {
"lat" : 40.6766290197085,
"lng" : -73.94573598029152
}
}
},
"place_id" : "ChIJaVKlrIVbwokRhqlQjSdxUHc",
"types" : [ "street_address" ]
},
...
...
],
"status" : "OK"
}
The response sends a PHP Function to Convert Latitude and Longitude into Address:Below is the php function to get the address details of the given geographic co-ordinates. You must pass longitude and latitude to the function which in turn makes http request to the api, receive json response, parse and return the formatted address. results[0]->formatted_address;
return $address;
}
?>
|
