Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get my current address using javascript

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.

like image 913
tim peterson Avatar asked Jan 29 '13 10:01

tim peterson


People also ask

How do I get the current URL?

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.

Can JavaScript get location?

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.

How do I find the geocode of an address?

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.

How do I get current location in react JS?

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.


1 Answers

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
like image 153
tim peterson Avatar answered Oct 21 '22 03:10

tim peterson