美文网首页开源Mapbox
Mapbox入门教程

Mapbox入门教程

作者: WebGiser | 来源:发表于2022-03-09 16:43 被阅读0次

    环境:Vue2.x项目

    安装依赖

    cnpm  i  mapbox-gl  --save
    cnpm  i  @mapbox/mapbox-gl-geocoder  --save
    cnpm  i  mapbox-gl-controls  --save
    cnpm  i  @mapbox/mapbox-gl-draw  --save
    

    初始化地图

    <template>
        <div>
            <div id="map"></div>
        </div>
    </template>
    
    <script>
    // 引入mapbox-gl
    import mapboxgl from 'mapbox-gl'
    import 'mapbox-gl/dist/mapbox-gl.css'
    
    // 引入标绘工具
    import MapboxDraw from "@mapbox/mapbox-gl-draw";
    import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css'
    
    // 地图控件
    import {
        RulerControl,
        StylesControl,
        CompassControl,
        ZoomControl,
        InspectControl,
        TooltipControl,
        LanguageControl,
        ImageControl
    } from 'mapbox-gl-controls'
    
    // 地理编码控件
    import MapboxGeocoder from '@mapbox/mapbox-gl-geocoder';
    import '@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css';
    
    export default {
        name: "mapbox1",
        data() {
            return {
                map: null,
                draw: null
            };
        },
        mounted() {
            this.initMap();
    
            this.addDraw();
    
            this.addScale();
            this.addGeocoder();
    
            this.addRulerControl();
            this.addStyleChangeControl();
            this.addCompassControl();
            this.addZoomControl();
            this.addLanguageControl();
            this.addInspectControl();
            this.addTooltipControl();
        },
        methods: {
            // 初始化地图
            initMap() {
                mapboxgl.accessToken =
                    "your token";
                this.map = new mapboxgl.Map({
                    container: "map",
                    style: "mapbox://styles/mapbox/streets-v11",
                    center: [115, 35],
                    zoom: 5,
                });
                this.map.addControl(new mapboxgl.FullscreenControl(), 'bottom-right');
            },
            // 增加点线面绘制工具
            addDraw(){
                this.draw = new MapboxDraw();
                this.map.addControl(this.draw, 'top-right');
                this.map.on('draw-create', this.updateArea);
                this.map.on('draw-delete', this.updateArea);
                this.map.on('draw-update', this.updateArea);
            },
            updateArea(e){
                console.log(e);
                let data = this.draw.getAll()
                let answer = document.getElementById('calculated-area')
                if (data.features.length > 0) {
                    let area = turf.area(data)
                    let rounded_area = Math.round(area * 100) / 100
                    answer.innerHTML = '<p><strong>' + rounded_area + '</strong></p><p>square meters</p>'
                } else {
                    answer.innerHTML = ''
                    if (e.type !== 'draw.delete') alert('Use the draw tools to draw a polygon!')
                }
            },
            // 增加长度测量控件
            addRulerControl(){
                this.map.addControl(new RulerControl(), 'top-right');
                this.map.on('ruler.on', ()=>{
                    console.log('ruler.on');
                })
                this.map.on('ruler.off', ()=>{
                    console.log('ruler.off');
                })
            },
            // 增加地图风格切换控件
            addStyleChangeControl(){
                this.map.addControl(new StylesControl({
                    styles: [
                        {
                            label: 'Streets',
                            styleName: 'Mapbox Streets',
                            styleUrl: 'mapbox://styles/mapbox/streets-v9',
                        }, {
                            label: 'Satellite',
                            styleName: 'Satellite',
                            styleUrl: 'mapbox://styles/mapbox/satellite-v9',
                        },
                    ],
                    onChange: (style) => console.log(style),
                }), 'top-left');
            },
            // 增加指北针控件
            addCompassControl(){
                this.map.addControl(new CompassControl(), 'top-right');
            },
            // 增加地图缩放控件
            addZoomControl(){
                this.map.addControl(new ZoomControl(), 'top-right');
            },
            // 增加不同语言标注控件
            addLanguageControl(){
                this.map.addControl(new LanguageControl({
                    language: 'chinese'
                }));
            },
            // InspectControl
            addInspectControl(){
                this.map.addControl(new InspectControl(), 'bottom-right');
            },
            // 增加提示控件
            addTooltipControl(){
                this.map.addLayer({
                    id: '$fill',
                    type: 'fill',
                    source: { type: 'geojson', data: polygon },
                    paint: { 'fill-opacity': 0.3, 'fill-color': '#4264fb' },
                });
                this.map.addControl(new TooltipControl({
                    layer: '$fill'
                }));
            },
    
            // 增加比例尺控件
            addScale(){
                const scale = new mapboxgl.ScaleControl({
                    maxWidth: 80,
                    unit: 'metric'
                });
                this.map.addControl(scale);
            },
    
            // 增加地理编码控件
            addGeocoder() {
                const coordinatesGeocoder = function(query) {
                    const matches = query.match(
                        /^[ ]*(?:Lat: )?(-?\d+\.?\d*)[, ]+(?:Lng: )?(-?\d+\.?\d*)[ ]*$/i
                    );
                    if (!matches) {
                        return null;
                    }
                    function coordinateFeature(lng, lat) {
                        return {
                            center: [lng, lat],
                            geometry: {
                                type: "Point",
                                coordinates: [lng, lat],
                            },
                            place_name: "Lat: " + lat + " Lng: " + lng,
                            place_type: ["coordinate"],
                            properties: {},
                            type: "Feature",
                        };
                    }
    
                    const coord1 = Number(matches[1]);
                    const coord2 = Number(matches[2]);
                    const geocodes = [];
    
                    if (coord1 < -90 || coord1 > 90) {
                        // must be lng, lat
                        geocodes.push(coordinateFeature(coord1, coord2));
                    }
    
                    if (coord2 < -90 || coord2 > 90) {
                        // must be lat, lng
                        geocodes.push(coordinateFeature(coord2, coord1));
                    }
    
                    if (geocodes.length === 0) {
                        // else could be either lng, lat or lat, lng
                        geocodes.push(coordinateFeature(coord1, coord2));
                        geocodes.push(coordinateFeature(coord2, coord1));
                    }
    
                    return geocodes;
                };
                let geocode = new MapboxGeocoder({
                    accessToken: mapboxgl.accessToken,
                    localGeocoder: coordinatesGeocoder,
                    zoom: 4,
                    placeholder: "Try: -40, 170",
                    mapboxgl: mapboxgl,
                    reverseGeocode: true,
                });
                this.map.addControl(geocode, 'top-left');
            }
        },
    };
    </script>
    
    <style scoped>
    #map {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
    }
    
    
    </style>
    
    
    <style>
    /* 去掉mapbox的logo和版权声明 */
    .mapboxgl-ctrl-logo{
        display:none !important;
    }
    .mapboxgl-ctrl-attrib-inner{
        display:none !important; 
    }
    </style>
    

    效果

    1646815307(1).png

    加载OGC地图服务

    <template>
        <div>
            <div id="map"></div>
        </div>
    </template>
    
    <script>
    // 引入mapbox-gl
    import mapboxgl from 'mapbox-gl'
    import 'mapbox-gl/dist/mapbox-gl.css'
    export default {
        name: "mapbox2",
        data() {
            return {
                map: null
            };
        },
        mounted() {
            this.initMap();
            // this.addWmsLayer();
            // this.addWmtsLayer();
            // this.addTmsLayer();
            this.addTmsLayer2();
        },
        methods: {
            // 初始化地图
            initMap() {
                mapboxgl.accessToken =
                    "pk.eyJ1Ijoid2FuZ3poYW9mYW5nIiwiYSI6ImNsMGo1ZTBkYzA5OG8zZG96ZWV3am5xMjMifQ.p3c82gSRyqt5_wdndro8SQ";
                this.map = new mapboxgl.Map({
                    container: "map",
                    style: "mapbox://styles/mapbox/streets-v11",
                    center: [115, 35],
                    zoom: 5,
                });
                this.map.addControl(new mapboxgl.FullscreenControl(), 'bottom-right');
            },
            // 加载wms地图服务
            addWmsLayer(){
                let wmsUrl = "http://localhost:8085/geoserver/test/wms?service=WMS&format=image/png&transparent=true&request=GetMap&layers=test:guo&styles=&bbox={bbox-epsg-3857}&width=256&height=256&srs=EPSG:3857";
                this.map.on('load', ()=>{
                    this.map.addSource('geoserver-wms-source', {
                        type: "raster",
                        scheme: 'xyz',
                        tiles: [wmsUrl],
                        tileSize: 256
                    })
                    this.map.addLayer({
                        id: "geoserver-wms-layer",
                        type: "raster",
                        source: "geoserver-wms-source",
                        'source-layer': "test:guo"
                    });
                })
                setTimeout(() => {
                    this.map.removeLayer('geoserver-wms-layer');
                }, 5000);
            },
            // 加载wmts地图服务
            addWmtsLayer(){
                let wmtsUrl = "http://localhost:8085/geoserver/gwc/rest/wmts/test:guo/line/EPSG:900913/EPSG:900913:{z}/{y}/{x}?format=image/png";
                this.map.on('load', ()=>{
                    this.map.addSource('geoserver-wmts-source', {
                        type: "raster",
                        scheme: 'xyz',
                        tiles: [wmtsUrl],
                        tileSize: 256
                    })
                    this.map.addLayer({
                        id: "geoserver-wmts-layer",
                        type: "raster",
                        source: "geoserver-wmts-source",
                        'source-layer': "test:guo"
                    });
                })
                setTimeout(() => {
                    this.map.removeLayer('geoserver-wmts-layer');
                }, 5000);
            },
            // 加载tms地图服务
            addTmsLayer(){
                let tmsUrl = "http://localhost:8085/geoserver/gwc/service/tms/1.0.0/test%3Aguo@EPSG%3A900913@png/{z}/{x}/{y}.png";
                this.map.on('load', ()=>{
                    this.map.addSource('geoserver-tms-source', {
                        type: "raster",
                        scheme: 'tms',
                        tiles: [tmsUrl],
                        tileSize: 256
                    })
                    this.map.addLayer({
                        id: "geoserver-tms-layer",
                        type: "raster",
                        source: "geoserver-tms-source",
                        'source-layer': "test:guo"
                    });
                })
                setTimeout(() => {
                    this.map.removeLayer('geoserver-tms-layer');
                }, 5000);
            },
            // 加载tms矢量瓦片地图服务
            addTmsLayer2(){
                let tmsUrl = "http://localhost:8085/geoserver/gwc/service/tms/1.0.0/test%3Aguo@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf";
                this.map.on('load', ()=>{
                    this.map.addSource('geoserver-tms-source', {
                        type: "vector",
                        scheme: 'tms',
                        tiles: [tmsUrl]
                    })
                    this.map.addLayer({
                        id: "geoserver-tms-layer",
                        type: "line",
                        source: "geoserver-tms-source",
                        'source-layer': "guo",
                        paint: {
                            'line-color': '#0000ff',
                            'line-width': 2
                        }
                    });
                })
                setTimeout(() => {
                    // this.map.removeLayer('geoserver-tms-layer');
                }, 5000);
            }
        },
    };
    </script>
    
    <style scoped>
    #map {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
    }
    
    
    </style>
    
    
    <style>
    /* 去掉mapbox的logo和版权声明 */
    .mapboxgl-ctrl-logo{
        display:none !important;
    }
    .mapboxgl-ctrl-attrib-inner{
        display:none !important; 
    }
    </style>
    

    效果

    image.png

    增加点线面几何图形

    <template>
        <div>
            <div id="map"></div>
        </div>
    </template>
    
    <script>
    // 引入mapbox-gl
    import mapboxgl from "mapbox-gl";
    import "mapbox-gl/dist/mapbox-gl.css";
    export default {
        name: "mapbox3",
        data() {
            return {
                map: null,
            };
        },
        mounted() {
            this.initMap();
            this.addPoint();
            this.addLine();
            this.addPolygon();
        },
        methods: {
            // 初始化地图
            initMap() {
                mapboxgl.accessToken =
                    "pk.eyJ1Ijoid2FuZ3poYW9mYW5nIiwiYSI6ImNsMGo1ZTBkYzA5OG8zZG96ZWV3am5xMjMifQ.p3c82gSRyqt5_wdndro8SQ";
                this.map = new mapboxgl.Map({
                    container: "map",
                    style: "mapbox://styles/mapbox/streets-v11",
                    center: [115, 35],
                    zoom: 5,
                });
                this.map.addControl(
                    new mapboxgl.FullscreenControl(),
                    "bottom-right"
                );
            },
            // 增加点
            addPoint() {
                this.map.on("load", () => {
                    const marker1 = new mapboxgl.Marker()
                        .setLngLat([123, 30])
                        .addTo(this.map);
    
                    const marker2 = new mapboxgl.Marker({
                        color: "black",
                        rotation: 45,
                    })
                        .setLngLat([120, 30])
                        .addTo(this.map);
                });
            },
            // 增加线
            addLine() {
                this.map.on("load", () => {
                    this.map.addSource("route", {
                        type: "geojson",
                        data: {
                            type: "Feature",
                            properties: {},
                            geometry: {
                                type: "LineString",
                                coordinates: [
                                    [122, 34.18],
                                    [122, 35.74],
                                    [123, 34],
                                    [124, 34]
                                ],
                            },
                        },
                    });
                    this.map.addLayer({
                        id: "route",
                        type: "line",
                        source: "route",
                        layout: {
                            "line-join": "round",
                            "line-cap": "round",
                        },
                        paint: {
                            "line-color": "#00ff00",
                            "line-width": 8,
                        },
                    });
                });
            },
            // 增加面
            addPolygon(){
                this.map.on('load', () => {
                    this.map.addSource('maine', {
                        'type': 'geojson',
                        'data': {
                            'type': 'Feature',
                            'geometry': {
                                'type': 'Polygon',
                                'coordinates': [
                                    [
                                        [117.13734, 25.13745],
                                        [118.96466, 24.8097],
                                        [118.11617, 23.68405],
                                        [117.13734, 25.13745]
                                    ]
                                ]
                            }
                        }
                    })
    
                    this.map.addLayer({
                        'id': 'maine',
                        'type': 'fill',
                        'source': 'maine', 
                        'layout': {},
                        'paint': {
                            'fill-color': '#0080ff', 
                            'fill-opacity': 0.5
                        }
                    });
    
                    this.map.addLayer({
                        'id': 'outline',
                        'type': 'line',
                        'source': 'maine',
                        'layout': {},
                        'paint': {
                            'line-color': '#000',
                            'line-width': 3
                        }
                    });
                })
            }
        },
    };
    </script>
    
    <style scoped>
    #map {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
    }
    </style>
    
    <style>
    /* 去掉mapbox的logo和版权声明 */
    .mapboxgl-ctrl-logo {
        display: none !important;
    }
    .mapboxgl-ctrl-attrib-inner {
        display: none !important;
    }
    </style>
    

    效果

    image.png

    相关文章

      网友评论

        本文标题:Mapbox入门教程

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