Last active
June 2, 2023 11:18
-
-
Save pedrohma/11f425655b534fa729fb931b1db47db0 to your computer and use it in GitHub Desktop.
Getting Zip Code by GeoLocation using Google Maps API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getLocation() { | |
if (navigator.geolocation) { | |
navigator.geolocation.getCurrentPosition(showPosition); | |
} else { | |
alert("Sorry, but Geolocation is not supported by this browser."); | |
} | |
} | |
function showPosition(position) { | |
var lat = position.coords.latitude; | |
var long = position.coords.longitude; | |
var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + long + "&key=YOUR_API_KEY"; | |
$.ajax({ | |
type: "GET", | |
url: url, | |
dataType: "json", | |
success: function (msg) { | |
var results = msg.results; | |
var zip = results[0].address_components[6].long_name; | |
alert("Your zip code is: " + zip); | |
}, | |
error: function (req, status, error) { | |
alert('Sorry, an error occurred.'); | |
console.log(req.responseText); | |
} | |
}); | |
} |
Updated! Thanks @veeren 👍
Hey How Can I work this in Mozila and Internet explorer. This is worked fine for me in crome and Edage.Thanks!
@nusratnazmi
Seems like IE is not supported, however they have a new version for Edge.
https://support.mozilla.org/en-US/questions/1293707
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var zip = results[0].address_components[7].long_name;
Update this line withvar zip = results[0].address_components[6].long_name;