<template>
<div id="map" style=" width:1080px;height:700px; background-color: gray;"></div>
<div id="info"> </div>
</template>
<script>
import GeoJSON from "ol/format/GeoJSON";
import Map from "ol/Map";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import View from "ol/View";
import { Fill, Stroke, Style } from "ol/style";
import XYZ from "ol/source/XYZ";
import TileLayer from "ol/layer/Tile";
import { useMessage } from 'naive-ui';
export default {
components: {},
data() {
return {
map: null,
featureOverlay: null,
selFeature: null,
url:
"http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
};
},
mounted() {
let style = new Style({
fill: new Fill({
color: "#eeeeee",
}),
});
//数据图层:
let vectorLayer = new VectorLayer({
source: new VectorSource({
url: "/public/ecoregions.json",
format: new GeoJSON(),
}),
style: function (curFeature) {
let color = "#f00"; //curFeature.get("COLOR") || "#eeeeee";
style.getFill().setColor(color);
return style;
},
opacity: 0.2,
});
//瓦片图层:
var AMapLayer = new TileLayer({
source: new XYZ({
url: this.url,
}),
});
this.map = new Map({
layers: [AMapLayer, vectorLayer],
target: "map",
view: new View({
center: [0, 0],
zoom: 3,
}),
});
//图形叠加层:
this.featureOverlay = new VectorLayer({
source: new VectorSource(),
map: this.map,
style: new Style({
stroke: new Stroke({
color: "rgba(255, 0, 255, 1)",
width: 2,
}),
}),
});
//添加地图事件:
this.map.on("pointermove", (evt) => {
if (!evt.dragging) {
let pixel = this.map.getEventPixel(evt.originalEvent);
this.displayFeatureInfo(pixel, false);
}
});
//this.map.on("click", (evt) => this.displayFeatureInfo(evt.pixel));
this.map.on("click", (evt) => {
let pixel = this.map.getEventPixel(evt.originalEvent);
this.displayFeatureInfo(pixel, true);
});
},
methods: {
displayFeatureInfo(pixel, showName) {
//查找指定像素所在的图形
let curFeature = this.map.forEachFeatureAtPixel(pixel, (feature) => {
return feature;
});
//更新信息栏:
let info = document.getElementById("info");
info.innerHTML = curFeature
? curFeature.get("NAME") || " "
: " ";
if (showName && curFeature){
console.log(useMessage);
}
//按配置信息显示图形:
if (curFeature) {
curFeature.setStyle(
new Style({
fill: new Fill({
color: [0, 0, 255, 0.6],
}),
stroke: new Stroke({
color: "rgba(0, 0, 255, 1)",
width: 1,
}),
})
);
}
//更新图形的边框:
if (curFeature !== this.selFeature) {
let source = this.featureOverlay.getSource();
//移除之前的图形:
this.selFeature ? source.removeFeature(this.selFeature) : {};
//添加新图形:
curFeature ? source.addFeature(curFeature) : {};
//保存:
this.selFeature = curFeature;
}
},
},
};
</script>
<style scoped>
@import "ol/ol.css";
</style>
效果