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.
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].long. If we use the Haversine formula, we can figure out the distance between the two points.
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.
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.