HTML and CSS Reference
In-Depth Information
Getting the User's Location
The GeoLocation API is remarkably simple to use. Browsers that support geolocation expose a
geoloca-
tion
interface that has a number of methods (kind of like how you call
getElementById()
on the
document
object).
The main method that you will be using in this chapter is
getCurrentPosition()
. This will return a
GeoPos-
ition
object that has a number of properties, including
coords
. The
coords
property contains data such as the
latitude
and
longitude
of the user's position. Later in this chapter, you will be using these latitude and longit-
ude coordinates to calculate the distance between the user and each of the Joe's Pizza restaurants. Then you will
write some code that compares the results to find the closest restaurant.
Setting Up Your JavaScript Files
Before you can dive into writing code that interacts with the GeoLocation API, you first need to add two new
JavaScript files to your project. The first of these contains a small JavaScript library to help you out when calculating
distances; the second file is where you will place all of the code you are going to write.
The code for this exercise can be found in the download files for Chapter 13, folder 1.
Here are the steps:
1.
Download the
geo.js
file from the book's website and place it in the
js
folder within your project direct-
ory. The
geo.js
file can be found in the following folder:
chapter13/1/js
.
2.
Create a new file in your
js
folder and call it
geolocation.js
.
3.
Open the
locations.html
file in your text editor.
4.
Add the following two new
<script>
elements just before the end tag for the
<body>
, one for each of
the JavaScript files. Make sure that the
geo.js
file is first.
<script src="js/geo.js"></script>
<script src="js/geolocation.js"></script>
</body>
5.
Save the
locations.html
file.
Requesting the User's Location
Now you have the admin stuff out of the way, and it's time to start working with the GeoLocation API. In this sec-
tion, you learn how to request the user's location.
First you need to write some code that detects whether the user's browser supports the GeoLocation API. To do this,
you use an
if
statement that checks whether the
geolocation
interface is available. This is how the code would
look: