I was interested in getting my current address using Javascript and just figured this out by assembling some other SO threads (1,2) so wanted to post this question and answer.
Please see answer below.
Answer: Use the window. location. href Property You can use the JavaScript window. location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc. The following example will display the current url of the page on click of the button.
The JavaScript Geolocation API provides access to geographical location data associated with a user's device. This can be determined using GPS, WIFI, IP Geolocation and so on. To protect the user's privacy, it requests permission to locate the device.
One way to find your geolocation is to simply perform a lookup online. Melissa's Geocoder Lookup tool returns latitude, longitude, county, census tract and block data based on an address or ZIP Code. Simply enter the address or ZIP Code into the easy-to-use Lookups interface and submit.
Get Current Position Get the current position of the user using the navigator. getCurrentPosition() method. Open the console, and the output should look like this. The xxx can be any number based on the location.
Here's the HTML:
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<p id='latitudeAndLongitude'></p>
<p id='address'></p>
Here's the JS:
var latitudeAndLongitude=document.getElementById("latitudeAndLongitude"),
location={
latitude:'',
longitude:''
};
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
latitudeAndLongitude.innerHTML="Geolocation is not supported by this browser.";
}
function showPosition(position){
location.latitude=position.coords.latitude;
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(location.latitude, 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With