Polygon 多边形
使用 leaflet、vue 创建多边形。
示例
代码实现
vue
<script setup>
import { defineAsyncComponent } from 'vue';
const InitMap = defineAsyncComponent(() =>
import('../../components/InitMapTianditu.vue')
);
// 矩形
const rectData = [
{
lat: 31.979921773775636,
lng: 118.75190734863283
},
{
lat: 32.042300782300785,
lng: 118.75190734863283
},
{
lat: 32.042300782300785,
lng: 118.85696411132814
},
{
lat: 31.979921773775636,
lng: 118.85696411132814
}
];
// 多边形
const polygonData = [
{
lat: 32.10347253417688,
lng: 118.65921020507814
},
{
lat: 32.0982308450108,
lng: 118.71826171875001
},
{
lat: 32.04404911449747,
lng: 118.72169494628906
},
{
lat: 32.02539851636276,
lng: 118.67843627929688
},
{
lat: 32.036472767156546,
lng: 118.64135742187501
},
{
lat: 32.06852225858854,
lng: 118.64341735839845
},
{
lat: 32.06968748310397,
lng: 118.68530273437501
},
{
lat: 32.08599906719349,
lng: 118.66744995117189
}
];
const mapLoad = (map) => {
// 配置参考 https://leafletjs.cn/reference.html#polygon
L.polygon(rectData, { color: 'red', fillColor: 'green' }).addTo(map);
L.polygon(polygonData, { color: 'red' }).addTo(map);
};
</script>
<template>
<init-map @map-load="mapLoad"></init-map>
</template>
<style scoped></style>
vue
<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import L from 'leaflet';
const props = defineProps({
center: {
type: Array,
default: [32.0237855, 118.8075675]
}
})
const emit = defineEmits(['mapLoad']);
const mapRef = ref();
const initMap = () => {
const map = L.map(mapRef.value, {
center: props.center,
zoom: 11,
minZoom: 1,
maxZoom: 18
});
const mapType = 'vec';
L.tileLayer(
'https://t{s}.tianditu.gov.cn/' +
mapType +
'_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=' +
mapType +
'&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=b72aa81ac2b3cae941d1eb213499e15e',
{
subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
attribution:
'© <a href="http://lbs.tianditu.gov.cn/home.html">天地图 GS(2022)3124号 - 甲测资字1100471</a>'
}
).addTo(map);
const mapLabelType = 'cva';
L.tileLayer(
'https://t{s}.tianditu.gov.cn/' +
mapLabelType +
'_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=' +
mapLabelType +
'&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=b72aa81ac2b3cae941d1eb213499e15e',
{
subdomains: ['0', '1', '2', '3', '4', '5', '6', '7']
}
).addTo(map);
// 地图初始化完成发送事件
emit('mapLoad', map);
return map;
};
const mapObj = ref();
// 在 onMounted 中初始化地图
onMounted(() => {
mapObj.value = initMap();
});
const removeMap = () => {
if (mapObj.value) {
mapObj.value.remove();
}
};
// 在组件卸载时删除地图
onUnmounted(() => {
removeMap();
});
</script>
<template>
<div ref="mapRef" class="map"></div>
</template>
<style scoped>
.map {
height: 40vh;
z-index: 0;
}
</style>