Check the user’s location with GPS

Get the coordinates of a user’s device in longitude and latitude

To get the user’s location you can use HTML5 Geolocation which is supported on all modern browsers and mobile devices (though a user may choose to conceal their location). The example code below looks up the user’s location and creates two variables that you can use with the longitude and latitude coordinates:

JavaScript


navigator.geolocation.getCurrentPosition(function onShowPosition(position) {
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;
}, function onError(error) {
  var errorMessage = error.message;
});

Taking this example further, we’ll use the user’s location to place a marker on a Google map or let a user share it as a URL with others. See the code below:

JavaScript


function getLocation() {
  // Here we are getting the user’s location and passing it to the showPosition function
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, onError);
  } else {
    alert('Geolocation is not supported by this browser.');
  }
}

function showPosition(position) {
  // Here we using the location to create a URL for a Google map
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;
  var latlong = latitude + ',' + longitude;
  var mapUrl = 'https://www.google.com/maps?q=' + latlong;


  // We let the user decide if they want to open the URL or
  // Share the URL with someone else
  Fliplet.UI.Actions({
    title: 'What do you want with this address?',
    labels: [{
        label: 'Open in Google Maps',
        action: {
          action: 'url',
          url: mapUrl
        }
      },
      {
        label: 'Share URL',
        action: function () {
          Fliplet.Communicate.shareURL(mapUrl);
        }
      }
    ],
    cancel: 'Dismiss'
  });
}

function onError(error) {
  // If there’s an error with retrieving the geolocation data we can do something here eg display an error message
  var errorMessage = error.message;
}


// Above we’ve only been defining the code
// We actually start it running with the command below
getLocation();

The above code is only called once, when the user opens the app or navigates to a screen that contains the code. If you would like to repeatedly call the code (ie, to continuously check a user’s location as they move) you would change navigator.geolocation.getCurrentPosition() to navigator.geolocation.watchPosition()

This will repeatedly send requests to get a user’s location. While this can be helpful it can also be a drain on a mobile devices battery. So it’s important to stop watching for a user’s location when we no longer need to.

To stop watching for location changes you can use the following code (this will also happen if a user navigates to another screen)

JavaScript


navigator.geolocation.clearWatch();