SOURCE

console 命令行工具 X clear

                    
>
console
mapboxgl.accessToken = 'pk.eyJ1IjoibGVla2U5OCIsImEiOiJjazNzZGxlMHQwNjAxM21tdHh3NmJyOWJ0In0.nhCMjub5PhQqzFOSNB9uMw';
const map = new mapboxgl.Map({
    container: 'map', // container ID
    style: 'mapbox://styles/mapbox/satellite-v9', // style URL
    center: [-98.137343, 38.137451], // starting position [lng, lat]
    zoom: 3 // starting zoom
});

const layerList = document.getElementById('menu');
const inputs = layerList.getElementsByTagName('input');

for (const input of inputs) {
    input.onclick = (layer) => {
        const layerId = layer.target.id;
        console.info('layerId', layerId)
        // map.setStyle('mapbox://styles/mapbox/' + layerId);

        const style = map.getStyle()
        const sources = Object.keys(style.sources)
        const layers = style.layers.map(o => o.id)
        setMapStyleFn('mapbox://styles/mapbox/satellite-v9', {
            map,
            style: 'mapbox://styles/mapbox/' + layerId,
            sourcesList: sources,
            layersList: layers
        })
        // const style = map.getStyle().sources
        // console.info(style)
    };
}

map.on('load', function () {
    // Add a new source from our GeoJSON data and set the
    // 'cluster' option to true. GL-JS will add the point_count property to your source data.
    map.addSource("earthquakes", {
        type: "geojson",
        // Point to GeoJSON data. This example visualizes all M1.0+ earthquakes
        // from 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
        data: "https://docs.mapbox.com/mapbox-gl-js/assets/earthquakes.geojson",
        cluster: true,
        clusterMaxZoom: 14, // Max zoom to cluster points on
        clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
    });

    // map.addLayer({
    //     id: "clusters",
    //     type: "circle",
    //     source: "earthquakes",
    //     filter: ["has", "point_count"],
    //     paint: {
    //         // Use step expressions (https://docs.mapbox.com/mapbox-gl-js/style-spec/#expressions-step)
    //         // with three steps to implement three types of circles:
    //         //   * Blue, 20px circles when point count is less than 100
    //         //   * Yellow, 30px circles when point count is between 100 and 750
    //         //   * Pink, 40px circles when point count is greater than or equal to 750
    //         "circle-color": [
    //             "step",
    //             ["get", "point_count"],
    //             "#51bbd6",
    //             100,
    //             "#f1f075",
    //             750,
    //             "#f28cb1"
    //         ],
    //         "circle-radius": [
    //             "step",
    //             ["get", "point_count"],
    //             20,
    //             100,
    //             30,
    //             750,
    //             40
    //         ]
    //     }
    // });

    map.addLayer({
        id: "cluster-count",
        type: "symbol",
        source: "earthquakes",
        filter: ["has", "point_count"],
        layout: {
            'icon-image': ['get', 'icon'],
            "text-field": "{point_count_abbreviated}",
            "text-font": ["DIN Offc Pro Medium", "Arial Unicode MS Bold"],
            "text-size": 12,
            "icon-offset": [1000, 0]
        }
    });

    map.addLayer({
        id: "unclustered-point",
        type: "circle",
        source: "earthquakes",
        filter: ["!", ["has", "point_count"]],
        paint: {
            "circle-color": "#11b4da",
            "circle-radius": 4,
            "circle-stroke-width": 1,
            "circle-stroke-color": "#fff"
        }
    });

    // inspect a cluster on click
    map.on('click', 'clusters', function (e) {
        var features = map.queryRenderedFeatures(e.point, { layers: ['clusters'] });
        var clusterId = features[0].properties.cluster_id;
        map.getSource('earthquakes').getClusterExpansionZoom(clusterId, function (err, zoom) {
            if (err)
                return;

            map.easeTo({
                center: features[0].geometry.coordinates,
                zoom: zoom
            });
        });
    });

    map.on('mouseenter', 'clusters', function () {
        map.getCanvas().style.cursor = 'pointer';
    });
    map.on('mouseleave', 'clusters', function () {
        map.getCanvas().style.cursor = '';
    });
});

