I use google maps api 3 to get city from coordinates. I read the ReverseGeocoding but I did not understand how to have the correct city value from this type of result: http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false
this Funktion returns the Name of a requested City at lat/long. As this Script is from end of 2012. Worked fine for me that time. Returns "unknown" when the API doesn't find any.
function get_api ($lat, $long) {
$get_API = "http://maps.googleapis.com/maps/api/geocode/json?latlng=";
$get_API .= round($lat,2).",";
$get_API .= round($long,2);
$jsonfile = file_get_contents($get_API.'&sensor=false');
$jsonarray = json_decode($jsonfile);
if (isset($jsonarray->results[1]->address_components[1]->long_name)) {
return($jsonarray->results[1]->address_components[1]->long_name);
}
else {
return('Unknown');
}
}
edit: and a jquery.
<p id="city"></p>
<script>
$(document).ready( function () {
// define lat / long
var lat = 37.42;
var long = -122.08;
$.ajax({
type: 'GET',
dataType: "json",
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&sensor=false",
data: {},
success: function(data) {
$('#city').html(data);
$.each( data['results'],function(i, val) {
$.each( val['address_components'],function(i, val) {
if (val['types'] == "locality,political") {
if (val['long_name']!="") {
$('#city').html(val['long_name']);
}
else {
$('#city').html("unknown");
}
console.log(i+", " + val['long_name']);
console.log(i+", " + val['types']);
}
});
});
console.log('Success');
},
error: function () { console.log('error'); }
});
});
</script>