Skip to content

Instantly share code, notes, and snippets.

@bomsn
Last active March 11, 2024 16:22
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bomsn/ca43368ff4cd554a612871ddfa18c4c9 to your computer and use it in GitHub Desktop.
Save bomsn/ca43368ff4cd554a612871ddfa18c4c9 to your computer and use it in GitHub Desktop.
Get User Postal Code ( Zip Code ) with Browser Geolocation & Google API
// jQuery must be loaded before calling this function ( for AJAX )
let getUserPostcode = () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
let lat = position.coords.latitude,
long = position.coords.longitude,
url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + long + "&key=YOUR_GOOGLE_API_KEY";
$.ajax({
type: "GET",
url: url,
dataType: "json",
success: function (response) {
let results = response.results,
postalCode = '';
if (results[0]) {
for (let i = 0; i < results[0].address_components.length; i++) {
let types = results[0].address_components[i].types;
for (let typeIdx = 0; typeIdx < types.length; typeIdx++) {
if (types[typeIdx] == 'postal_code') {
postalCode = results[0].address_components[i].long_name;
break;
}
}
if (postalCode !== '') {
break;
}
}
}
alert(postalCode);
},
error: function (req, status, error) {
alert('Sorry, there was an error.');
}
});
},
(error) => {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.");
break;
case error.TIMEOUT:
alert("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.");
break;
}
}
);
} else {
alert("Sorry, Geolocation is not supported by your browser.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment