Display a Map Using Leaflet.js

What is Leaflet.js

Leaflet.js is a light-weight JavaScript library, created by Vladimir Agafonkin, that allows developers to add interactive maps to their web sites.

Given that we are a business development agency working with geospatial technology, we thought it would be a good idea to explore this open-source software and see what we could create.

Adding Leaflet.js to Your Website

To take advantage of the features in the Leaflet.js library, you must first link the Leaflet CSS file and THEN the Leaflet JavaScript file.

   
    <!-- Include the Leaflet CSS -->

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css" 
    integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
    crossorigin=""/> 

    <!-- Include the Leaflet JS -->

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css" 
    integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
    crossorigin=""/> 
        
Create a DIV on the Website

To display the map we needed to create a div on the site and simply define the height and width in the CSS.


    <!-- Create the map display div -->

    <div id="mapid"></div>

    #mapid { width: 100%; height: 400px; } 
        
Add a Tile Layer that Displays a Map

Now we need to link a map to our div, which is a straightforward enough process of setting the centre point (using Lat and Long) of the view and creating a map instance. We set this to the Quarry One Eleven Office in the Surrey Technology Centre and applied a suitable zoom level - in this case, 17.

To actually display a map, we need a map tile and Leaflet.js provides access to the Openstreet Map for use as a template.

Where the code says 'your.mapbox.access.token' is where it expects a code form your Mapbox Account which you can setup and use here: Access Code


        <!--   -->

    var mymap = L.map('mapid').setView([51.239937,-0.612063], 17);

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
    attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
    maxZoom: 18,
    id: 'mapbox.streets',
    accessToken: 'your.mapbox.access.token'
        }).addTo(mymap);
    
Show the Map

And, as you can see below, that's that is needed to display an interactive map that users can pan and zoom around.