vue3.0 + typescript openlayers实现地图标点、移动、画线、显示范围、测量长度、测量面积、画三角形、画正方形、画圆、线选、画笔、清除测量、清除、地图上展示弹窗等功能
warning:
这篇文章距离上次修改已过185天,其中的内容可能已经有所变动。
以下是一个简化的示例,展示了如何在Vue 3和TypeScript中使用OpenLayers实现基本的地图功能,包括标点、移动、画线、显示范围以及测量长度。
<template>
<div id="map" class="map"></div>
</template>
<script lang="ts">
import { ref, onMounted, defineComponent } from 'vue';
import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import { Draw, Modify, Snap } from 'ol/interaction';
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style';
import { Pointer } from 'ol/control';
import { LineString, Polygon } from 'ol/geom';
export default defineComponent({
setup() {
const map = ref<Map>();
onMounted(() => {
map.value = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM(),
}),
],
view: new View({
center: [0, 0],
zoom: 2,
}),
});
// 添加交互
const draw = new Draw({
source: new VectorSource(),
type: 'Point',
});
map.value.addInteraction(draw);
const modify = new Modify({
source: draw.getSource(),
});
map.value.addInteraction(modify);
const snap = new Snap({
source: draw.getSource(),
});
map.value.addInteraction(snap);
// 添加绘制图层
map.value.addLayer(new VectorLayer({
source: draw.getSource(),
style: new Style({
image: new CircleStyle({
radius: 5,
fill: new Fill({ color: 'blue' }),
stroke: new Stroke({ color: 'white', width: 2 }),
}),
}),
}));
// 添加测量长度控件
const lengthControl = new Pointer({
html: '<div>长度:<output id="length">0</output> 米</div>',
});
map.value.addControl(lengthControl);
draw.on('drawend', (event) => {
const geometry = event.feature.getGeometry();
let length = 0;
if (geometry instanceof LineString) {
length = geometry.getLength();
} else if (geometry instanceof Polygon) {
length = geometry.getLinearRing(0).getLength();
}
(lengthControl.element.querySelector('#length') as HTMLElement).innerTex
评论已关闭