2

I have implemented the cordova-plugin-geolocation plugin into my cordova app. I was simply trying to derive the user's country without the need for a third party APi. My application is communicating with a WebApi written in C# so I don't mind if there was a C# solution for this. I would rather not explore using third party tools including Google but if that is the best option then I will explore.

In terms of the accuracy, I only need to detect whether they are outside the UK.

CR41G14
  • 5,464
  • 5
  • 43
  • 64

1 Answers1

0

There is another possibility that does not need any third-party-apis respectively internet-connection at all.

This answer is based on the point-in-polygon-aglorithm.

You need a country/countries as polygon(s) that consist of lat/lng-points, you can get all lat/lng-points of austria (for instance) by using GGIS-Editor and relevant data (as shapefile) from here or from natural earth (select Admin 0 – Countries) here

  1. Install GGIS-Editor
  2. Unpack AUT_adm_shp.zip
  3. Start GGIS-Editor
  4. Select Tab: Layer -> Add Layer -> add Vectorlayer
  5. Select AUT_adm0.shp (shapefile), it shoudl look like this now: enter image description here

  6. Mark whole polygon via Mark-Tools (yellow button with cursor): enter image description here

  7. Select Tab: Layer -> Save as

  8. Save as GeoJSON-File
  9. Copy all lng/lat coordinates out of this GeoJSON-File: enter image description here

  10. When you have copied all Lng/Lat-Points as Array-elements in this format:

    [ [ lng, lat ], .....]


Then you can use my fiddle-code:

var countryLngLatsOfAustria = [ [ lng, lat ], .....];

function pointInPoly(verties, testx, testy) {
  var i,
  j,
  c = 0,
  nvert = verties.length;
  for (i = 0, j = nvert - 1; i < nvert; j = i++) {
    if (((verties[i][0] > testy) != (verties[j][0] > testy)) && (testx < (verties[j][1] - verties[i][1]) * (testy - verties[i][0]) / (verties[j][0] - verties[i][0]) + verties[i][1]))
    c = !c;
  }
  return c;
}

// use current location
navigator.geolocation.getCurrentPosition(
  function (position) {
    alert(position.coords.longitude +", "+ position.coords.latitude);
    var isInAustria = pointInPoly(countryLngLatsOfAustria, position.coords.latitude, position.coords.longitude);
    if (isInAustria) alert('User is located within austria!');
    else alert('User is located outside from austria!');
  }, 
  function (err) {
    console.log(err);
  }, 
  {
    timeout: 5000,
    enableHighAccuracy: true
  }
);

(Link: https://jsfiddle.net/pfa028n8) to find out whether you are located in- or outside of austria. Of course it also works with other countries or "combined countries" to find out whether an user is within europe for instance.

Hope this helps.

Blauharley
  • 4,186
  • 6
  • 28
  • 47