Skip to content

Instantly share code, notes, and snippets.

@danasilver
Created July 17, 2013 20:11
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save danasilver/6024009 to your computer and use it in GitHub Desktop.
Save danasilver/6024009 to your computer and use it in GitHub Desktop.
Get only city and state from Google Maps API Reverse Geocoder
if (window.navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var lat = position.coords.latitude,
lng = position.coords.longitude,
latlng = new google.maps.LatLng(lat, lng),
geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
for (var i = 0; i < results.length; i++) {
if (results[i].types[0] === "locality") {
var city = results[i].address_components[0].short_name;
var state = results[i].address_components[2].short_name;
$("input[name='location']").val(city + ", " + state);
}
}
}
else {console.log("No reverse geocode results.")}
}
else {console.log("Geocoder failed: " + status)}
});
},
function() {console.log("Geolocation not available.")});
}
@l0c0luke
Copy link

this did not work for me ... try this...

for (var ac = 0; ac < results[0].address_components.length; ac++) {
                                    var component = results[0].address_components[ac];

                                    switch(component.types[0]) {
                                        case 'locality':
                                            storableLocation.city = component.long_name;
                                            break;
                                        case 'administrative_area_level_1':
                                            storableLocation.state = component.short_name;
                                            break;
                                        case 'country':
                                            storableLocation.country = component.long_name;
                                            storableLocation.registered_country_iso_code = component.short_name;
                                            break;
                                    }
                                };

@unaibamir
Copy link

Hey l0c0luke

Apologize for late reply but you solution just rocked man. Than you so much.

@mfgulshani
Copy link

Hey l0c0luke,

Your code worked for me. Thank you.

@dody87
Copy link

dody87 commented Aug 11, 2017

Great job!!

I've forked it in order to make some improvements just in the case that you need city + state once. There is the link if someone needs: https://gist.github.com/dody87/12897208a72147c2319c0bf7cbc200ad

Thanks.

@abrambailey
Copy link

@l0c0luke Nice work.

@edurodriguesdias
Copy link

Thank's for share!

@celsowhite
Copy link

@l0c0luke thanks I had to modify your code a bit because I was finding that the first parameter in the types array wasn't always the one we were looking for in the switch statement. For example the types array that includes sublocality looked like this ["political", "sublocality", "sublocality_level_1"]. The Array.includes() method helped improve accuracy.

I also wasn't able to find 'locality' as an array element. Google labeled my city as a 'sublocality'.

let storableLocation = {};

for (var ac = 0; ac < results[0].address_components.length; ac++) {
    
   var component = results[0].address_components[ac];
    
   if(component.types.includes('sublocality') || component.types.includes('locality')) {
        storableLocation.city = component.long_name;
   }
   else if (component.types.includes('administrative_area_level_1')) {
        storableLocation.state = component.short_name;
   }
   else if (component.types.includes('country')) {
        storableLocation.country = component.long_name;
        storableLocation.registered_country_iso_code = component.short_name;
   }

};

@aliciakott
Copy link

@celsowhite This worked for me, thanks!

@amos80m
Copy link

amos80m commented Sep 10, 2018

@celsowhite Thanks

@heldr
Copy link

heldr commented Jun 18, 2019

London-UK requires postal_town after locality

@rickyriccs
Copy link

rickyriccs commented Feb 13, 2020

There is no accuracy to build combination of city_name with their state_name, I have try to build below code for with accuracy. Its work for Multiple Countries... Try it and give review also....

var x, lat, lng, city, state, country, geocoder, latlng;

$(document).ready(function() {
    getLocation();
});

x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    lat = position.coords.latitude;
    lng = position.coords.longitude;
    // inprange = parseInt($('#range_3').prop("value") * 1000);
    geocodeLatLng(lat, lng);
}

function showError(error) {
    switch (error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation.";
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable.";
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out.";
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred.";
            break;
    }
}

function geocodeLatLng(lat, lng) {
    geocoder = new google.maps.Geocoder();
    latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({
        'latLng': latlng
    }, function(results, status) {
        if (status === 'OK') {
            if (results[1]) {
                console.log(results);
                for (var i = 0; i < results[0].address_components.length; i++) {
                    for (var b = 0; b < results[0].address_components[i].types.length; b++) {
                        switch (results[0].address_components[i].types[b]) {
                            case 'locality':
                                city = results[0].address_components[i].long_name;
                                break;
                            case 'administrative_area_level_1':
                                state = results[0].address_components[i].long_name;
                                break;
                            case 'country':
                                country = results[0].address_components[i].long_name;
                                break;
                        }
                    }
                }
                x.innerHTML = 'City = ' + city + ', ' + 'State = ' +  state + ', ' + 'Country = ' +  country;
            } else {
                alert("No results found");
            }
        } else {
            alert("Geocoder failed due to: " + status);
        }
    });
}

@shubhamtakode
Copy link

@rickyriccs Thanks. Its working for me

@rjsnavarette
Copy link

@celsowhite thank you, it works.

@Slisarenko
Copy link

@celsowhite Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment