views:

3570

answers:

2

I need a function to get an nearest address or city from coordinates(lat,long) using google map api reverse geocoding and php... Please give some sample code

+4  A: 

You need to use the getLocations method on the GClientGeocoder object in the Google Maps API

var point = new GLatLng (43,-75);
var geocoder = new GClientGeocoder();
geocoder.getLocations (point, function(result) {
    // access the address from the placemarks object
    alert (result.address);
    });

You can find a working example of this here. This example is also doing walking directions between two points, but if you have a look at the getLocations call in the dragend listener it does the geocode each time the end point is moved.

EDIT: Ok. You are doing this stuff server side. This means you need to use the HTTP Geocoding service. To do this you will need to make an HTTP request using the URL format described in the linked article. You can parse the HTTP response and pull out the address:

// set your API key here
$api_key = "";
// format this string with the appropriate latitude longitude
$url = 'http://maps.google.com/maps/geo?q=40.714224,-73.961452&output=json&sensor=true_or_false&key=' . $api_key;
// make the HTTP request
$data = @file_get_contents($url);
// parse the json response
$jsondata = json_decode($data,true);
// if we get a placemark array and the status was good, get the addres
if(is_array($jsondata )&& $jsondata ['Status']['code']==200)
{
      $addr = $jsondata ['Placemark'][0]['address'];
}

N.B. The Google Maps terms of service explicitly states that geocoding data without putting the results on a Google Map is prohibited.

Cannonade
Thanks. I need the code in PHP because im going to show the address of latitude and longtitude in reports as records... please just me..
boss
boss, part of being a programmer is the ability to abstract source code to your language. The Google Location Api is essentially the same in all used languages (including the GLatLng Syntax)
Henrik P. Hessel
@Cannonade: I don't want to answer just to include the php sample code. Just a hint: there are a lot of php wrapper classes for the javascript api out there.
Henrik P. Hessel
Thanks Henrik. The ones I have seen just seem to wrap up the HTTP request. I'll post a sample as soon as I get a chance to try one out. Feel free to post if you have the time :).
Cannonade
A: 

The 'address' return is actually: $jsondata ['Placemark'][0]['address'];

Connor