Get City Name Using Google Geolocation

<script type=”text/javascript” src=”https://code.jquery.com/jquery-2.2.3.js”></script>

<script type=”text/javascript”>
    navigator.geolocation.getCurrentPosition(success, error);
    function success(position) {
        var GEOCODING = ‘https://maps.googleapis.com/maps/api/geocode/json?latlng=’ + position.coords.latitude + ‘%2C’ + position.coords.longitude + ‘&language=en’;
        jQuery.getJSON(GEOCODING).done(function(location) {
            jQuery(‘#country’).html(location.results[0].address_components[5].long_name);
            jQuery(‘#state’).html(location.results[0].address_components[4].long_name);
            jQuery(‘#city’).html(location.results[0].address_components[2].long_name);
            jQuery(‘#address’).html(location.results[0].formatted_address);
            jQuery(‘#latitude’).html(position.coords.latitude);
            jQuery(‘#longitude’).html(position.coords.longitude);
        })
    }
    function error(err) {
        console.log(err)
    }
</script>

Leave a Reply