Search code examples
c#apilocationcoordinatespolygon

How to get in which country somebody is without using any API? Latitude and longitude countries coordinates


What is the best & easiest way to check in which country my (e.g) person is (geolocation), without using API like GoogleMaps, HereMaps etc.

I only have latitude and longitude coordinates of my (e.g) people and want to automatically check in which country they currently are.


Solution

    1. Download QGIS - great geocoordinate program, such like Google Maps Pro, but with much more options and functions.

    2. From naturalearthdata.com (e.g: https://www.naturalearthdata.com/downloads/50m-cultural-vectors/50m-admin-0-countries-2/) download .shp file.

    In my case it was ne_10m_admin_0_countries_pol.shp

    EDIT: For better accuracy (small islands / state borders) use: https://ec.europa.eu/eurostat/web/gisco/geodata/reference-data/administrative-units-statistical-units/countries#countries20

    (if the WKT file will be too big for you, go to Vector -> Geometric tools -> Simplify)

    1. Import this file into QGIS (the one that is the "biggest" in size)

    2. We need .WKT (Well-known text -> yeah, the worst name for extension imo), so download extension (follow this tutorial: https://www.youtube.com/watch?v=N6WOzM00FLk)

    3. Click "Select features by area or single click" (in the toolbar, in the top middle, near the blue refresh icon)

    4. Click WKT (from 4. extension) and copy values to new .txt file and save this file (WARNING: one file, one country).

    And now let's go to coding:

    1. In your class import library

      using NetTopologySuite.IO;
      
    2. Read all the countries you want to check, e.g:

      var Merica = File.ReadAllText(@"<fileToPatch>\America_WKT.txt"); 
      
    3. Use our library and create GeometryFactory and WKT reader variable:

      var gf = NetTopologySuite.NtsGeometryServices.Instance.CreateGeometryFactory(4326); //NtsGeometryServices.DefaultSRID
      var wkt = new WKTReader();
      //(longitude, latitude) 
      // I used dictionary (key - value), but you can use just normal list/array/enumerable.
      var GeomDict = new Dictionary<string, NetTopologySuite.Geometries.Geometry>();
      GeomDict.Add("MericaFakYeah", wkt.Read(AmericaWktString));
      
    4. Create your final function:

      var pointStart = gf.CreatePoint(new NetTopologySuite.Geometries.Coordinate(longitudeStart, latitudeStart));
      
      foreach (var geom in geomDict)
      {
           var isLocation = geom.Value.Contains(pointStart);
      
           if (isLocation)
           {
               location = geom.Key;
               break;
           }
       }
      

    Voila. Hope it will help a lot of us!