3

I want to load a local .mbtiles (with vector tiles) with maplibre-gl-js (in a Cordova app if it's important to know). As far as I understand, I should use the addProtocol method. That works fine as I get my console.log, but I don't know how to load the tiles then...

This is my code:

maplibregl.addProtocol('mbtiles', (params, callback) => {
  console.log('I get this log.');
  // but what to do here to get local mbtiles vector tiles loaded?
});

The style is defined like this:

...
"sources": {
  "openmaptiles": {
    "type": "vector",
    "url": "mbtiles://map/data/test.mbtiles"
  }
},
...

Any help / hints appreciated :)

If you need more information, just feel free to ask.

P.S. I used mapbox-gl-cordova-offline before and tried to understand how this plugin loads the tiles, but I can't figure it out yet.

dda
  • 6,030
  • 2
  • 25
  • 34
Hollul
  • 319
  • 4
  • 16

1 Answers1

2

Here's what I'm doing to achieve this:

maplibregl.addProtocol("custom", (params, callback) => {
// tileBuffer = get a arrayBuffer of a specific tile using params.url
    if (tileBuffer) {
        callback(null, tileBuffer, null, null);
    } else {
        let message = `Tile is not in DB: ${params.url}`;
        callback(new Error(message));
    }
    return { cancel: () => { } };
});

I'm using cordova-sqlite-ext in order to be able to use a pre-populated database in Cordova. The style has a tiles: [custom://database-name/{z}/{x}/{y}] in order to know which tile to fetch.

Full code can be found here: https://github.com/IsraelHikingMap/Site/blob/6aa2ec0cfb8891fa048b1d9e2a4fc7d4cbcc8c97/IsraelHiking.Web/src/application/services/database.service.ts

It's worth noting that I added the addProtocol method to maplibre especially for this purpose. :-)

Harel M
  • 183
  • 7
  • I created a sveltekit demo app and used some of your code for the unzipping part. I also find your custom protocol interesting. I'm thinking I could make use of it for PWAs so that data can be retrieved from browser storage when off-line. What is the correct way to handle the case when a tile is not available? Demo app: https://github.com/FunMiles/Planetiler_MapLibre_Sveltekit – Michel Aug 08 '22 at 05:07
  • How does this enable using the .mbtiles file directly? Seems like you still need something in the middle to translate the z,x,y requests? – chrismarx Sep 27 '22 at 21:05
  • 1
    @chrismarx yes, you need to write some code to fetch the tile using the url (which has x,y,z already "filled"). I use a database service for that in the browser which uses native capabilities in cordova/capacitor – Harel M Sep 29 '22 at 06:16