How to sort a list of locations by how close they are to you

One of the things that are most important to me for phase 1 of the state parks app is to have the list of parks be sorted by how far the user is from the park.  After all, Tower Hill State Park might be interesting but if you live 4 hours away, you aren’t likely to give it a visit.  While I know vaguely how I would do that, I do not think that I have actually done that before.  So, let’s figure this out.

For the first step, we need to figure out where the user is.  Last year, I wrote a codepen where I used navigator.geolocation and MapQuest to figure out where the user is.  The result was to just show the address the person is most likely at.  If we fork that pen and add an array-driven table of UW system campuses, we now both know our starting point and our five potential end points.

See the Pen
Sorting a list of locations by how for away they are: Part 1
by Joe Steinbring (@steinbring)
on CodePen.

The second step is the most interesting one.  You will notice that we have the user’s lat/long coordinates in this.location.latLng and we have the lat/long coordinates for each campus in this.campuses[i].lat and this.campuses[i].long.  If we use the Haversine formula, we can figure out the distance between the two points.

See the Pen
Sorting a list of locations by how for away they are: Part 2
by Joe Steinbring (@steinbring)
on CodePen.

The above code gets you the number of kilometers between the two points, as the crow flies.  If you want better precision, you need to make an API call to something like google maps.  Once we get this far, we just need to sort the table by the “distance away” column.  We have done that at least once before.  Using a computed property, we can sort the array by distance.

See the Pen
Sorting a list of locations by how for away they are: Part 3
by Joe Steinbring (@steinbring)
on CodePen.

So, now we know where the user is, we know where the campuses are, we know the distances between the user and the campuses, and we have the table sorted from the closest campus to the one that is furthest away.  If we were going to continue the exercise, we would probably want to convert from kilometers to miles and round those values down to one or two decimal places.  I will leave that for a future blog post, though.

Have any questions, comments, etc?  Feel free to drop a comment, below.

 

[ Cover photo by Thomas Kinto on Unsplash ]

1 thought on “How to sort a list of locations by how close they are to you

  1. as the crow flies rather than road network? I’m thinking of transferability and skill challenges. You could look at locations with a mountain range or large lake impacting movement. Have you coded barriers into this?
    You know I’m loving the #MappyGeeky

Leave a Reply

Your email address will not be published.