Get current city name via latitude and longitude using javascript

<p id="city"></p>


$(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'); } 
    }); 
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s