How to get geolocation or latitude and longitude information with javascript!


05 Jul 2018views: 185


blog cover image

Geolocation refers to the identification of the geographic location of a user or computing device via a variety of data collection mechanisms. Typically, most geolocation services use network routing addresses or internal GPS devices to determine the users location.

Geolocation commonly uses Global Positioning System (GPS) and other related technologies to assess and specify geographical locations. The HTML Geolocation API is used to get the geographical position of a user. Since this can compromise privacy, the position is not available unless the user approves it.

The first step to get location information about a user is getting permission from the user. This allows the web app to get the geographical coordinates of the user or device. The accuracy depends on the device as GPS enabled mobile devices gives precise information while computers without GPS feature provides results with deviations.

To get the permission from the user or device navigator.geolocation have to be called from javascript which will ask the user for permission.





And then navigator.geolocation.getCurrentPosition(showPosition); to get the location information.

The complete script is shown below:


<script type="text/javascript">
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    temp_lat = 0.0; //set default lat value
    temp_lng = 0.0; //set default lng value
  }
}

function showPosition(position) {
  temp_lat = position.coords.latitude;
  temp_lng = position.coords.longitude;
  $("#loc_lat").html('<p align="justify">Lat:'+temp_lat+'</p>');
  $("#loc_lng").html('<p align="justify">Lng:'+temp_lng+'</p>');
}
</script>

Now to get the geolocation information, we just need to call the getLocation() function. The above code also uses Jquery to display the results. So the last step is to build a button which will call getLocation() function. That is also very simple here shown below.

<button id="loc_btn" name="loc_btn" onclick="getLocation()" class="btn btn-info mb-2">Auto Detect</button>

<div id="loc_lat"></div>
<div id="loc_lng"></div>

Techconductor/Weather uses the above code. Check the above link to see how it works.






Thank you for Subscribing! We will make sure you never miss a thing.



author-avatar

Om Prakash Mahato

Full stack developer, author, founder of TechConductor.


0 Comments:


    Leave a comment:


    Name is ok.
    Comment is ok.
    Email is ok.
    Website is ok.