Get user location (latitude & longitude) using Javascript

Most of the browsers are capable to detect user’s locations through GPS,WIFI or IP geolocation. You can store these details to provide better service to the user according their location like finding nearby hotels, hospitals etc.

Here i will explain to get user’s locations with native javascript.Javascript provide this service from geolocation api.

Most of the current browser supports the API. Any how we will check web development side for the Geolocation API availability.

if (navigator.geolocation) {
  // geolocation is available
else {
  // geolocation is not supported

Then, get user current location with Geolocation.getCurrentPosition()

navigator.geolocation.getCurrentPosition(function(position) {
	/*coords: {
            latitude - Geographical latitude in decimal degrees.
            longitude - Geographical longitude in decimal degrees. 
            altitude - Height in meters relative to sea level.
            accuracy - Possible error margin for the coordinates in meters. 
            altitudeAccuracy - Possible error margin for the altitude in meters. 
            heading - The direction of the device in degrees relative to north. 
            speed - The velocity of the device in meters per second.
        timestamp - The time at which the location was retrieved.*/

Leave a Reply

Your email address will not be published. Required fields are marked *