Published on 14 September 2021

Using LINZ Basemaps tiles with Leaflet.js

The excellent Leaflet.js is one of my preferred tools when building interactive online maps. And so is the aerial Basemaps service from Land Information New Zealand. Here I share a couple of tricks I usually apply each time I combine the two.

If you have a look at the LINZ Basemaps documentation, you'll see that the example code they example is something like:

<div id="map" style="width: 600px; height: 400px;"></div>

<script>

var url = "https://basemaps.linz.govt.nz/v1/tiles/aerial/3857/{z}/{x}/{y}.webp?api={api_key}";

var attr = '<a href="//www.linz.govt.nz/data/linz-data/linz-basemaps/data-attribution">LINZ CC BY 4.0 © Imagery Basemap contributors</a>';

var tiles = L.tileLayer(url, {

   attribution: attr

});

var map = L.map("map")

   .addLayer(tiles)

   .setView([-40.5, 173], 6);

</script>

In some old browsers, the tiles might not showing up due to the fact that the WEBP image format is not supported. In this case, you can fallback to PNG which will do the trick. I have had this issue with old iOS versions (iPhone 5/6, iPad2,  etc). I wasn't able to debug my mobile Safari using my Macbook because they are running with different versions. This StackOverflow thread shows how to detect WEBP support, which you can apply to the code above resulting in:

<div id="map" style="width: 600px; height: 400px;"></div>

<script>

function support_format_webp() {
    var elem = document.createElement('canvas');
    if (!!(elem.getContext && elem.getContext('2d'))) {
        return elem.toDataURL('image/webp').indexOf('data:image/webp') == 0;
    }
    else {
        return false;
     }
}


if (support_format_webp()) {
    var url = "https://basemaps.linz.govt.nz/v1/tiles/aerial/3857/{z}/{x}/{y}.webp?api={api_key}";
}
else {
    var url = "https://basemaps.linz.govt.nz/v1/tiles/aerial/3857/{z}/{x}/{y}.png?api={api_key}";
}

// The rest of the code is the same as above

</script>

I often use full-width maps and occasionally this is an issue with mouse wheels as instead of scrolling down/up the page, the user finds suddenly zooming in and out of the map which is annoying. Similar in mobile when using the finger to scroll up/down a page, the user may get stuck in the map without being able to go back to continue scrolling the page. But the options scrollWheelZoom and dragging when initialising a Leaflet map are your friends:

var map = L.map('map', {
    zoomControl:true, maxZoom:28, minZoom:1, scrollWheelZoom: false, dragging: !L.Browser.mobile,
})