Mapbox-gl is one of the most powerful tools in GIS visualization. Here’s my first project with MapBox. Here’s some nonsense:

Q: Why did I use MapBox? A: It’s actually A very interesting reason. The business of the project needs to load A 30M GeoJSON. I once invited the two veterans openLayers and Leaflet, but they were not helpful. The map would get stuck when dragging and zooming. At this time, I thought of using the GIS library of webGL, which is our spirit boy, MapBox!

Cough cough ~ back to business ah! First of all, I’d like to thank Ape Base for the local offline deployment of MapBox and the introduction to the Mapbox/Node-Fontnik tool. I as a vegetable chicken, standing on the shoulders of giants, do a Mapbox off-line deployment of finishing.

What is required for mapBox offline deployment?

We need to localize the following four resources:

  1. Sprite (icon)
  2. Glyphs (map annotation font)
  3. Sources (Layer source)
  4. Layer definition

Do it! Do it!

Download and install

I personally prefer to use NPM to install, after all, webpack to help pack.

npm install mapbox-gl --save
Copy the code

Map initialization

When we need to use mapbox-GL offline, we don’t need to write accesstoken in the first place. The official document of Mapbox requires us to write Accesstoken in order to read the resources in the official CDN of Mapbox. (If you see a link to mapbox:// in the code, that’s the official source!)

import 'mapbox-gl/dist/mapbox-gl.css'
import Mapbox from 'mapbox-gl'
import style from './style.js'
// For offline deployment, do not use the following sentence!
// mapboxgl.accessToken = 'pk. Blah, blah, blah ';
const map = new Mapbox.Map({
  container: ' '.// You can set properties such as center point and scale. , style })Copy the code

If we inhaled accesstoken, style of writing is a string, such as mapbox: / / styles/mapbox/streets – v11

If we don’t write accesstoken, then style requires that we write an object, and we need to configure the style property in our map initialization.

Then, we will focus on the content of style.js.

Version version [Number]

Don’t ask. Ask is eight.

Why, I don’t know, maybe he’s only eight

// style.js
const style = {
    version: 8
}
export default style
Copy the code

Name the name [String]

Name it whatever you like.

// style.js
const style = {
    version: 8.name: 'myStyle'
}
export default style
Copy the code

Icon Sprite [String]

The value of Sprite is a string, but what we really need is a URL. However, we don’t need another service to support this function, we just need a JSON and a Sprite image to solve this problem.

Personally, I have not made localization deployment of ICONS at present, because the project requirements have not progressed to this stage yet. However, according to the information of many parties, the following information is obtained. Since there is no test, please kindly point out any problems.

sprite.json

Here’s an example for JSON

You can also click here to see an official JSON example from MapBox

{
    "house": {
        "width": 20, "height" :20."x": 0."y": 0."pixelRatio": 1."visible": true
    },
    "radio": {
        "width": 20, "height" :20."x": 20."y": 0."pixelRatio": 1."visible": true},... }Copy the code

sprite.png

Here is an example of an image that matches the JSON shown above.

Once you have these two files, you can put them in a folder and store them on the server as static resources.

You can make the image service elegant by using the ngnix agent etc. For example, the current folder called Sprite is placed in the position /static/img and the static folder is proxied to localhost:8787, then you can say this in style.js

// style.js
const style = {
    version: 8.name: 'myStyle'
    sprite: 'localhost:8787/img/sprite'
}
export default style
Copy the code

Font glyphs [String]

Mapbox fonts are also available as a service, so all you need is a lot of PBF files. Here mapbox provides a tool called Node-Fontnik

However, the tool only runs on Linux, and almost never runs on Windows, so don’t ask why.

If you don’t have Linux, consider reading this article to get Ubuntu for your Windows 10

For an introduction to Node-Fontnik, see this article

I gave the solution directly here, and slightly improved the script from Ape Base

If you don’t have a font file, look it up on Wordsmith

git clone https://github.com/mapbox/node-fontnik.git
cd node-fontnik
vi start.js
Copy the code

At this point, create a start.js

// start.js
var fontnik = require('. ');
var fs = require('fs');
var path = require('path');
const dirExists = require('./dirExists')
var fontPath = process.argv[2]
var convertPath = process.argv[3]

var convert = async function(fileName, outputDir) {
    await dirExists(outputDir)
    console.log('In transition... ')
    var font = fs.readFileSync(path.resolve(fileName));
    output2pbf(font, 0.255, outputDir);
}

function output2pbf(font, start, end, outputDir) {
    if (start > 65535) {
        console.log("Done!);
        return;
    }
    fontnik.range({font: font, start: start, end: end}, function(err, res) {
        var outputFilePath = path.resolve(outputDir + start + "-" + end + ".pbf");
        fs.writeFile(outputFilePath, res, function(err){
            if(err) {
                console.error(err);
            } else {
                output2pbf(font, end+1, end+1+255, outputDir); }}); }); } convert(fontPath, convertPath);Copy the code

Run this js

Nodestart. js [font path] [output path]Copy the code

Then you can get a bunch of PBF files, for example, if I get Microsoft YAHEI, then I put the PBF files in YAHEI folder and put them on the file server, then you can write in style.js

// style.js
const style = {
    version: 8.name: 'myStyle'
    sprite: 'localhost:8787/sprite'.source: {
    	polygonSource: {
    		type: 'geojson'.data: '/geojson/zhejiang.json'.generateId: true.sprite: 'localhost:8787/img/sprite'.glyphs: 'localhost:8787/YAHEI/{fontstack}/{range}.pbf',}}}export default style
Copy the code

Layer source Sources [Object]

Source is the layer data source. There are six types in MapBox: Vector, Raster, Raster-dem, GeoJSON, image and video.

You can define multiple sources to handle various situations

The source defined here is the same as the source defined by map.addSource

You can see the official documentation for configuration items

I’ll give you an example of geoJSON

If you don’t have the GeoJSON file, look for it here

// style.js
const style = {
    version: 8.name: 'myStyle'
    sprite: 'localhost:8787/sprite'.sources: {
    	polygonSource: {
    		type: 'geojson'.data: '/geojson/zhejiang.json'.generateId: true}}}export default style
Copy the code

The key name in the source is the unique ID of the source. As a GEOJSON, you can either give it as an object directly in data or refer to it via a link.

GenerateId can automatically encode unique ids for blocks that do not have ids, for example, setFeatureState

Layer the Layers (Array)

The layer is actually displayed at the front, which is actually applied to the Source

You can see the official documentation for configuration items

For example, if we now want to fill geoJSON as paint, you can do so in style.js

// style.js
const style = {
    version: 8.name: 'myStyle'
    sprite: 'localhost:8787/sprite'.source: {
    	polygonSource: {
    		type: 'geojson'.data: '/geojson/zhejiang.json'.generateId: true}},layers: [{id: 'polygonLayer'.type: 'fill'.source: 'polygonSource'.// Write the id of the source
            paint: '# 092453'}}]export default style
Copy the code

At this point, you have the simplest offline deployment of Mapbox-GL.

So, what are you waiting for? Grab your keyboard and get going!

If you have any questions, please point out in the comments!

๐Ÿ† technology project phase iii | data visualization of those things…