Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Smart devices with GPS common place in todays world. With that being true we can start tapping in to that information to make exciting applications. Developers can get a user's location by using a Geolocation API. In this Workshop, Andrew shows you not only how to find a location but handle all the other gotchas and errors that can occur.
Project Start Point
Click on the link below to view the initial code snapshot, and click Fork to follow along!
[MUSIC]
0:00
Hello, I'm Andrew and welcome to this
workshop where we'll take a look at
0:04
the Geolocation API in Java Script.
0:09
Geolocation is a convenient way to find
the user's location and
0:11
then provide some sort of feedback like
locating them on a map,
0:15
finding directions to a restaurant, or how
far away they are from their friends.
0:18
The term geolocation can mean a couple of
different things.
0:23
Firstly, it can mean the method of
obtaining coordinates to identify
0:27
a particular location on Earth.
0:31
You could say I'm going to use geolocation
to find out where I am.
0:33
Secondly, geolocation can refer to the
actual set of coordinates for
0:38
something on the Earth.
0:41
For example, you could say my geolocation
is followed by your coordinates.
0:43
A location is made up of a number of
things like latitude, longitude, and
0:49
altitude, the x, y and z of a position if
you like.
0:54
There are other properties you can access,
but most commonly,
0:58
developers only need the latitude and
longitude for
1:01
close approximations of distances between
two locations.
1:04
For example, how far someone is from the
current location to the nearest ATM.
1:08
Let's go over some reasons why you'd want
to use geolocation in a web project.
1:15
You can use your current location to
obtain directions to
1:20
a place from the website.
1:23
You can figure out the closest location of
your favorite restaurant, bank, or
1:25
supermarket.
1:29
You can share your location on a social
network or
1:30
with a private group of friends.
1:33
Most people don't know their latitude and
longitude off the top of their head.
1:36
So as a developer, we can leverage
geolocation to provide an automatic,
1:40
accurate way to locate a person and
1:45
find their location to do something with
that information.
1:47
Also if a user is out and
1:51
about, they may not know the name of where
they are exactly.
1:53
With geolocation, you don't need to worry
about that.
1:57
The geolocation is more accurate than
providing a street name.
2:00
Geolocation became popular first on mobile
devices since most of them have
2:04
GPS built in.
2:08
However, geolocation is available on a
number of browsers on the desktop.
2:10
While desktop computers don't have GPS
built in,
2:14
they can use a database to cross-reference
the wireless networks it can see.
2:17
For example, the wireless networks
surround the home are different than those
2:22
surrounding your work.
2:25
That's providing you don't work from home.
2:26
So depending on the signal strength of
those fixed wireless networks,
2:29
the computer can calculate your location
by cross-referencing the locations of
2:33
these networks with a database of wireless
access points, all without GPS.
2:37
All this is seamless and under the hud.
2:44
To use geolocation to find a position is
fairly straightforward.
2:46
Since we're getting the position of the
device,
2:50
we need to access the navigator object.
2:52
This is an object that contains
information about the web client,
2:55
meaning the browser and device.
2:58
You can use this to garner information
about the browser's version and
3:01
other interesting things, including the
geolocation.
3:05
This geolocation object has two ways to
access the current location,
3:08
getCurrentPosition and watchPosition.
3:13
GetCurrentPosition is just executed once,
3:16
whereas watchPosition a callback with the
current position.
3:19
The callback function takes a parameter,
the position, and
3:24
that has a object of coords, where the
latitude and
3:29
longitude and other information can be
accessed.
3:34
Let's take a look at our project.
3:38
If you want to follow along, you can click
on the snapshot in the show notes and
3:40
then click on the Fault button, and
3:45
it will create a new white space with all
the files, just like this.
3:46
Now, before we get into coding,
3:50
let's just take a look at where the
project is right now.
3:52
So click on the preview, and I'm using
Safari for
3:55
this project because it has these Remember
my decision for
3:59
one day, or it will continually prompt you
every time.
4:05
So because we're going to try this out out
in a few different ways,
4:09
I like how Safari asks me.
4:12
So I'm going to click on Allow, and it
shows the location,
4:14
or the distance to my favorite burger
joints for my current location.
4:21
As you can see, Little Big Burger's the
closest,
4:25
McDonald's is slightly further away, and
we've got Original Wow Burger and
4:27
Red Robin which is six miles away and far
too far away for me right now.
4:31
Another reason why I'm using Safari is
that if you look in the Developer menu,
4:36
there's Disable JavaScript, and it's super
easy to disable.
4:41
So let's see the state of the application
when JavaScript is disabled.
4:43
Well, it shows an error.
4:49
It says that You need JavaScript enabled
for your application to work.
4:50
That's because there's no geolocation APIs
that are non-JavaScript,
4:54
so for the browser at least, so we need
JavaScript enabled.
4:58
And having this error message here really
helps the user
5:03
understand the issues involved if they've
got JavaScript disabled,
5:07
or a system administrator may have
disabled it for whatever reason.
5:12
So I'm gonna re-enable JavaScript up here
5:17
since we'll be using it a lot in this
workshop.
5:20
So I'm just gonna refresh and then click
on Allow, and the distance is calculated.
5:24
So let's just take a look at our code to
see how it all works.
5:30
So in the index for HTML, we have the
error message,
5:36
which is defaultly shown, so we don't use
any CSS to hide that.
5:41
We've got this hud here which uses
JavaScript to show the,
5:46
remember we see Acquiring Location.
5:52
Just giving the user some additional
feedback
5:55
while the geolocation process is
happening.
5:59
This can take a long time if it's the
first time you're finding a location.
6:02
So it's good to have some visual clues and
indicators.
6:07
And we've got a div with the restaurants
in.
6:12
It's unordered list, and each one has a
question mark miles,
6:16
so that's the default position of the, of
the restaurant, and
6:22
I've, I did these data attribute of lat
for
6:27
latitude and lon for longitude for all the
different restaurants.
6:30
I look these up on Google Maps as a close
approximation of where they are,
6:34
and I've added them as data attributes.
6:39
So let's take a look at the JavaScript
that's involved.
6:43
I've separated this into a separate file.
6:47
This is a bit of information on
calculating the distance between two
6:49
points on the planet.
6:53
And it calculates the distance as the crow
flies,
6:56
which means the direct location from the
location one to location two so.
6:59
It doesn't take into account curves in
roads, or
7:04
you having to go a long way around to
something.
7:07
It's if you were a crow and you flew from
one location to another,
7:10
that is the distance to that particular
location.
7:15
So lat1 and lon1 are for your particular
location.
7:17
And lat2 and long2 is for the restaurant.
7:21
And if we take a look at this
geolocation.js here,
7:26
we have JavaScript enabled, so we need to
hide that error message at the top
7:30
of the page, and because we're asking for
the geolocation immediately,
7:35
I'm gonna show the hud the, the progress
bar saying we're acquiring the location.
7:40
Here we use that piece of code that I
showed before.
7:46
It's using the navigator, the geolocation,
and getting the current position, so
7:51
this fires once, and the callback is
gotLocation.
7:55
And the currentPosition is the one
parameter that comes into that
7:59
gotLocation.
8:03
I hide the hud.
8:05
So we've acquired the locations, so we
need to get ride of it now.
8:06
And we use a bit of jQuery to get all the
spans,
8:10
remember the spans are the ones with the
data for
8:15
the latitude and the longitude of all the
restaurants.
8:19
And then we calculate the distance from
the currentPosition's coordinates
8:26
latitude, currentPositions coordinates
longitude and
8:30
the restaurant latitude and the restaurant
longitude.
8:34
And then we fill the span, remember with
cycling over using the each cert.
8:38
This in the context of this function is
the actual span, and we do the distance in
8:44
miles, which is calculated here, with the
string of miles added to the end.
8:49
And at the bottom here, I've got this help
function which displays the error, so
8:56
it modifies the text of that error, and it
slides down there in a slow way.
9:00
And we'll use that for
9:06
other scenarios because getting this code
working is fairly trivial.
9:08
As you can see, we've got something
working, quote unquote.
9:14
But what is more important is the cases
where things go wrong.
9:17
We've already got the code for when
JavaScript is disabled.
9:22
But what about if the browser doesn't
support geolocation?
9:26
Not all browsers support it still, so
9:29
we need to handle that situation for the
user.
9:32
So up on line three, I can add a
conditional.
9:35
[BLANK_AUDIO]
9:40
Where I'm basically testing for the truth
in this, i.e., if there's something there.
9:54
Under geolocation we can run the
geolocation code.
9:58
If it's not there, we want to display the
error.
10:03
[BLANK_AUDIO]
10:06
With something like, Your browser
10:12
doesn't support geolocation.
10:17
And this should display on the page in the
error box.
10:22
So the way that we can test this is just
by doing
10:28
not in front of this conditional statement
here, and clicking on preview.
10:33
And it says Your browser doesn't support
geolocation.
10:40
And as you can see here, we've got, it's
still saying Aquiring Location,
10:42
which isn't true any more.
10:46
So what I'm gonna do is in this
displayError,
10:47
I'm actually going to hide the HUD.
10:50
[BLANK_AUDIO]
10:53
And I'm going to take away that not and
11:00
it should acquire the location fine when
we allow.
11:04
But what happens when we don't allow?
11:08
It's still saying Aquiring Location.
11:13
This isn't good.
11:14
There's no error.
11:15
So what we need to do is take a look at
the MDN, or
11:16
Mozilla Developer Network documentation on
geolocation.
11:21
If we click on getCurrentPosition,
11:28
which is the method that we're using on
the Geolocation object,
11:30
you can see that there's actually three
parameters that you can pass in.
11:34
There's the success callback, which is
actually required, an error callback which
11:38
is optional, and this callback takes one
parameter, a PositionError object.
11:43
And then there's some options that you can
set for other reasons.
11:49
So we're just going to take a look at this
error callback, and
11:55
we're going to deal with this
PositionError.
12:00
So what we can do is we can create a
function called gotError, and
12:03
it has one parameter, which is that
PositionError.
12:10
So I'm just gonna call that an error.
12:16
And let's take a look at that
PositionError object.
12:18
So the PositionError has a code, so it has
a value of 1 through 3.
12:24
And it's been assigned to some constants,
so
12:29
we don't need to memorize these numbers.
12:31
So we can inspect that error code when it
comes in.
12:34
We can then compare it to one of these
particular constants.
12:39
And then we can display an error message
to the user.
12:43
Which would be probably more user friendly
than the error message that's being
12:47
generated by the system.
12:52
So let's jump into here and we'll create a
string called var message.
12:54
Actually we won't assign it just yet, so
it's not technically a string yet, but
13:03
when we create our switch statement,
13:07
we're gonna use a switch statement instead
of conditionals.
13:10
You could use if and else and else if, but
it can get a bit verbose whereas,
13:12
like, a switch case statement can be a
little bit more concise.
13:17
Let's switch on the error's code.
13:22
And we want to do case.
13:29
[BLANK_AUDIO]
13:34
So if the error's code is the same value
13:45
as the error.PERMISSION_DENIED
13:50
constant, we want to set the message to,
13:55
You need to give permission to use your
14:01
location to calculate distances.
14:06
[BLANK_AUDIO]
14:10
Then we'll do a break.
14:15
So outside of the switch statement,
14:17
we can call the displayError function with
the message.
14:20
So up here on
navigator.geolocation.getCurrentPosition,
14:27
let's make sure that we're calling the get
error callback when an error occurs,
14:32
so let's pass in gotError as a call back
on getCurrentPosition.
14:38
Cool!
14:42
So let's try this out and see if it works.
14:43
So it's asking us if we allow it, so let's
Don't Allow.
14:46
And the HUD disappears and this shows,
slowly says this.
14:53
You need to give permission to use your
location to calculate distances.
14:59
Cool.
15:02
So let's close these tabs down, and finish
off this code.
15:04
So the next case would be,
POSITION_UNAVAILABLE.
15:12
The acquisition of the geolocation failed
because at least one of the internal
15:19
sources of the position returned an
internal error.
15:23
So that's whether if the GPS had an error
or
15:26
the lookup on the database on the desktop
eh, occurred.
15:30
This means that we can't find the current
position.
15:35
So it's not down to the user denying it.
15:37
It's just one of those gremlins in the
works that causes problem.
15:39
So let's write a message for this case.
15:44
There was an issue getting your location
from your device.
15:52
Please try again.
16:01
[BLANK_AUDIO]
16:02
And what is try again?
16:10
Actually it's a refresh, so Please refresh
the page.
16:11
[BLANK_AUDIO]
16:14
The next case is a TIMEOUT.
16:24
So the time allowed to acquire the
geolocation
16:30
defined by the PositionOptions.timeout.
16:33
So remember, there was a third parameter
that we could define, and
16:36
there was a set of positionOptions.
16:39
And one of the properties on those options
is the TIMEOUT.
16:42
The default value is infinity,
16:47
meaning the getCurrentPosition won't
return until the position is available.
16:49
There may be some times where your, the
position needs to be returned
16:54
within a particular amount of time before
you update a user interface, so
16:58
you may want to set this a couple of
seconds if you want.
17:02
And this time here is in milliseconds, so
times everything by 1,000.
17:05
If you want it to wait for 2 seconds, it
would be 2,000 milliseconds.
17:10
Since we, we're, we're not really not that
interested in this application,
17:15
we're not going to set the options.
17:19
But just in case if you do set this in the
future,
17:21
you'll wanna set the TIMEOUT for the error
ha, handling.
17:24
So let's set a message and say,
17:29
It took too long getting your position.
17:34
[BLANK_AUDIO]
17:40
And let's break.
17:46
And then finally, the good thing about
using a switch
17:47
statement is that we can set a default
value,
17:52
if an error happens that isn't on this
chart.
17:56
So say, for example, maybe the APIs in the
future introduce a new error type.
18:01
Or you use this gotError for a different
case, we can
18:07
set a specific message as default if these
conditions aren't met above.
18:13
So we can do message equals
18:18
An unknown error has occurred.
18:24
Please refresh the page.
18:31
[BLANK_AUDIO]
18:37
And break, and save.
18:42
And there we have it.
18:45
We've got our error codes, and they've all
been set up.
18:47
Let's just make sure we haven't broke
anything.
18:50
[BLANK_AUDIO]
18:52
And it looks like we have.
18:59
It says that there's an unexpected
semicolon and
19:00
an unexpected colon on the switch clause,
so let's have a look down here.
19:04
That's on this TIMEOUT.
19:11
And let's try again.
19:14
Here we have the dialog saying, can we
have permission to see the location?
19:18
So let's click on Allow, and it works.
19:22
Let's refresh again, and let's click on
Don't Allow.
19:25
It says, you need to give permission for
your location to calculate the distances.
19:30
Okay, so we caught that little error at
the end there, and it's all working.
19:33
So, remember when you're creating an
application that there's often
19:38
other states that your application needs
to handle, and
19:43
geolocation is an example where if you
don't handle
19:46
all of these side issues, it could leave
the user hanging and frustrated.
19:51
And when you have hanging and frustrated
users, you lose them.
19:57
You need to sign up for Treehouse in order to download course files.
Sign up