abc

Share This blog with your friends, so that we can improve more & more . our aim is to easy & simple way of learning.

12/13/2020

how to get geolocation with latitude and longitude

 ask browser to allow location


function getLocation() {

  if (navigator.geolocation) {

    navigator.geolocation.getCurrentPosition(showPosition);

  } else { 

    x.innerHTML = "Geolocation is not supported by this browser.";

  }

}


using position.coords.latitude & position.coords.longitude we can get exact position in map


useful when adding google map to website or app, also track geolocation

no any other script or file required.


<!DOCTYPE html>

<html>

<body>


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


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


<p><strong>Note:</strong> The geolocation property is not supported in IE8 and earlier versions.</p>


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


<script>

var x = document.getElementById("demo");


function getLocation() {

  if (navigator.geolocation) {

    navigator.geolocation.getCurrentPosition(showPosition);

  } else { 

    x.innerHTML = "Geolocation is not supported by this browser.";

  }

}


function showPosition(position) {

  x.innerHTML = "Latitude: " + position.coords.latitude + 

  "<br>Longitude: " + position.coords.longitude;

}

</script>


</body>

</html>

Useful links 

1) to get latitude and longitude - https://www.latlong.net/

2) google map API - https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=myMap



No comments:

Post a Comment

An Introduction to the Laravel Framework: What It Is and Why You Should Use It

  If you're a PHP developer looking for a modern, efficient, and powerful framework to build web applications, look no further than Lara...