HirenPatel_
HirenPatel_

Reputation: 530

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?

Upvotes: 0

Views: 2304

Answers (2)

Frozenthia
Frozenthia

Reputation: 759

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));

Upvotes: 1

CathalMF
CathalMF

Reputation: 10055

If you read the ReadMe on the website it tells you that the ReverseLookup object creation is expensive. So they want to you to create it once and then reuse it.

https://github.com/vansha/Two10.CountryLookup/blob/master/readme.md

It is expensive because it loads and parses the entire 7.1MB region list in the constructor.

I just ran some tests. Querying 20 locations and creating the ReverseLookup object each time took 10 seconds. Creating it once and reusing it 20 times took .6 seconds. Reusing it 2000 times took 2 seconds.

Upvotes: 1

Related Questions