美文网首页Mapbox
Geojson转化并加载PBF矢量瓦片

Geojson转化并加载PBF矢量瓦片

作者: WebGiser | 来源:发表于2023-04-11 20:57 被阅读0次

    Geojson转PBF矢量瓦片

    var fs = require("fs");
    var vtpbf = require("vt-pbf");
    var geojsonVt = require("geojson-vt");
    var VectorTile = require("@mapbox/vector-tile").VectorTile;
    var Protobuf = require("pbf");
    
    var express = require("express");
    var app = express();
    
    app.get("/toPbf", function (req, res) {
        let params = req.query;
        let z = params.z;
        z = Number(z);
        // let x = params.x;
        // x = Number(x);
        // let y = params.y;
        // y = Number(y);
        // console.log(params, z, x, y);
        var geojson = JSON.parse(fs.readFileSync(__dirname + "/1.geojson"));
        var tileindex = geojsonVt(geojson, {
            maxZoom: 14, // max zoom to preserve detail on; can't be higher than 24
            tolerance: 3, // simplification tolerance (higher means simpler)
            extent: 4096, // tile extent (both width and height)
            buffer: 64, // tile buffer on each side
            debug: 0, // logging level (0 to disable, 1 or 2)
            lineMetrics: false, // whether to enable line metrics tracking for LineString/MultiLineString features
            promoteId: null, // name of a feature property to promote to feature.id. Cannot be used with `generateId`
            generateId: false, // whether to generate feature ids. Cannot be used with `promoteId`
            indexMaxZoom: 5, // max zoom in the initial tile index
            indexMaxPoints: 100000, // max number of points per tile in the index
        });
    
        for (let i = 0; i <= z; i++) {
            // fs.mkdir(__dirname + "/" + i, { recursive: true });
            let num = Math.pow(2, i);
            for (let x = 0; x < num; x++) {
                for (let y = 0; y < num; y++) {
                    fs.mkdir(__dirname + "\\" + i + "\\" + x, { recursive: true }, function (err) {
                        if (err) {
                            return console.error(err);
                        }
                        // console.log("目录创建成功。");
                        let tile = tileindex.getTile(i, x, y);
                        // console.log(tile);
                        if (tile) {
                            // var layername = z + "-" + x + "-" + y;
                            var buff = vtpbf.fromGeojsonVt({ 1: tile });
                            fs.writeFileSync(i + "/" + x + "/" + y + ".pbf", buff);
                            // fs.writeFileSync(__dirname + "\\" + i + "\\" + x + "\\" + y + ".pbf", buff);
                        }
                    });
                }
            }
        }
        res.end("success");
    });
    
    app.get("/getPbf", function (req, res) {
        let params = req.params;
        let layer = params.layer;
        let idx = params.idx;
        var data = fs.readFileSync(__dirname + "/1.pbf");
        var tile = new VectorTile(new Protobuf(data));
        var orig = tile.layers[layer].feature(idx).toGeoJSON(0, 0, 1);
        console.log(orig);
    });
    
    app.listen(3000, function () {
        console.log("服务运行!");
    });
    

    Mapbox加载PBF矢量瓦片

    <template>
        <div id="map"></div>
    </template>
    
    <script>
    import { onMounted } from "vue";
    export default {
        name: "Map",
        setup() {
            onMounted(() => {
                axios.get("data/mapConfig2.json").then((response) => {
                    let style = response.data;
                    mapboxgl.accessToken = "pk.eyJ1Ijoid";
                    const map = new mapboxgl.Map({
                        container: "map",
                        attributionControl: false,
                        doubleClickZoom: false,
                        hash: false,
                        // style: "mapbox://styles/mapbox/streets-v11",
                        style: style,
                        center: [115, 35],
                        zoom: 3,
                    });
    
                    // control 控件
                    map.addControl(new mapboxgl.FullscreenControl({ container: document.querySelector("body") }));
                    map.addControl(
                        new mapboxgl.GeolocateControl({
                            positionOptions: {
                                enableHighAccuracy: true,
                            },
                            trackUserLocation: true,
                            showUserHeading: true,
                        })
                    );
                    map.addControl(new mapboxgl.NavigationControl(), "top-left");
                    const scale = new mapboxgl.ScaleControl({
                        maxWidth: 80,
                        unit: "imperial",
                    });
                    map.addControl(scale);
    
                    map.on("load", () => {
                        // 加载tms矢量瓦片地图服务
                        let tmsUrl = "http://127.0.0.1:8082/{z}/{x}/{y}.pbf";
                        map.addSource("test-source", {
                            type: "vector",
                            // scheme: "tms",
                            tiles: [tmsUrl],
                            minzoom: 0,
                            maxzoom: 8,
                        });
                        // map.addLayer({
                        //  id: "test-layer",
                        //  type: "line",
                        //  source: "test-source",
                        //  "source-layer": "1",
                        //  layout: {
                        //      "line-cap": ["step", ["zoom"], "butt", 11, "round"],
                        //      "line-join": "round",
                        //  },
                        //  paint: {
                        //      "line-color": "rgb(255, 0, 0)",
                        //  },
                        // });
    
                        map.addLayer({
                            id: "test-layer2",
                            type: "fill",
                            source: "test-source",
                            "source-layer": "1",
                            layout: {
                            },
                            paint: {
                                "fill-color": "rgb(255, 0, 0)",
                                "fill-opacity": 0.5
                            },
                        });
                    });
                });
            });
        },
    };
    </script>
    
    <style scoped>
    #map {
        width: 100%;
        height: 100%;
    }
    </style>
    

    相关文章

      网友评论

        本文标题:Geojson转化并加载PBF矢量瓦片

        本文链接:https://www.haomeiwen.com/subject/trkcddtx.html