1

I am currently working on my project in Laravel. I need to get the information about the user (primarily his location) for my application to run smoothly; so I researched for some time and learned about Geolocation. I have the following code that finds the location of the user:

var location;
var latitude;
var longitude;




 function findLocation() {
  var geoSuccess = function(position) {
    location = position;
    latitude = location.coords.latitude;
    longitude = location.coords.longitude;
    console.log("Latitude is " + location.coords.latitude);
    console.log("Longitude is " + location.coords.longitude);
  };
  navigator.geolocation.getCurrentPosition(geoSuccess);
};

The thing is, the user needs to provide his location in order to register his account. So, when the user forbids the location permission, I want to notify the user to provide the location to continue. But I don't know how to do that. What I want to do is:

if(error){
  console.log("You need to provide your location!");  
  // I will do a bunch of stuffs here
 }

So, how do I do that? Any help is appreciated.

Note: The geolocation code is taken from W3Schools.com

2 Answers2

0

You can add callbacks in your getCurrentPosition() method.

Source: https://stackoverflow.com/a/18117882/5865284

navigator.geolocation.getCurrentPosition(showPosition(){
    // Do stuff...
}, showError(){
    // Do stuff...
}, {timeout:8000});

It's worth noting you will likely want the timeout, to handle browsers like Firefox that provide the "Not Now" option. This is because by design it won't fire an error handler, and so we need the timeout to assert if we have recieved the data or not.

Matthew Spence
  • 986
  • 2
  • 9
  • 27
0

Actually, I got to find that everything about the question is mentioned in the W3Schools' page about geolocation. And, I found how to handle errors and rejections there.