maptalk第一模块(地图显示,平移旋转,常用控件,同步地图,添加工具栏,获取地图信息)

完整demo在底部,此部分为文字注释版本
<!DOCTYPE html> <html> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>地图 - 限制地图区域</title> <style type="text/css"> html,body{margin:0px;height:100%;width:100%} .container{width:100%;height:100%} </style> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/maptalks/dist/maptalks.css"> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/maptalks/dist/maptalks.min.js"></script> <body> <div id="map" class="container"></div>

 <div id="map2" class="map2"></div>
        <!-- <canvas id="map" class="map"></canvas> -->
        <div class="text">
            <p>mapCenter:{{mapCenter}}</p>
            <p>zoom:{{zoom}}</p>
            <p>minZoom:{{minZoom}}</p>
            <p>maxZoom:{{maxZoom}}</p>
            <p>extent:{{extent}}</p>
            <p>bearing:{{bearing}}</p>
        </div>


// 地图实例放在canvas里
<canvas width=600 height=300 id="map" style="border:1px solid"> <script> var map = new maptalks.Map('map', { center: [-0.113049,51.498568], // 地图中心坐标 zoom: 14, // 缩放比例
     dragPitch : true, // 是否开始鼠标拖动偏移(左键)
        dragRotate : true, // 是否开启鼠标拖动旋转(右键或者ctrl+左键)
     zoomControl : true, // add zoom control // 添加缩放比例控件

    seamlessZoom: true,// 细微缩放,官方说由此控制是否使用无缝缩放模式(并未搞清楚有何区别)

scaleControl : true, // add scale control // 比例尺控件 overviewControl : true, // add overview control // 缩略图控件
        centerCross : true, // 地图中心显示红色十字符号
        baseLayer: new maptalks.TileLayer('base', {
          urlTemplate: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
          subdomains: ['a','b','c','d'],
          attribution: '&copy; <a href="http://osm.org">OpenStreetMap</a> contributors, &copy; <a href="https://carto.com/">CARTO</a>'
        }),
        layers : [
          new maptalks.VectorLayer('v')
        ]
      });

      var extent = map.getExtent();// 获取地图范围

      // set map's max extent to map's extent at zoom 14
      map.setMaxExtent(extent); // 限制最大地图范围

      map.setZoom(map.getZoom() - 2, { animation : false });// 更改缩放比例

      map.getLayer('v')
        .addGeometry( // 添加新的几何图形
          new maptalks.Polygon(extent.toArray(), { 新的多边形
            symbol : { 'polygonOpacity': 0, 'lineWidth': 5 }
          })
        );
 function up() {
        map.panBy([0, -200]);//设置偏移量[x,y]
      }

      function down() {
        map.panBy([0, 200]);
      }

      function left() {
        map.panBy([-200, 0]);
      }

      function right() {
        map.panBy([200, 0]);
      }

      function toCoordinate() {
        var symbol = {  // 添加的标志样式,等同于设置单个marker
          markerType : 'x', 
          markerLineColor : '#f00',
          markerLineWidth : 4,
          markerWidth : 20,
          markerHeight : 20
        };
        var coordinate = map.getCenter().add(0.008, 0.008); // 选择marker的位置
        map.getLayer('v')
          .clear()// 清空之前设置的marker
          .addGeometry(new maptalks.Marker(coordinate, { 'symbol' : symbol })); //添加新的坐标中心时的marker
        map.panTo(coordinate);
      }
 
      var toolbar = new maptalks.control.Toolbar({ // 添加自定义工具栏,item是工具栏显示的内容,click为触发的事件名
        items: [
          {
            item: '↑',
            click: up
          },
          {
            item: '↓',
            click: down
          },
          {
            item: '←',
            click: left
          },
          {
            item: '→',
            click: right
          },
          {
            item: 'pan to',
            click: toCoordinate
          }
        ]
      }).addTo(map);

