- 项目环境:
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()
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",
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",
center: [101.501624, 24.966424],
zoom: 5,
maxZoom: 19,
minZoom: 1,
constrainResolution: true,
smoothResolutionConstraint: false,
}),
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);
}
});
}
function addMarker(lnglat: any, options = {}) {
const lnglats = lnglat;
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>