JavaScript Chapter 10 Javascript and Geolocation


One really useful new browser object you can use is Geolocation. Geolocation returns a Latitude and Longitude that you can use on mapping services like Google Maps. We'll do that now. (You'll need a modern browser for this, though. If you're using Internet Explorer then make sure it's at least version 9.)

Create a new web page for this from your template. Move the two SCRIPT tags to the BODY section. Add the following two HTML tags just above the SCRIPT tags:
<P ID="error_code"></P>
<DIV ID="map"></DIV>
Your code should then look like this:
Javascript tags in the body section of the HTML page
If Geolocation is not supported in the browser we'll display an error message. If all goes well we can display a Google map showing the user's location.
For the first line of the Javascript add the code below:
var getLabel = document.getElementById("error_code");
This just gets a reference to the error_code ID. We'll use this to display an error if anything goes wrong.
Geolocation is part of the Navigator objector. To test browser support, add the following IF … ELSE statement:
if ( navigator.geolocation ) {
else {
In between the round brackets of IF we're just testing for a value of true fornavigator.geolocation.
Save your work and load the page into a browser. IF the browser supports the Geolocation object then you'll see the first message displayed, and you can continue with this lesson. If you see the second message displayed then you'll need to either update your current browser or download a new one.

The Geolocation Object

The Geolocation Object has three methods you can use (case sensitive):
We'll use the first one, getCurrentPosition. The second one, watchPosition, is like a timer. It's used if you want to update a user's position. You use clearWatch to clear the watchPosition timer.
getCurrentPosition is used like this:
getCurrentPosition( location, error, options )
Only the first argument between the round brackets is required. The error argument is for when something goes wrong. If a user's positions can't be found then you can display an error message. We'll do this shortly. The third argument, options, is if you want to set the accuracy, a timeout value, or if a cached location should be used. We won't use any of the options.
The location argument is usually a function. getCurrentPosition then provides some position values for you to manipulate.
So, delete the getLabel code for the IF statement, but leave the one for the ELSE part. Type the following for IF:
navigator.geolocation.getCurrentPosition( getLongLaterrorMessage );
Your code should then look like this:
A geolocation function in Javascript
Now add the getLongLat function we set up for the first argument of getCurrentPosition:
function getLongLat( position ) {
getLabel.innerHTML = position.coords.latitude + "<BR>";
getLabel.innerHTML = getLabel.innerHTML + position.coords.longitude + "<BR>";
Now add the error function:
function errorMessage( error ) {
We'll add some code for the error function shortly. But here's what your code should look like:
Getting longitude and latitude with geolocation and Javascript
Have a look at the getLongLat function, though:
function getLongLat( position ) {
When we set up the getCurrentPosition method we didn't add a position argument:
getCurrentPosition( getLongLat, errorMessage )
So how come our getLongLat function now has this position argument? Well, it's because the getCurrentPosition method provides this for you. When getCurrentPosition method goes off and does its stuff, it returns with a few properties for you. You can store these properties in a variable between the round brackets of your function. We've called our variable position. You could call it something else if you like, though.
Now have a look at the first line of the getLongLat function:
getLabel.innerHTML = position.coords.latitude + "<BR>";
After the equal sign is our position variable. Then we have this:
cords is one of the properties returned by the getCurrentPosition method (the other one is timestamp). After a dot, you can type one of quite a few other sub-properties. We used latitude. But here are the other options:
For the second line of our function, we've used the longitude sub-property (careful with longitude - it's easy to misspell!):
Save your work and try it out. When you refresh your browser, you should see a popup message appear. When you're trying to get somebody's position they will have the option of saying no. The box will look something like this: (You'll get different warnings depending on the browser you're using. This one is from Google Chrome.)
Geolocation warning in Chrome
Allow the tracking, though, and a latitude and longitude will appear:
latitude and longitude coordinates
Before we get to how to use these with Google Maps, let's add the error message code.

Geolocation Error Codes

The error part of the getCurrentPosition method has a few inbuilt error codes you can use. They are:
You can use the error codes in a switch statement. Add the following to your errorMessage( error ) function:
switch( error.code ) {
case error.TIMEOUT:
getLabel.innerHTML = 'Timeout';
getLabel.innerHTML = 'Position unavailable';
getLabel.innerHTML ='Permission denied';
case error.UNKNOWN_ERROR:
getLabel.innerHTML ='Unknown error';
Notice what's in the round brackets of switch:
The error part is the property and code part is the value it will contain. This value equates to one of the inbuilt error codes from above (the error code are called constants, and they are in capital letters.) Again, the getCurrentPosition method fetches these values for you.
To test it out, refresh the page in your browser. Instead of allowing tracking, this time deny it. You should see the "Permission Denied" error appear. (Some browsers will now prevent the popup box appearing again, once you click deny. To get it back, you'll have to close the browser down and reopen it.)

Geolocation and Google Maps

Now that we have a pair of coordinates, we can use them with the Google Maps API (Application Programming Interface). The API we'll use is called staticmap. This is one of the easier Google mapping APIs to get to grips with. It uses something called a querystring to get the various options available to you.


A querystring is way to get information using a key/value pair. Here's an example of a key/value pair:
In the querystring above, sensor is the key and false is the value. The two are separated by an equal sign, with no spaces between the two. (The sensor key is required if you're using Google's static maps. A value of false means you're not updating the information - you just want the data once.)
Two querystrings are separated from each other with the ampersand character (&). For example, there is a size key that takes a height and width as its value. To separate the two querystrings you do this:
To keep things simple, we'll use three other keys: centerzoom, and markers. The center key is required. Its value can be a pair of latitude and longitude coordinates separated by a comma, or an actual address (center=Chicago).
The zoom key refers to how much detail you want display. A zoom value of 0 means you want to view the whole world; a value of 21, the highest, means you want to zoom in really close. The zoom key is required if you miss out the markers key.
The markers key refers to the position marker over the coordinates you want. This can be quite complicated so we urge you to study the documentation, here:
We'll keep it simple, though, and just add our latitude and longitude coordinates again.
So here's the whole thing:
var pos=position.coords.latitude + "," + position.coords.longitude;
var display="" + pos + "&zoom=15&size=500x500&markers=" + pos + "&sensor=false";
Let's break that down a bit.
The first line just joins our two coordinates together, separated by a comma. The comma goes between quote marks (single or double). There must be no spaces between your comma and your quotes.
The second line is where we return the Google map. The first part is this:
The question mark at the end means that a querystring follows. Our querystring itself is this:
center=" + pos + "&zoom=15&size=500x500&markers=" + pos + "&sensor=false";
The double quote marks after center= is matched to the first one before http:
We need to do this because our coordinates are held in a variable. If you put quote marks around a variable Javascript treats it as a string and just prints the variable name rather than its contents.
Next we have:
+ pos +
This concatenates the pos variable with the rest of the string. The next part is this:
So we're setting the zoom level to 15 and the size to 500 by 500. The markers are the same as the values in the pos variable. In other words, put a position marker over the latitude and longitude coordinates. Finally, we set sensor to false.
When Google has finished with your querystring it will return an image with the map you requested. Our image is being held in the variable we called display. We need to add this to an IMG tag and place it in the BODY of the HTML. The next two lines do that:
var img_display = "<IMG SRC=" + display + ">";
The first line creates the HTML image element, with the display variable as the source. The second line uses innerHTML to add the image to the page.
The whole of the getLongLat function should look like this:
Google Maps API used with Geolocation
Make sure you're online and test it out in your browser. If all went well you should see a map displayed for your current location.