Geolocation is determination of where something is placed. Usually it is where the user is placed, when trying to find e.g. an address or a tourist attraction in the area. Along with maps like Google Maps it is also used to mark where certain types of shops or franchises are placed, when trying to find the nearest store.
The JavaScript to make geolocation work, consists of three parts:
Determination of coordinates
Showing the coordinates
Handling of errors
To make the JavaScript work on a page, you need a field for writing in. Here we use a DIV with ID="ShowPosition". In order to demonstrate the functionality, we'll make a button here, to start the function FindCoordinates. It looks like this:
Be aware that the BUTTON and DIV must be before the JavaScript when you write in the DIV. If you want the script in the header or as an external script, see this page.
For at forbinde den DIV vi skal skrive i og de fundne koordinater, skal vi først bruge en variabel, der har fat i feltet. Her bruger vi en getElementById():
<SCRIPT>
var Coordinates = document.getElementById("ShowPosition");
</SCRIPT>
Funktionen FindCoordinates() start by checking that browser support geolocation. If it does, the next two function ShowPosition and ShowError are executed. If not, an error message, that the browser does not support geolocation will appear. Then the code looks like this:
<SCRIPT>
var Coordinates = document.getElementById("ShowPosition"); function FindCoordinates() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(ShowPosition, ShowError);
} else {
Coordinates.innerHTML = "This browser does not support Geolocation.";
}
}
</SCRIPT>
Now we have the coordinates, or a message if an error occurs while getting the coordinates. The JavaScript with the function ShowCoordinates() looks like this:
<SCRIPT>
var Coordinates = document.getElementById("ShowPosition");
function FindCoordinates() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(ShowCoordinates, ShowError);
} else {
Coordinates.innerHTML = "This browser does not support Geolocation.";
}
}
If an error occurred so there is no set of coordinates to show, e.g. if the user click "Do no allow" on the browser's request for access to geolocation data, it is considered good practice to have an error message, so the user knows why noting appears on the screen. The JavaScript with the function ShowError() looks like this:
<SCRIPT>
var Coordinates = document.getElementById("ShowPosition");
function FindCoordinates() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(VisCoordinates, ShowError);
} else {
Coordinates.innerHTML = "This browser does not support Geolocation.";
}
}
function ShowError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
Coordinates.innerHTML = "The user denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
Coordinates.innerHTML = "Information on location not available."
break;
case error.TIMEOUT:
Coordinates.innerHTML = "The request for the user's location stopped (time out)."
break;
case error.UNKNOWN_ERROR:
Coordinates.innerHTML = "An unknown error occurred."
break;
}
}
</SCRIPT>
On screen it looks like this:
For the example here, we only asked for latitude and longitude, but if needed, getCurrentPosition() returns quite a few other informations, that you can retrieve if you like, e.g. height above sea level. This, obviously, is provided that the information about the location is available. The returnable values are:
Property
Returns
coords.latitude
Latitude as decimal number (always returned)
coords.longitude
Longitude as decimal number (always returned)
coords.accuracy
The accuracy of the position (always returned)
coords.altitude
Height above average sea level in meters (returned if available)
coords.altitudeAccuracy
The accuracy of height of the position (returned if available)
coords.heading
Direction as degrees, clockwise, from North (returned if available)
coords.speed
Speed in meter per second (returned if available)
timestamp
Date/time for response (returned if available)
Geolocation on the move
If you need a continuous update of geolocation because you are on the move, e.g. a GPS, you use the function watchPosition() instead of getCurrentPosition(). As this will always be updating, i.e. use bandwidth and mobile data, you have to be able to turn it off, if you want. This is done using clearWatch().
Google Maps
A practical thing: Google Chrome from ver. 50 on, requires a safe connection, i.e. HTTPS instead of HTTP, to run the Geolocation API, i.e. show a map with location. For the other browsers where this has not already been implemented, you can expect that it is only a matter of time before the same requirements occur.
To get access to use the full Google Maps, you need a Key, i.e. you need to start a project in Google APIs. This is done here, and it if free. It is a slightly convoluted process to get started, so you need to be a bit patient. What you really need to be aware of, is that for maps you have quite a few APIs, and which one to choose to make it work isn't that obvious when you start. For this I can only recommend trying to activate the APIs until it works. You can use parts of Google Maps without a Key, and what will be shown here is examples with and without Key.
In its simplest form, the JavaScript for showing a map, looks like this:
However, as we need the map to show more than just specific areas, we'll need quite a bit more than just this line.
Let's start with an ordinary section of a map, where we know the coordinates. It could be something like Rådhuspladsen in Copenhagen. The solution consists of three parts:
A field for placing the map. Here we use a DIV with ID="GoogleMap1", and in this case we specify the size of the map.
A JavaScript where we specify the coordinates and how much we want to zoom in.
A JavaScript which is an API call with your Key (be aware that the Key inserted here only works for this site)
If you want the map to show you where you are, i.e. a GPS function, you need to combine show map and geolocation. For this we create a function called LocalMap, which is a rewriting of MyMap, to replace the function ShowCoordinates, and instead of fixed coordinates, we insert the coordinates found using the function FindCoordinates(). Then tyhe code looks like this (changes highlighted using bold typeface):
<SCRIPT>
var Coordinates = document.getElementById("GoogleMap2");
function FindCoordinates() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(LocalMap, ShowError);
} else {
Coordinates.innerHTML = "This browser does not support Geolocation.";
}
}
function LocalMap(position) {
var LocalMapProp= {
center:new google.maps.LatLng(position.coords.latitude,position.coords.longitude), zoom:17,
};
var map=new google.maps.Map(document.getElementById("GoogleMap2"),LocalMapProp);
}
function ShowError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
Coordinates.innerHTML = "The user denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
Coordinates.innerHTML = "Information on location not available."
break;
case error.TIMEOUT:
Coordinates.innerHTML = "The request for the user's location stopped (time out)."
break;
case error.UNKNOWN_ERROR:
Coordinates.innerHTML = "An unknown error occurred."
break;
}
}