Commit e43d749a authored by Rodrigo Tapia-McClung's avatar Rodrigo Tapia-McClung
Browse files

Local tile generation with geojson-vt

parent ff3037cb
Loading
Loading
Loading
Loading
+1 −0
Changes for public/index.html: 1 added line, 0 removed lines.
Original line number Diff line number Diff line
@@ -17,6 +17,7 @@
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
    <script src='https://unpkg.com/@turf/turf/turf.min.js'></script>
    <script src="https://unpkg.com/geojson-vt@3.2.0/geojson-vt.js"></script>
    <script src="../js/functions.js"></script>
</body>

+138 −19
Changes for public/js/functions.js: 138 added lines, 19 removed lines.
Original line number Diff line number Diff line
@@ -8,29 +8,43 @@
/* global mapboxgl, turf */

const baseUrl = new URL(`/data`, window.location.href).href;
let queryGeom = `${baseUrl}/query/dim_municipio?columns=st_asgeojson(box2d(municipio_geom_4326)) box,st_asgeojson(municipio_geom_4326) geom&filter=municipio_cvegeo='09002'`;
let tiles, polygon, box;
let claves = ['09002', '09012'];
let tiles, polygon, box, tileLayers = [];
let pieces, singlePolys = [];

// define MVT layer for given table and some attributes
const mapboxLayer = (table, polygon, box) => {
const mapboxLayer = (table, n, polygon, box) => {

    let columns = ["denue_nombre", "sector", "sector_nombre"],
    //let columns = ["denue_nombre", "sector", "sector_nombre"],
    let columns = ["denue_nombre", "sector"],
        //filter = `ST_Intersects(ST_GeomFromGeoJSON(st_asgeojson(denue_geom_4326,4)),ST_GeomFromGeoJSON('${JSON.stringify(box)}'))`;
        filter = `ST_Intersects(denue_geom_4326,ST_GeomFromGeoJSON('${JSON.stringify(box)}'))`;

    tileLayers.push(table+"-"+n);

    let pbfLayer = {
        id: table,
        id: table+"-"+n,
        source: {
            type: "vector",
            tiles: [`${baseUrl}/${table}/mvt/{z}/{x}/{y}?geom_column=denue_geom_4326&columns=${columns.join(",")}&filter=${filter}`],
            maxzoom: 19,
            minzoom: 6
            //tiles: [`${baseUrl}/${table}/mvt/{z}/{x}/{y}?geom_column=denue_geom_4326&columns=${columns.join(",")}`],
            //maxzoom: 19,
            //minzoom: 6
        },
        "source-layer": table,
        type: "circle",
        "paint": {
            //"circle-opacity": 0.5,
            'circle-opacity': ['case', ['within', polygon], 0.5, 0],
            "circle-radius": 3.5,
            "circle-opacity": ['case', ['within',  polygon], 0.5, 0],
            //"circle-radius": 1,
            //"circle-radius": ['case', ['within',  polygon], 1, 0],
            "circle-radius": [
                "interpolate",
                ["linear"],
                ["zoom"],
                9, 1,
                22, 4
            ],
            "circle-color": [
                "interpolate",
                ["linear"],
@@ -40,35 +54,126 @@ const mapboxLayer = (table, polygon, box) => {
                100, "rgb(158,1,66)"
            ]
        }
        /*type: "heatmap",
        "paint": {
            //"heatmap-opacity": ['case', ['within',  polygon], 0.1, 0],
            "heatmap-intensity": 0.1,
            "heatmap-radius": 1,
            "heatmap-weight": 1
        }*/
    }
    return pbfLayer;
}

const geojsonLayer = (table, n, polygon, box) => {

    /*d3.json(geojsonQ).then( d => {
        let tileIndex = geojsonvt(d);
        var tile = tileIndex.getTile(9, 114, 228);
    */
    let columns = ["denue_nombre", "sector"],
        filter = `ST_Intersects(denue_geom_4326,ST_GeomFromGeoJSON('${JSON.stringify(box)}'))`,
        geojsonQ = `${baseUrl}/geojson/dim_denue2019?geom_column=denue_geom_4326&columns=${columns.join(",")}&filter=${filter}`,
        pbfLayer;


    tileLayers.push(table+"-"+n);
    d3.json(geojsonQ).then(d => {
        pbfLayer = {
            id: table+"-"+n,
            source: {
                type: "geojson",
                data: d
            },
            //"source-layer": table+"-"+n,
            type: "circle",
            "paint": {
                //"circle-opacity": 0.5,
                "circle-opacity": ['case', ['within',  polygon], 0.5, 0],
                //"circle-radius": 1,
                //"circle-radius": ['case', ['within',  polygon], 1, 0],
                "circle-radius": [
                    "interpolate",
                    ["linear"],
                    ["zoom"],
                    9, 1,
                    22, 4
                ],
                "circle-color": [
                    "interpolate",
                    ["linear"],
                    ["get", "sector"],
                    10, "rgb(49,54,149)",
                    50, "rgb(255,255,191)",
                    100, "rgb(158,1,66)"
                ]
            }
        }
        map.addLayer(pbfLayer);
    });
    //});
}

let map = new mapboxgl.Map({
    container: 'mexmap',
    accessToken: "pk.eyJ1IjoiZGV2ZWxvcGdlbyIsImEiOiJja2dwcXFic20wYnJnMzBrbG11d3dwYTkyIn0.4WwFOH6C7hDQXV9obU6mAw",
    style: 'mapbox://styles/mapbox/dark-v10',
    center: [-99.18, 19.48],
    zoom: 12
    center: [-99.17, 19.36],
    zoom: 9
});

map.addControl(new mapboxgl.NavigationControl());

map.on("style.load", async () => {
    d3.json(queryGeom).then( d => {
        polygon = JSON.parse(d[0].geom);
        box = JSON.parse(d[0].box);
        tiles = mapboxLayer("dim_denue2019", polygon, box);
    /*claves.forEach( (clave, i) => {
        let queryGeom = `${baseUrl}/query/dim_municipio?columns=municipio_cvegeo id,municipio_nombre nombre,st_asgeojson(box2d(municipio_geom_4326)) box,st_asgeojson(municipio_geom_4326) geom&filter=municipio_cvegeo='${clave}'`;
        d3.json(queryGeom).then( geoms => {
            geoms.forEach( g => {
                polygon = JSON.parse(g.geom);
                let feature = turf.feature(polygon, {id: g.id, nombre: g.nombre});
                if (feature.geometry.type === 'MultiPolygon') {
                    pieces = feature.geometry.coordinates.map(c => turf.polygon(c));
                } else {
                    pieces = [feature];
                }
                singlePolys.push(pieces);
                box = JSON.parse(g.box);
                tiles = mapboxLayer("dim_denue2019", i, feature, box);
                map.addLayer(tiles);
            });
        });
    });*/
    let filter = [];
    claves.forEach( clave => {
        filter.push(`municipio_cvegeo='${clave}'`);
    });
    //let queryGeom = `${baseUrl}/query/dim_municipio?columns=municipio_cvegeo id,municipio_nombre nombre,st_asgeojson(box2d(st_geometryn(municipio_geom_4326,1)),4) box,st_asgeojson(st_geometryn(municipio_geom_4326,1),4) geom&filter=${filter.join(" or ")}`;
    let queryGeom = `${baseUrl}/query/dim_municipio?columns=municipio_cvegeo id,municipio_nombre nombre,st_asgeojson(box2d(municipio_geom_4326)) box,st_asgeojson(municipio_geom_4326) geom&filter=${filter.join(" or ")}`;
    d3.json(queryGeom).then( geoms => {
        geoms.forEach( (g, i) => {
            polygon = JSON.parse(g.geom);
            let feature = turf.feature(polygon, {id: g.id, nombre: g.nombre});
            if (feature.geometry.type === 'MultiPolygon') {
                pieces = feature.geometry.coordinates.map(c => turf.polygon(c));
            } else {
                pieces = [feature];
            }
            singlePolys.push(pieces);
            box = JSON.parse(g.box);
            //tiles = mapboxLayer("dim_denue2019", i, polygon, box);
            //map.addLayer(tiles);
            geojsonLayer("dim_denue_2019", i, polygon, box);
        });
    });

});

map.on('click', e => {
    if (turf.booleanWithin(turf.point([e.lngLat.lng, e.lngLat.lat]), polygon)) {
    singlePolys.flat().forEach( p => {
        if (turf.booleanWithin(turf.point([e.lngLat.lng, e.lngLat.lat]), p)) {
            var features = map.queryRenderedFeatures(e.point,
            { layers: ['dim_denue2019'] }
                { layers: tileLayers }
            );

            if (features.length != 0) {
                new mapboxgl.Popup()
                    .setLngLat(e.lngLat)
@@ -77,7 +182,21 @@ map.on('click', e => {
            }
        }
    });
});

const changeCursor = event => {
    console.log(event)
    if (event.type === "mousenter") return map.getCanvas().style.cursor = 'pointer';
    if (event.type === "mousleave") return map.getCanvas().style.cursor = '';
}

map.on('mouseenter', 'dim_denue2019-0', e => {
    if (turf.booleanWithin(turf.point([e.lngLat.lng, e.lngLat.lat]), singlePolys.flat()[0])) {
        map.getCanvas().style.cursor = 'pointer';
    }
});

/*
// Change the cursor to a pointer when the mouse is over the denue layer.
map.on('mouseenter', 'dim_denue2019', e => {
    if (turf.booleanWithin(turf.point([e.lngLat.lng, e.lngLat.lat]), polygon)) {
@@ -88,4 +207,4 @@ map.on('mouseenter', 'dim_denue2019', e => {
// Change it back to a pointer when it leaves.
map.on('mouseleave', 'dim_denue2019', () => {
    map.getCanvas().style.cursor = '';
});
 No newline at end of file
});*/
 No newline at end of file