user1770843
user1770843

Reputation: 21

Windows Phone how to get country by coordinates?

I am currently developing a c# application for Windows phone with XNA/Silverlight for a school project. I've been able to get the coordinates from a device. But I don't want the coordinates, I want to show which country they are in. I found some sites that are able to convert the coordinates into the country: http://maps.google.com/maps/geo?q=47.645,122.141&output=csv&sensor=false But I don't want the user to get on the internet to show it to him, I want to get it build in my application. So how do I show the country in my application on a TextBlock?

Thanks

Upvotes: 2

Views: 587

Answers (1)

neeKo
neeKo

Reputation: 4280

1. Make your own data set

Download a high resolution map, paint each country into a different color and assign those colors to their respective countries in a lookup table. Make sure you save the map as a bitmap - compression formats will distort colors along the edges of the countries.

To get the country name, do these steps:

1. Translate geocoordinates into map coordinates
2. Get the pixel at selected map coordinates
3. Get country name from the lookup by getting color data from the pixel

This solution requires a lot of manual work, unless you already have a high resolution colored map ready.

Naturally, the higher the resolution the better. You might consider also painting territorial waters for different countries, as well as international waters (i.e. - return Atlantic Ocean).


2. Polygon of countries

Alternatively, as L.B suggested, you could get a polygon of countries, and use a point in polygon hit-test algorithm to determine which country the user is in.

I've programmed a simple class that does this: pastebin link.

Basically, it parses an kml file (I've used this geocommons map), and uses code found on the point in polygon answer on stackoverflow to detect which country is on given coordinates.


Example usage:

FileInfo kmlFile = new FileInfo("5603.kml");

String kmlString = "";
using (StreamReader sr = new StreamReader(kmlFile.OpenRead()))
{
    kmlString = sr.ReadToEnd();
}

Kml kml = new Kml(kmlString);
String country = kml.GetCountryByCoordinates(18.26, 42.56);

This prints Croatia for me, which is the country I'm actually in. The code was hastily put together (especially the KML parsing part), so it might have some bugs. You should test it more.


If you need individual states in the US, you could try using a different KML file. Also, this particular map isn't very high resolution, if you look at coastlines you can see that a lot of peninsulas and islands aren't encompassed with polygons, so there might be some errors when in these areas. Territorial waters also aren't marked. I could only recommend you look for better maps or make your own if this poses a significant problem.

Upvotes: 1

Related Questions