<template>
<!--地图-->
<div class="distributeMap" id="distributeMap"></div>
<!--弹窗-->
<section ref="popup" id="popupDiv" class="popup">
{{ state.popupParams.name }}
</section>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { Feature, Map, Overlay, View } from "ol";
import OSM from "ol/source/OSM";
import "ol/ol.css";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { fromLonLat } from "ol/proj";
import { Point } from "ol/geom";
import CircleStyle from "ol/style/Circle";
import { Fill, Icon, Style } from "ol/style";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import { useRouter } from "vue-router";
const $router = useRouter();
let popup = ref(null) as any;
const state = reactive({
map: null as any,
popupParams: {} as any,
overlay: null as any,
});
const getOpenLayersMap = () => {
let layer = new TileLayer({
source: new XYZ({
url: "http://t4.tianditu.com/DataServer?T=vec_w&tk=4a76fd399e76e3e984e82953755c3410&x={x}&y={y}&l={z}",
crossOrigin: "anoymous",
}),
});
state.map = new Map({
target: "distributeMap",
layers: [layer],
view: new View({
projection: "EPSG:4326",
center: [114.31, 30.62048],
zoom: 1,
}),
});
};
const mapPoint = (data: any) => {
const pointFeature = new Feature({
name: "点位",
id: 1,
geometry: new Point([114.31, 30.62048]),
});
pointFeature.setStyle(
new Style({
image: new Icon({
src: "https://smart-garden-manage.oss-cn-chengdu.aliyuncs.com/shexiangtou.png",
scale: 0.3,
}),
})
);
const vectorSource = new VectorSource({
features: [pointFeature],
});
const vectorLayer = new VectorLayer({
source: vectorSource,
});
state.map.addLayer(vectorLayer);
};
const addOverPlay = () => {
state.overlay = new Overlay({
element: document.getElementById("popupDiv") as any,
positioning: "bottom-center",
stopEvent: false,
autoPan: true,
offset: [0, -20],
});
state.map.addOverlay(state.overlay);
};
const iconTouchstart = () => {
state.map.on("pointermove", (e: any) => {
let point = state.map.forEachFeatureAtPixel(
e.pixel,
(feature: any) => feature
) as any;
console.log(point);
if (point) {
state.map.getTargetElement().style.cursor = "pointer";
state.overlay.getElement().style.display = "block";
let params = point.getProperties();
console.log("鼠标移入当前标点参数", params);
state.popupParams = params;
let coordinates = point.getGeometry().getCoordinates();
state.overlay.setPosition(coordinates);
} else {
state.overlay.getElement().style.display = "none";
state.popupParams = {};
}
});
};
onMounted(() => {
getOpenLayersMap();
mapPoint();
iconTouchstart();
addOverPlay();
});
</script>
<style lang="scss" scoped>
.popup {
display: flex;
align-items: center;
justify-content: center;
background-color: #fff;
color: #8d919a;
padding: 6px;
border-radius: 5px;
}
</style>