11
votes

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

2
so, your question is "How to parse the JSON" ?Raptor
yes! That is, ho I can parse the array with JS?Tab

2 Answers

19
votes

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>
5
votes

In HTML5 page we can get city name as follows:

<script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script>
        (function() {

            if(!!navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {

                  var geocoder = new google.maps.Geocoder();
                  var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

                  console.log(position.coords.latitude + ', ' + position.coords.longitude);

                  geocoder.geocode({'latLng': geolocate}, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                       var result;
                       if (results.length > 1) {
                         result = results[1];
                       } else {
                         result = results[0];
                       }
                       //console.log(result);
                       console.log(result.address_components[2].long_name + ', ' + result.address_components[3].long_name);

                     }  
                  });    
                });
</script>