效果图
代码
<template>
<div ref="mapEl" :style="{ width: 100vw, height: 100vh}"></div>
</template>
<script setup>
import "ol/ol.css";
import TileLayer from "ol/layer/Tile"; // 切片
import VectorLayer from "ol/layer/Vector"; // 矢量
import VectorSource from "ol/source/Vector";
import { Map, View, Feature } from "ol";
import { XYZ } from "ol/source";
import { Style, Stroke, Fill } from "ol/style";
import { Polygon, MultiPolygon } from "ol/geom";
import { fromLonLat } from "ol/proj";
import { defaults } from "ol/control";
import areaGeo from "./vtj.json";
const mapEl = ref(null);
const state = reactive({
map: null,
areaLayer: null,
});
onMounted(() => {
init();
addArea(areaGeo);
});
// 初始化地图
const init = () => {
state.map = new Map({
target: mapEl.value,
controls: new defaults({
zoom: false,
}),
view: new View({
center: ["105.3683244", "36.915085"],
projection: "EPSG:4326",
zoom: 5,
minZoom: 4,
maxZoom: 18,
}),
});
var gaodeMapLayer = new TileLayer({
customData: "background",
source: new XYZ({
url: "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
}),
zIndex: 0,
});
state.map.addLayer(gaodeMapLayer);
state.map.getView().setCenter([116.395645038, 39.9299857781]);
};
// 设置区域
const addArea = (geo = []) => {
if (geo.length == 0) return false;
// 设置图层
state.areaLayer = new VectorLayer({
source: new VectorSource({
features: [],
}),
});
let areaFeatureArray = [];
// 添加图层
state.map.addLayer(state.areaLayer);
const style = new Style({
fill: new Fill({ color: "#4e98f4" }),
stroke: new Stroke({
width: 3,
color: [71, 137, 227, 1],
}),
});
geo.forEach((g) => {
areaFeatureArray = g.features.map((lineData, index) => {
if (lineData.geometry.type == "MultiPolygon") {
return new Feature({
geometry: new MultiPolygon(lineData.geometry.coordinates),
style: style,
});
} else if (lineData.geometry.type == "Polygon") {
return new Feature({
geometry: new Polygon(lineData.geometry.coordinates),
style: style,
});
}
});
});
state.areaLayer.getSource().addFeatures(areaFeatureArray);
};
</script>
import areaGeo from "./vtj.json"; 这个文件需要去数据源 , 下载JSON API,
有问题留评论区,工作日看到会回复的