Google Maps and geolocation




Geolocation

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:
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:

<BUTTON ONCLICK="FindCoordinates()">Find Coordinates</BUTTON>

<DIV ID="ShowPosition"> </DIV>


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.";
    }
}


function ShowCoordinates(position) {
    Coordinates.innerHTML = "Latitude: " + position.coords.latitude + "<BR>Longitude: " + position.coords.longitude;
}
</SCRIPT>


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 VisCoordinates(position) {
    Coordinates.innerHTML = "Latitude: " + position.coords.latitude + "<BR>Longitude: " + position.coords.longitude;
}


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:

PropertyReturns
coords.latitudeLatitude as decimal number (always returned)
coords.longitudeLongitude as decimal number (always returned)
coords.accuracyThe accuracy of the position (always returned)
coords.altitudeHeight above average sea level in meters (returned if available)
coords.altitudeAccuracyThe accuracy of height of the position (returned if available)
coords.headingDirection as degrees, clockwise, from North (returned if available)
coords.speedSpeed in meter per second (returned if available)
timestampDate/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:

<SCRIPT SRC="https://maps.googleapis.com/maps/api/js?key=InserKeyHere"> </SCRIPT>


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:
Then the code looks likethis:

<DIV ID="GoogleMap1" STYLE="width:600px; height:400px;"></DIV>

<SCRIPT>
function myMap() {
    var mapProp= {
        center:new google.maps.LatLng(55.67591419999999,12.569128399999954), zoom:17,
    };
    var map=new google.maps.Map(document.getElementById("GoogleMap1"),mapProp);
}
</SCRIPT>

<SCRIPT SRC="https://maps.googleapis.com/maps/api/js?key=InsertKeyHere&callback=myMap"></SCRIPT>


On screen, the result looks like this:



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):

<BUTTON ONCLICK="FindCoordinates()">Find coordinates</BUTTON>

<DIV ID="GoogleMap2" STYLE="width:600px; height:400px;"></DIV>

<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;
    }
}

<SCRIPT SRC="https://maps.googleapis.com/maps/api/js?key=InsertKeyHere&callback=myMap"></SCRIPT>
</SCRIPT>


On screen it looks like this: