How to search through a list of coordinates and display, depending on the distance between it and current location? (Windows Phone 7)
I have gathered about 60 or so geo coordinates of cinema locations around Ireland and I want to use them in my WP7 app to show nearest cinemas to your current location.
I thought I would save them in an XML file but I don't think that will work for what I'm trying to achieve, which is to be able to search the entire list of coordinates and display whichever cinemas appear within (for example) 25kms of their location.
I have found a few links to helping find the distance between two points so that part shouldn't be too bad.
Any ideas on how I might go about achieving this? Thanks in advance
I created a similar service.
First of all, as Shedal also pointed out, consider hosting the locations in an external service. This will make your life a lot easier when you need to add more locations. (The update application service in App Hub can take up to 10 days which is a long time if you need to quickly fix a wrong location)
Secondly, once you have loaded the list of locations, it is simple to loop through them and find the nearest cinemas. You can use the Haversine formula to calculate the distance between two geo locations (this formula takes into account that the earth is round, and not flat - unlike the Pythagorean theorem). Luckily for your the WP GeoLocation class comes with a built in function called GetDistanceTo that you can use.
The problem is now nothing but a simple Linq query:
List<GeoCoordinate> cinemaLocations = new List<GeoCoordinate>(); GeoCoordinate myLocation = new GeoCoordinate(); var closestCinemas = cinemaLocations.OrderBy(s => s.GetDistanceTo(myLocation)); var closestCinema = closestCinemas.FirstOrDefault();
Shouldn't the list of cinemas be updated from time to time? If so, I would host a web service somewhere and call it from your app to obtain the up-to-date list of cinemas.
In regards to calculation of the distance, it's simply the Pythagorean theorem.
D = sqrt(abs(x2 - x1) + abs(y2 - y1))
I would store them in a SQL server (SQL lite can run inside a WP7 app). Then I would query with lat and lon using a +/- of some value based on your current location. Now you will need to be sure to compensate for being near the 0 degrees axis, but this will give you a square area to reduce your results down to. Once you have this you can iterate over the result set looking for the distance to each point and just drop the results that sit in the corners of this square creating a result set that looks in all directions with a defined maximum tolerance. Of course I haven't had to solve this exact problem (I tend to rely on projects like Neo4J Spacial which handles stuff like this automatically (and really well)