map.on('load1', () => {
    // Add a data source containing GeoJSON data.
    map.addSource('maine', {
        'type': 'geojson',
        'data': {
            'type': 'Feature',
            'geometry': {
                'type': 'Polygon',
                // These coordinates outline Maine.
                'coordinates': [
                    [
                        [-67.13734, 45.13745],
                        [-66.96466, 44.8097],
                        [-68.03252, 44.3252],
                        [-69.06, 43.98],
                        [-70.11617, 43.68405],
                        [-70.64573, 43.09008],
                        [-70.75102, 43.08003],
                        [-70.79761, 43.21973],
                        [-70.98176, 43.36789],
                        [-70.94416, 43.46633],
                        [-71.08482, 45.30524],
                        [-70.66002, 45.46022],
                        [-70.30495, 45.91479],
                        [-70.00014, 46.69317],
                        [-69.23708, 47.44777],
                        [-68.90478, 47.18479],
                        [-68.2343, 47.35462],
                        [-67.79035, 47.06624],
                        [-67.79141, 45.70258],
                        [-67.13734, 45.13745]
                    ]
                ]
            }
        }
    });

    // Add a new layer to visualize the polygon.
    map.addLayer({
        'id': 'maine',
        'type': 'fill',
        'source': 'maine', // reference the data source
        'layout': {},
        'paint': {
            'fill-color': '#0080ff', // blue color fill
            'fill-opacity': 0.5
        }
    });
    // Add a black outline around the polygon.
    map.addLayer({
        'id': 'outline',
        'type': 'line',
        'source': 'maine',
        'layout': {},
        'paint': {
            'line-color': '#000',
            'line-width': 3
        }
    })

    const style = map.getStyle()
    console.info(Object.keys(style.sources))
    console.info(style.layers.map(o => o.id))
})

var setMapStyleFn = function (defaultStyle, { map, style, sourcesList, layersList }) {
    let prevStyle = defaultStyle
    // return (props) => {
    // const { map, style, sourcesList, layersList } = props
    if (!map || !style || !layersList || !sourcesList) {
        return
    }

    // if (deepEqual(prevStyle, style)) {
    //     return
    // }
    prevStyle = style

    const mapStyle = map.getStyle();
    if (!mapStyle) {
        return
    }
    const layers = (mapStyle.layers || []).filter((layer) => layersList.includes(layer.id));
    const sources = Object.keys((mapStyle.sources || {})).filter((key) => {
        return sourcesList.includes(key)
    }).reduce((prev, result) => {
        prev[result] = (mapStyle.sources || {})[result];
        return prev;
    }, {});

    const handleStyle = () => {
        Object.keys(sources).forEach((key) => {
            const existing = map.getSource(key);
            if (!existing) {
                map.addSource(key, sources[key]);
            }
        });
        layers.forEach((layer) => {
            const existing = map.getLayer(layer.id);
            if (!existing) {
                map.addLayer(layer)
            }
        });
        map.off('style.load', handleStyle);
    }
    map.on('style.load', handleStyle);

    map.setStyle(style, { diff: true });
    // }
}

<div id="map"></div>

<div id="menu">
    <input id="satellite-v9" type="radio" name="rtoggle" value="satellite" checked="checked">
    <!-- See a list of Mapbox-hosted public styles at -->
    <!-- https://docs.mapbox.com/api/maps/styles/#mapbox-styles -->
    <label for="satellite-v9">satellite</label>
    <input id="light-v10" type="radio" name="rtoggle" value="light">
    <label for="light-v10">light</label>
    <input id="dark-v10" type="radio" name="rtoggle" value="dark">
    <label for="dark-v10">dark</label>
    <input id="streets-v11" type="radio" name="rtoggle" value="streets">
    <label for="streets-v11">streets</label>
    <input id="outdoors-v11" type="radio" name="rtoggle" value="outdoors">
    <label for="outdoors-v11">outdoors</label>
</div>


body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }

    #menu {
        position: absolute;
        background: #efefef;
        padding: 10px;
        font-family: 'Open Sans', sans-serif;
    }

本项目引用的自定义外部资源