爱山东pc端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

147 lines
3.2 KiB

<template>
<div class="map-container" ref="mapContainer"></div>
</template>
<script setup>
import { ref, onMounted, watch } from "vue"; // 添加watch
import AMapLoader from "@amap/amap-jsapi-loader";
const props = defineProps({
center: {
type: Array,
default: () => [120.287882, 36.178786],
},
zoom: {
type: Number,
default: 10.5,
},
//地图点位
markers: {
type: Array,
default: () => [],
},
// 地图中心点
mapCenter: {
type: Array,
default: () => [],
},
});
const mapContainer = ref(null);
let map = null;
let markers = []; // 存储当前地图上的marker实例
// 清除所有点位
const clearMarkers = () => {
if (map) {
map.remove(markers);
markers = [];
}
};
// 添加点位
const emit = defineEmits(["marker-click"]); // 添加事件发射器
const addMarkers = () => {
clearMarkers();
props.markers.forEach((marker, index) => {
const content = `
<div style="
background: ${marker.color || "#3388FF"};
color: white;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 12px;
box-shadow: 0 2px 4px rgba(0,0,0,0.3);
padding: 8px;
border-radius: 15px;
white-space: nowrap;
">
${marker.name || ""}
<span style="
background: #ffffff;
color: ${marker.color || "#3388FF"};
border-radius: 10px;
min-width: 20px;
height: 20px;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 10px;
padding: 0 4px;
margin-left: 4px;
box-sizing: border-box;
font-weight: bold;
">${marker.total || ""}间</span>
</div>
`;
const amarker = new AMap.Marker({
position: [marker.longitude, marker.latitude],
content: content,
offset: new AMap.Pixel(-15, -15),
});
// 添加点击事件
amarker.on("click", () => {
emit("marker-click", {
marker,
index,
position: [marker.longitude, marker.latitude],
});
map.setCenter([marker.longitude, marker.latitude]);
map.setZoom(15);
});
markers.push(amarker);
map.add(amarker);
});
};
onMounted(async () => {
try {
const AMap = await AMapLoader.load({
key: import.meta.env.VITE_AMAP_KEY,
version: "2.0",
plugins: ["AMap.ToolBar", "AMap.Scale", "AMap.Marker"], // 添加Marker插件
});
map = new AMap.Map(mapContainer.value, {
viewMode: "2D",
zoom: props.zoom,
center: props.center,
});
// 添加控件
map.addControl(new AMap.ToolBar());
map.addControl(new AMap.Scale());
// 初始添加点位
addMarkers();
// 监听markers变化
watch(
() => props.markers,
() => {
addMarkers();
},
{ deep: true }
);
watch(()=>props.mapCenter,(newVal,oldVal)=>{
map.setCenter(newVal)
},
{deep:true})
} catch (error) {
console.error("地图加载失败:", error);
}
});
</script>
<style scoped>
.map-container {
width: 100%;
height: 100vh;
min-height: 400px;
}
</style>