Search code examples
c#geolocation

Get country name and code based on lat/long c#


The best solution I found so far is,

using Two10.CountryLookup;

var lookup = new ReverseLookup();
try
{   // get country details based on lat/long
    var country = lookup.Lookup(float.Parse(scandata.gpslat), float.Parse(scandata.gpslong));
  string cName = country.name;
   string cCode = country.code;
}
catch(Exception e)
{
    Console.WriteLine("Exception :"+e);
} 

But This object is too heavy, I have millions of records to go through. This object making my script slow. is there any other faster method?


Solution

  • If you read the source code of your library, it loads a region list.

    this.Regions = ParseInput(LoadFile()).ToArray();
    

    Even though ParseInput() and LoadFile() have deferred execution on them, it immediately casts the IEnumerable<Region> to an array, which executes it and forces the evaluation on every constructor. It's an expensive operation, so it should be set once.

    You should either construct the ReverseLookup item once, or implement it in a Singleton.

    public class RegionLocator
    {
        private static RegionLocator instance;
        private static ReverseLookup ReverseLookup;
    
        private RegionLocator() { }
    
        public static RegionLocator Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new RegionLocator();
                    ReverseLookup = new ReverseLookup();
                }
                return instance;
            }
        }
    
        public Region Lookup(float lat, float lng, RegionType[] types)
        {
            return ReverseLookup.Lookup(lat, lng, types);
        }
    
        public Region[] Regions()
        {
            return ReverseLookup.Regions;
        }
    }
    

    And use as such:

    RegionLocator.Instance.Lookup(float.Parse(scandata.gpslat), float.Parse(scandata.gpslong));