Abhayjeet Singh Abhayjeet Singh - 3 years ago 207
Javascript Question

how to return latitude and longitude of the user in Javascript?

I want to make return latitude and longitude of the current user from the function and I have written the following code but this piece of code is saying "undefined" as a result. If anybody knows the solution, please answer

<script>
function getLocation() {
if (navigator.geolocation) {
var lat_lng = navigator.geolocation.getCurrentPosition(showPosition);
console.log(lat_lng);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var user_position = {};
user_position.lat = position.coords.latitude;
user_position.lng = position.coords.longitude;
return user_position;
}
getLocation()
</script>

Answer Source

getCurrentPosition is executing asynchronous and console.log(lat_lng); is executed before you get the result from follow function:

navigator.geolocation.getCurrentPosition(showPosition);

You have to use a callback function instead.

function getLocation(callback) {
    if (navigator.geolocation) {
        var lat_lng = navigator.geolocation.getCurrentPosition(function(position){
        console.log(position);
          var user_position = {};
          user_position.lat = position.coords.latitude; 
          user_position.lng = position.coords.longitude; 
          callback(user_position);
        });
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}
getLocation(function(lat_lng){
  console.log(lat_lng);
});

Working solution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download