Sunday 27 November 2016

Get geo location using javascript in destop and leptop or computer


Get geo location using javascript in destop and leptop or computer



 <p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(getAddress);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";}
    }
function getAddress(position){

  var lat = position.coords.latitude;
  var lon = position.coords.longitude;

  //grab address via Google API using your position
  var apiurl = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+lon+'&sensor=true';


  //make the Ajax request
  var xhr = new XMLHttpRequest();

  xhr.open("GET", apiurl);
  xhr.onload = function() {
  var result = JSON.parse(xhr.responseText)

    //if we make a successful request and it returns an address
  if(this.status==200){
  //get formatted address from https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding
  //var result = JSON.parse(xhr.responseText).contents.results[0].formatted_address;
  console.log(result.results[0]['formatted_address']);
alert(result.results[0]['formatted_address']);
      } else {
      //send some general error
     
      }

  }

  xhr.send();
               
}
</script>

Get geo location using javascript in destop and leptop or computer

No comments:

Post a Comment

Thank You For Comment