HTML and CSS Reference
In-Depth Information
Your HTML now includes three
<div>
elements to which you will add content using JavaScript.
Calculating Distances for Each Location
In this section, you are going to create a new function called
findNearest
that will take in the latitude and longit-
ude coordinates of the user and calculate the distances for each of the restaurant locations. The function will then add
these distances to the
<div>
elements you previously added. Later in this chapter, you will add more code to this
function that handles finding the nearest location.
The code for this exercise can be found in folder 4.
First you need to calculate the distances. The following steps show you how to do this.
1.
Open the
geolocation.js
file.
2.
At the bottom of the file, create a new function,
findNearest()
. It should have two parameters:
lat
and
lon
. These parameters will be used to pass the user's location details to the function.
// Find the restaurant that is nearest to the user's location.
function findNearest(lat, lon) {
}
3.
Within this new function, use the
haversine()
function to calculate the distance between the user and
the first location. Initialize a new variable named
d1
using the result.
function findNearest(lat, lon) {
// Calculate the distances.
var d1 = haversine(lat, lon, 40.755018, -73.992556); // 310
West 38th Street
}
4.
Now do the same for location 2, this time creating a new variable named
d2
. Note that the last two paramet-
ers in the
haversine()
call have changed. This is because these are the coordinates of the restaurant loc-
ation.
function findNearest(lat, lon) {
// Calculate the distances.
var d1 = haversine(lat, lon, 40.755018, -73.992556); // 310
West 38th Street
var d2 = haversine(lat, lon, 40.791121, -73.973971); // 2450
Broadway
}
5.
Finally, create a variable,
d3
, and initialize it with the result of the
haversine()
call for the third loca-
tion.
function findNearest(lat, lon) {
// Calculate the distances.