Skip to content

Instantly share code, notes, and snippets.

@ihorduchenko
Created March 17, 2022 15:52
Show Gist options
  • Save ihorduchenko/85f554f6029a69a8debe6b2a49ef00fe to your computer and use it in GitHub Desktop.
Save ihorduchenko/85f554f6029a69a8debe6b2a49ef00fe to your computer and use it in GitHub Desktop.
Detect user's location using Geolocation API and Google Maps Javascript API
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuyuXzFTTgV7BestKhgKrrZjV_-rMmUQY&callback=geoFindMe&v=weekly&channel=2"
async
></script>
<script>
function reverseGeocodingWithGoogle(latitude, longitude) {
const latlng = {
lat: parseFloat(latitude),
lng: parseFloat(longitude),
};
const geocoder = new google.maps.Geocoder();
geocoder
.geocode({ location: latlng })
.then((response) => {
if (response) {
console.log(response)
} else {
window.alert("No results found");
}
})
.catch((e) => console.log("Geocoder failed due to: " + e));
}
function geoFindMe() {
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
if (!navigator.geolocation){
console.log('Geolocation is not supported by your browser');
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
reverseGeocodingWithGoogle(longitude, latitude, options)
}
function error() {
console.log('Unable to retrieve your location');
}
navigator.geolocation.getCurrentPosition(success, error);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment