0

I take user's location with javascript.How can i prevent fake location ? this is my code:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, showError);
}

and it's showPosition function:

function showPosition() {
    Latitude  = position.coords.latitude;
    Longitude = position.coords.longitude;
}
Wendelin
  • 2,354
  • 1
  • 11
  • 28
Mohsen Moradi
  • 21
  • 1
  • 3

2 Answers2

0

You cannnot detect if user is using mock.

One way is to use IP address of user and get location, but it can be inaccurate. You might want to check question below:

how to detect when user is using mock location chrome browser

  • When you found an answer that solve a question, don't post a link to it, instead use the built-in feature "vote/flag to close as a duplicate". If you don't have enough reps. to do that, move one and someone else that has, will do it. – Asons May 07 '19 at 06:47
  • ok I will do that from next time. – Takahiro Ito May 07 '19 at 07:28
0

You can't really prevent location spoofing but you can check if the GPS location matches the IP's region.

I suggest you to use a public API since this is quite easy.

//This only works if for http
fetch('http://www.geoplugin.net/json.gp')
.then((resp) => {
  if(!resp.ok) {
    console.warn('Cannot fetch location data')
    return
  }
  return resp.json()
})
.then((data) => {
  //Check if the location matches with a margin of one degree
  if(Math.abs(Latitude - data.geoplugin_latitude) < 1 && Math.abs(Longitude - data.geoplugin_longitude) < 1) {
    console.log("Location is valid")
  } else {
    console.warn("Location is probably fake")
  }
})
Wendelin
  • 2,354
  • 1
  • 11
  • 28