Topic 12: Further Web Mapping

Introduction

Today we will look at some additional web mapping topics, specifically:

The Geolocation API

Introduction

The Geolocation API allows you to obtain the current location of the device running the browser from within JavaScript. Even on desktop browsers this will give a result if you are using a wireless network, but its real use is in the mobile web development world. A mobile browser can talk to the GPS chip of the phone and obtain the phone's current location on the earth. Alternatively, if the GPS chip is not available, a rough estimate can be obtained from cell towers or wireless networks.

Using the Geolocation API

It is fairly straightforward to use the Geolocation API. Here is an example (please note - all examples in this topic will show the JavaScript only, not the HTML):



function init()
{
    if(navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition (

            gpspos=> {
                console.log(`Lat ${gpspos.coords.latitude} Lon ${gpspos.coords.longitude}`); // show on the console
            },

            err=> {
                alert(`An error occurred: ${err.code}`);
            }

        );
    }
    else
    {
        alert("Sorry, geolocation not supported in this browser");
    }
}

How is this working?

Watching the position

The above code will simply obtain the current position and stop. In a typical mobile GPS application, however, the user will want to be informed of their location on a regular basis. To do this we use watchPosition() in place of getCurrentPosition(). Here is an example:


function init()
{
    if(navigator.geolocation)
    {
        navigator.geolocation.watchPosition (

            gpspos=> {
                console.log(`Lat ${gpspos.coords.latitude} Lon ${gpspos.coords.longitude}`); // show on the console
            },

            err=> {
                alert(`An error occurred: ${err.code}`);
            },

            {enableHighAccuracy:true, maximumAge: 5000 }

        );
    }
    else
    {
        alert("Sorry, geolocation not supported in this browser");
    }
}

Note that the code is almost the same as the first example, except:

IMPORTANT - Geolocation API now needs HTTPS server

For security reasons (the risk of your location being intercepted by packet-sniffers) the Geolocation API now (recently at the time of writing) requires the use of an HTTPS server (a web server with encrypted communication), on both Chrome and Firefox. Luckily Edward2 has HTTPS, so the examples will work as expected.

See Let's Encrypt for information on setting up an HTTPS server.

Exercise 1 - Geolocation

This is a key exercise; if you have completed Topic 11 Exercise 1 and Topic 11 Exercise 2 questions 1-2, you should attempt it before you finish previous work.

Displaying markers from a web service

A common use of web mapping is to show data from a web service on a map. For example, we might want to show the location of restaurants in a particular city on a web map. This is quite easy - you simply need to make an AJAX request to a web service, parse the JSON (or XML) returned and create markers using the data. The following exercise will allow you to explore this.

Exercise 2 - Connecting to a web service and displaying markers

In the dftitutorials database on edward2 is a table called artists which gives the latitude and longitude of the home towns of selected artists (Oasis, Madonna, The Beatles, David Bowie, Prince, Michael Jackson, Woop, Ed Sheeran). There is also a web service at https://edward2.solent.ac.uk/wad/artists.php which takes an artist as a query string parameter called artist and returns JSON describing the home town of that artist and the latitude and longitude of that home town.

Modify your HT-Tracks AJAX page (Session 6) so that as well as a "Search" button, there is a "Where is this artist from?" button. This should connect to a new JavaScript function which sends an AJAX request to this web service. Also modify your init() function from your AJAX exercise so that it initialises a Leaflet map. You'll need to declare the Leaflet map globally so that it can be accessed from multiple functions:

var map; // make the 'map' variable global

function init() {
    map = L.map("map1"); // Initialise the map in init()
    // ... etc ...
}

In the AJAX callback, parse the JSON returned so that a marker is shown on the map for that artist, and the map is centred at the artist's hometown. When the marker is clicked, the name of the home town of the artist should be shown in a popup.

If no query string parameters are passed to the web service, the home towns of all the artists are shown. Add a new button to the HT-Tracks AJAX page labelled "Show Home Towns Of All Artists". By making an AJAX request to the web service, it should show the location of the home towns of all the artists on the map, along with a popup giving information about the artist and their home town.

Further topic - GeoJSON

If you complete all the above, you might want to read these further notes on GeoJSON - a common standard format for representing geographical data.