getStatus(); // 获取地图状态

      function getStatus() {
        var extent = map.getExtent(), // 获取地图范围
          ex = [
            '{',
            'xmin:' + extent.xmin.toFixed(5),
            ', ymin:' + extent.ymin.toFixed(5),
            ', xmax:' + extent.xmax.toFixed(5),
            ', ymax:' + extent.xmax.toFixed(5),
            '}'
          ].join('');
        var center = map.getCenter(); // 获取地图中心点
        var mapStatus = [
          'Center : [' + [center.x.toFixed(5), center.y.toFixed(5)].join() + ']',
          'Extent : ' + ex,
          'Size : ' + map.getSize().toArray().join(),// 获取地图的尺寸(即地图的长宽)
          'Zoom : '   + map.getZoom(),// 获取地图缩放比例
          'MinZoom : ' + map.getMinZoom(),// 获取地图最小缩放比例
          'MaxZoom : ' + map.getMaxZoom(), // 获取地图最大缩放比例
          'Projection : ' + map.getProjection().code
        ];
var center = map.getCenter();
      var polygon = new maptalks.Polygon([
        center.add(-0.005, 0.005),
        center.add(0.005, 0.005),
        center.add(0.005, -0.005),
        center.add(-0.005, -0.005), // 绘制多边形需要从第三象限开始绘制
      ], {
        symbol : {
          polygonFill : '#fff',
          polygonOpacity : 0.5
        }
      }); //围绕地图中心点画一个多边形,四个角坐标以中心为基准
      map.getLayer('v').addGeometry(polygon);

      function fitExtent() {
        // fit map's extent to polygon's
        // 0 is the zoom offset
        map.fitExtent(polygon.getExtent(), 0); // 设置为适合给定范围,并使用可能的最大缩放级别,参数一为给定的范围,参数二为指定的缩放比例
      }
// 限制缩放级别可直接在声明地图时添加maxzoom和minzoom或者使用以下方法:
 map.setMinZoom(14).setMaxZoom(14);

// 地图实例放在canvas里

// var res = (window.devicePixelRatio || (window.screen.deviceXDPI / window.screen.logicalXDPI)) > 1;
// if (res) {
// // retina, see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
// var canvas = document.getElementById('map');
// var r = 2;
// canvas.width *= r;
// canvas.height *= r;
// canvas.style.cssText += 'width:' + Math.round(canvas.width / r) + 'px;height:' + Math.round(canvas.height / r) + 'px';
// }  // 这一部分为官方给的,感觉与canvas的绑定不太相关,即使删掉也没有什么影响,可能是为了解决未发现的bug?

var map = new maptalks.Map('map', {
center: [-0.113049, 51.498568],
zoom: 14,
zoomControl: true, // ignored in a canvas container
scaleControl: true, // ignored in a canvas container
baseLayer: new maptalks.TileLayer('base', {
urlTemplate: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
subdomains: ['a', 'b', 'c', 'd'],
attribution: '© <a href="http://osm.org">OpenStreetMap</a> contributors, © <a href="https://carto.com/">CARTO</a> '
})
}); // 这一段即可完成绑定,与div并无不同的样子

 // 监听点击事件
 map.on('click', function (param) {
        var infoDom = document.getElementById('info');
        infoDom.innerHTML = '<div>' + new Date().toLocaleTimeString() +
          ': click map on ' + param.coordinate.toFixed(5).toArray().join() + '</div>' +
          infoDom.innerHTML;
      });

 //  利用高德地图作为地图

const map = new maptalks.Map('map', {
            center: [-0.113049, 51.498568],
            zoom: 14,
            minZoom: 2,
            maxZoom: 20,
            centerCross: true,
            dragPitch: true,
            dragRotate: true,
            zoomControl: true,
            // seamlessZoom: true,
            scaleControl: true,
            overviewControl: true,
            baseLayer: new maptalks.TileLayer('base', {
                urlTemplate: 'http://wprd{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&z={z}&x={x}&y={y}&scl=1&ltype=11', // 这里的链接控制底图来源
                subdomains: ['01', '02', '03', '04'], //  此处不能继续用abcd,否则底图会失效
                // attribution: `'&copy; <a href="http://osm.org">OpenStreetMap</a> contributors, &copy;
                //  <a href="https://carto.com/">CARTO</a>'`,
            }),
 
// 这里是同步地图 (设置同步地图时需要设置绑定的元素的宽和高,不然不会显示。
 
const map2 = new maptalks.Map('map2', {
            center: map.getCenter(),
            zoom: map.getZoom(),
            draggable : false,        // disable draggble
            scrollWheelZoom : false,  // disable scroll wheel zoom
            dblClickZoom : false,     // disable doubleclick
            baseLayer: new maptalks.TileLayer('base1', {
            urlTemplate: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
            subdomains: ['a', 'b', 'c', 'd'],
            // attribution: '&copy; <a href="http://osm.org">OpenStreetMap</a> contributors, &copy; <a href="https://carto.com/">CARTO</a>'
            }),
        });
</script> 

</body>

</html>

第一部分的完整demo
<template>
    <div class="app">
        <div id="map" class="map"></div>
        <div id="map2" class="map2"></div>
        <!-- <canvas id="map" class="map"></canvas> -->
        <div class="text">
            <p>mapCenter:{{mapCenter}}</p>
            <p>zoom:{{zoom}}</p>
            <p>minZoom:{{minZoom}}</p>
            <p>maxZoom:{{maxZoom}}</p>
            <p>extent:{{extent}}</p>
            <p>bearing:{{bearing}}</p>
        </div>
        <div>
        </div>
    </div>
</template>
<script lang="ts">
import * as maptalks from 'maptalks';
import {Component, Vue} from 'vue-property-decorator';
import 'maptalks/dist/maptalks.css'
@Component
export default class App extends Vue {
    private mapCenter: any = '';
    private zoom: any = '';
    private minZoom: any = '';
    private maxZoom: any = '';
    private extent: any = '';
    private bearing: any = '';
    private newMap() {
        // const screen: any = window.screen;
        // const canvas: any = document.getElementById('map');
        // const res = (window.devicePixelRatio || (screen.deviceXDPI / screen.logicalXDPI)) > 1;
        // if (res) {
        //     // retina, see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
        //     const r: number = 2;
        //     console.log(canvas.width);
        //     canvas.width *= r;
        //     canvas.height *= r;
        //     canvas.style.cssText += 'width:' + Math.round(canvas.width / r) + 'px;height:'
        //     + Math.round(canvas.height / r) + 'px';
        // }
        const map = new maptalks.Map('map', {
            center: [-0.113049, 51.498568],
            zoom: 14,
            minZoom: 2,
            maxZoom: 20,
            centerCross: true,
            dragPitch: true,
            dragRotate: true,
            zoomControl: true,
            // seamlessZoom: true,
            scaleControl: true,
            overviewControl: true,
            baseLayer: new maptalks.TileLayer('base', {
                urlTemplate: 'http://wprd{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&z={z}&x={x}&y={y}&scl=1&ltype=11',
                subdomains: ['01', '02', '03', '04'],
                // attribution: `'&copy; <a href="http://osm.org">OpenStreetMap</a> contributors, &copy;
                //  <a href="https://carto.com/">CARTO</a>'`,
            }),
            layers : [
                new maptalks.VectorLayer('v'),
            ],
        });
        const map2 = new maptalks.Map('map2', {
            center: map.getCenter(),
            zoom: map.getZoom(),
            draggable : false,        // disable draggble
            scrollWheelZoom : false,  // disable scroll wheel zoom
            dblClickZoom : false,     // disable doubleclick
            baseLayer: new maptalks.TileLayer('base1', {
            urlTemplate: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
            subdomains: ['a', 'b', 'c', 'd'],
            // attribution: '&copy; <a href="http://osm.org">OpenStreetMap</a> contributors, &copy; <a href="https://carto.com/">CARTO</a>'
            }),
        });

        const toolbar = new maptalks.control.Toolbar({
            items: [{
                item: '上移',
                click: () => map.panBy([0, 200]),
            },
            {
                item: '下移',
                click: () => map.panBy([0, -200]),
            },
            {
                item: '左移',
                click: () => map.panBy([200, 0]),
            },
            {
                item: '右移',
                click: () => map.panBy([-200, 0]),
            },
            {
                item: '适应窗口',
                click: () => {
                    const center = map.getCenter();
                    const polygon = new maptalks.Polygon([
                    center.add(-0.004, -0.004),
                    center.add(-0.012, -0.004),
                    center.add(-0.008, 0),
                    center.add(-0.012, 0.004),
                    center.add(-0.004, 0.004),
                    center.add(0, 0.008),
                    center.add(0.004, 0.004),
                    center.add(0.012, 0.004),
                    center.add(0.008, 0),
                    center.add(0.012, -0.004),
                    center.add(0.004, -0.004),
                    center.add(0.00, -0.008), // 这里的多边形绘制似乎是由第三象限开始的,如果从第二象限开始则第三象限点位连线会乱
                    ], {
                        symbol: {
                            polygonFill: '#000',
                            polygonOpacity: 0.5,
                        },
                    });
                    map.getLayer('v').addGeometry(polygon);
                    map.fitExtent(polygon.getExtent(), 0);
                },
            }],
        }).addTo(map);
        map.on('moving moveend', (e) => {
            map2.setCenter(e.target.getCenter());
        });
        map.on('rotate', (e) => {
            map2.setBearing(e.target.getBearing());
        });
        map.on('pitch', (e) => {
            map2.setPitch(e.target.getPitch());
        });
        map.on('zooming zoomend', (e) => {
            map2.setCenterAndZoom(e.target.getCenter(), e.target.getZoom());
        });
        map.on('moveend', () => {
            const center = map.getCenter();
            this.mapCenter = center.toFixed(5);
            this.zoom = map.getZoom();
            this.minZoom = map.getMinZoom();
            this.maxZoom = map.getMaxZoom();
            this.extent = map.getExtent();
            this.bearing = map.getBearing();
            const polygon = new maptalks.Polygon([
                center.add(-0.005, 0.005), // 右下
                center.add(0.005, 0.005), // 右上
                center.add(0.008, -0.005), // 右下
                center.add(-0.008, -0.005), // 左下
            ], {
                symbol: {
                    polygonFill: '#fc0',
                    polygonOpacity: 0.1,
                },
            });
            map.getLayer('v').addGeometry(polygon);
        });
        new maptalks.VectorLayer('v1', new maptalks.Marker(map.getCenter()))
      .addTo(map);
    };
    // private getMapInfo() {
    //     // const tooltip = new maptalks.MapTool
    // }
    private mounted() {
        this.newMap();
    }
}
</script>
<style scoped lang="scss">
.app{
    width: 100%;
    height: 100%;
    font-size: 14px;
    display: flex;
    flex-direction: row;
    .map{
        flex: 1;
        width: 100%;
        height: 100%;
    }
    .map2{
        flex: 1;
        width: 100%;
        height: 100%;
    }
    .text{
        position: absolute;
        top:10px;
        left: 50px;
    }
}

</style>

 

 
posted @ 2021-10-11 18:15  妄欢  阅读(1137)  评论(0编辑  收藏  举报