Skip to content

Instantly share code, notes, and snippets.

@raazon
Last active July 1, 2019 06:39
Show Gist options
  • Save raazon/80fc566c3712cc3e104e42cd8d62a862 to your computer and use it in GitHub Desktop.
Save raazon/80fc566c3712cc3e104e42cd8d62a862 to your computer and use it in GitHub Desktop.
Get my current address using javascript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Get my current address using javascript</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- ref: https://stackoverflow.com/questions/14580715/get-my-current-address-using-javascript#answer-14580801 -->
<p id="latitudeAndLongitude"></p>
<p id="address"></p>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBNrASOuKNnXr4a5rEqDC_8fo_isduYSeU&libraries=places"></script>
<script>
var latitudeAndLongitude = document.getElementById("latitudeAndLongitude"),
get_location = {
latitude: '',
longitude: ''
};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
latitudeAndLongitude.innerHTML = "Geolocation is not supported by this browser.";
}
function showPosition(position) {
get_location.latitude = position.coords.latitude;
get_location.longitude = position.coords.longitude;
latitudeAndLongitude.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(get_location.latitude, get_location.longitude);
if (geocoder) {
geocoder.geocode({
'latLng': latLng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].formatted_address);
$('#address').html('Address: ' + results[0].formatted_address);
} else {
$('#address').html('Geocoding failed: ' + status);
console.log("Geocoding failed: " + status);
}
}); //geocoder.geocode()
}
} //showPosition
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment