Last active
October 18, 2024 02:23
-
-
Save bomsn/ca43368ff4cd554a612871ddfa18c4c9 to your computer and use it in GitHub Desktop.
Get User Postal Code ( Zip Code ) with Browser Geolocation & Google API
This file contains hidden or 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
// 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