Skip to content

Instantly share code, notes, and snippets.

@B-PRAVEEN
Forked from danasilver/citystategeo.js
Created September 13, 2018 21:19
Show Gist options
  • Save B-PRAVEEN/4f7e79d0d332768fa6150df1a9adfb7f to your computer and use it in GitHub Desktop.
Save B-PRAVEEN/4f7e79d0d332768fa6150df1a9adfb7f 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.")});
}
@B-PRAVEEN
Copy link
Author

if (resp.status == 'OK') {
	if (resp.results[1]) {
		var city=false,state=false;
		for (var i = 0; i < resp.results.length; i++) {
			if ((!city || !state) && resp.results[i].types[0] === "locality") {
				city = resp.results[i].address_components[0].short_name,
				state = resp.results[i].address_components[2].short_name;
				res = city + ", " + state;
			}
		}
	}
}

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