Today we’re going to use Turf.js to calculate the distance between any two points along the trail. Turf.js is billed as providing “Advanced geospatial analysis for browsers and Node.js.”
The distance calculated is a straight line (“as the crow flies”) distance rather than actual trail miles.
To calculate the distance we need to include
Turf.js. Rather than install it locally, just add this line to the head of your HTML:
Setting up the HTML
We need to add two dropdown (select) boxes: one for the “from” location, and the other for the “to” location. We also create a “calculate” button, and a div to contain the result:
Calculate distance from: <select id='fromBox'> </select> to: <select id='toBox'> </select> <input type="button" id="calculate" value="Calculate"> <div id="distanceResult"></div>
Calculating and Displaying the Distance
First we setup the two dropdown boxes with the list of towns.
To calculate the distance, we get the from and to locations from the dropdown boxes then pass the
turf.point objects to the Turf.js distance function.
Lines 1–16 populate the dropdown (select) boxes using the data in the
Line 18 sets up the calculate button to call the
calculateDistance function (lines 20–33).
In lines 21-26, we get the from/to towns and using the
featuremap, get the latitude and longitude
to create two
turf.point objects. Notice
turf.point is created by specifying the longtiude (x
Line 27 calculates the distance and line 28 just logs it to the console.
Line 29 converts from kilometers to miles.
Lines 31–32 set the text for the
Calculating a distance gives us the result in both kilometers and miles:
You can view the map live here.
To view the complete source code, view the source of the
leaflet_day9.html in your browser, then click on the