ol(openlayers)使用记录
openlayers+vue3+ts+vite开发地图模块
·
- 项目环境:
vue3+ts+vite
- ol版本:
7.1.0
- 安装:
yarn add ol
或者npm i ol
- 使用:保护区和标记点
<template>
<div id="map" class="my_map">
<div>我在地域</div>
</div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, shallowRef } from "vue";
import "ol/ol.css"; // 样式
import { Map, View, Feature } from "ol";
import TileLayer from "ol/layer/Tile";
import VectorSource from "ol/source/Vector.js";
import VectorLayer from "ol/layer/Vector.js";
import { XYZ, Cluster } from "ol/source";
import { defaults, ZoomSlider, Attribution, ScaleLine, FullScreen } from "ol/control";
import { Point, Polygon, MultiPolygon } from "ol/geom";
import { Style, Icon, Fill, Stroke, Text } from "ol/style";
import { getArea } from "@/api/species";
import { useRouter } from "vue-router";
import polygonData from '@/utils/feature.json'
const map = shallowRef(); // 存放地图实例
const router = useRouter();
const state = reactive({
loading: false,
name: '',
mapData: [] as any[]
})
// 区域默认样式
let defaultStyle = new Style({
fill: new Fill({
color: "#16a08580"
}),
stroke: new Stroke({
width: 2,
color: '#16a085'
})
})
// 区域高亮样式
let hightStyle = new Style({
fill: new Fill({
color: "#40e0d080"
}),
stroke: new Stroke({
width: 2,
color: '#40e0d0'
})
})
let highlight: any; // 设置高亮元素变量
onMounted(() => {
state.name = router.currentRoute.value.query.name as string || '';
initMap()
// onLoad()
addArea(polygonData.features)
addMarker([[101.501624, 24.966174], [101.501624, 24.966265], [101.501624, 21.966456], [101.501624, 24.116447], [101.501624, 24.966438], [101.501624, 24.966429], [101.501624, 24.966414]])
})
// 实例化地图
function initMap() {
// 清除地图节点中的其他元素
let map_dom = document.querySelector(".my_map");
if (map_dom && map_dom.children[0]) {
map_dom!.removeChild(map_dom!.children[0]);
}
// 地图实例
map.value = new Map({
target: "map", // 挂载元素id
// 设置地图图层
layers: [
new TileLayer({
source: new XYZ({
url: "http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=你的key",
}),
}), // 天地图瓦片底图
new TileLayer({
source: new XYZ({
url: "http://t0.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=你的key",
}),
}), // 天地图标注
],
// 设置显示地图的视图
view: new View({
// 设置地图中心范围
projection: "EPSG:4326", //EPSG:3857坐标系(投影坐标) EPSG:4326 坐标系(地理坐标)
center: [101.501624, 24.966424], // 定义地图显示中心于经度,纬度
zoom: 5, // 缩放级别
maxZoom: 19, // 最大缩放级别
minZoom: 1, // 最小缩放级别
constrainResolution: true, //自动缩放到距离最近的整数级,非整数级别时地图会糊
smoothResolutionConstraint: false, //2.关闭无级缩放地图
}),
//设置地图控件
controls: defaults().extend([
new ZoomSlider(), // 缩放按钮
new Attribution(), // 版权信息
new ScaleLine(), // 比例尺
new FullScreen(), // 全屏控件
]),
});
}
/**
* 设置区域
*/
function addArea(geo: any[]) {
if (geo.length == 0) return false;
let areaFeature = null as any;
// 设置图层
let areaLayer = new VectorLayer({
style: defaultStyle, // 默认样式
source: new VectorSource({
features: []
})
});
// 添加图层
map.value.addLayer(areaLayer);
geo.forEach((item: any) => {
if (item.geometry.type == "MultiPolygon") {
areaFeature = new Feature({
properties: item.properties,
geometry: new MultiPolygon(
item.geometry.coordinates
)
});
} else if (item.geometry.type == "Polygon") {
areaFeature = new Feature({
properties: item.properties,
geometry: new Polygon(
item.geometry.coordinates
)
});
}
areaLayer!.getSource()!.addFeatures([areaFeature]);
});
//悬浮切换图层颜色
map.value.on("pointermove", function (evt: any) {
// 是否是拖拽事件
if (evt.dragging) {
return;
}
let feature = map.value.forEachFeatureAtPixel(evt.pixel, function (feature: any) {
return feature;
});
// 是否规划区域
if (feature && (feature.getGeometry() instanceof Polygon || feature.getGeometry() instanceof MultiPolygon)) {
map.value.getTargetElement().style.cursor = "pointer"
if (highlight) {
highlight.setStyle(defaultStyle)
}
highlight = feature;
feature.setStyle(hightStyle)
} else {
map.value.getTargetElement().style.cursor = ""
if (highlight) {
highlight.setStyle(defaultStyle)
}
}
});
//单机图层
map.value.on("singleclick", function (evt: any) {
// 判断点击的坐标是否在保护区范围内
let feature = map.value.forEachFeatureAtPixel(evt.pixel, function (feature: any) {
return feature;
});
if (feature != null) {
let properties = feature.get("properties");
console.log(feature.getGeometry(), properties); //{"name": "高黎贡山","ID": 95, "Area": 4800000000,"sheng": ""}
// todo 点击事件
}
});
}
//添加标记点
function addMarker(lnglat: any, options = {}) {
const lnglats = lnglat;
// 创建Feature对象集合
const features = [];
for (let i = 0; i < lnglats.length; i++) {
if (lnglats[i][0] !== '' && lnglats[i][1] !== '') {
const numAry = new Feature({
properties: {
name: 'dsfsasadf'
},
geometry: new Point([parseFloat(lnglats[i][0]), parseFloat(lnglats[i][1])]),
});
features.push(numAry);
}
}
const clusterSource = new Cluster({
distance: 0.1, //标注之间
source: new VectorSource({
features: features,
}),
});
const iconStyle = new Style({
image: new Icon({
opacity: 1,
src: 'https://cdn-icons-png.flaticon.com/512/1483/1483336.png',
anchor: [0.5, 3], // 偏移位置
anchorOrigin: "bottom-left",
anchorXUnits: "fraction",
anchorYUnits: "pixels",
offsetOrigin: "top-right",
offset: [0, 1], //偏移量设置
scale: 0.08, //图标缩放比例
}),
text: new Text({
text: '测试名称',
fill: new Fill({
color: "#fff",
}),
offsetY: -50,
})
});
const clusters = new VectorLayer({
source: new VectorSource({
features: features,
}),
style: iconStyle,
...options,
});
map.value!.addLayer(clusters);
}
// 请求数据
function onLoad() {
try {
if (!state.name) return;
state.loading = true;
getArea(state.name).then(res => {
if (res.data.code === 200) {
if (res.data.data instanceof Array) {
state.mapData = res.data.data;
addMarker(state.mapData, { name: "block" });
}
}
state.loading = false;
});
} catch (e) {
state.loading = false;
}
}
</script>
<style>
.my_map {
width: 100%;
height: 800px;
}
</style>
更多推荐
已为社区贡献1条内容
所有评论(0)