TaskSystem-admin/src/components/map/MapContainer.vue
2023-08-17 18:26:00 +08:00

123 lines
3.3 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<div id="container" ref="map"></div>
</template>
<script lang="ts" setup name="mapContainer">
import AMapLoader from "@amap/amap-jsapi-loader";
import { shallowRef } from "@vue/reactivity";
const map = shallowRef(null);
let AMap: any = null;
let markerList: Array<any> = [];
let m_index: Number = 0;
const emits = defineEmits("changeMaps");
const resetMap = () => {
markerList = [];
map.value.clearMap();
m_index = 0;
emits("changeMaps", markerList);
};
defineExpose({
resetMap,
});
const initMap = async () => {
const loader = AMapLoader.load({
key: "4f8f55618010007147aab96fc72bb408",
version: "2.0",
});
AMap = await loader;
map.value = new AMap.Map("container", {
zoom: 13,
});
map.value.on("click", (e: any) => {
// console.log("点击", e.lnglat);
if (m_index >= 3) return;
// 调用函数并传入经纬度
getDistrictName(e.lnglat.lng, e.lnglat.lat);
// 获取地区名称
function getDistrictName(lng, lat) {
AMap.plugin("AMap.Geocoder", function () {
var geocoder = new AMap.Geocoder({
radius: 10, // 逆地理编码范围默认值1000单位
extensions: "all", // 返回地址描述结果时是否包含引擎内置的POI默认值base可选值base、all
}); // 经纬度数组
geocoder.getAddress([lng, lat], function (status, result) {
if (status === "complete" && result.info === "OK") {
// 解析成功,提取地区名称
var district = result.regeocode.addressComponent.district;
// console.log(district, result.regeocode); // 输出地区名字
markerList.push({
lnglat: e.lnglat,
address: result.regeocode.formattedAddress,
});
emits("changeMaps", markerList);
} else {
// 解析失败
console.log("逆地理编码失败");
}
});
});
}
// 自定义 Marker 的图标
var customIcon = new AMap.Icon({
size: new AMap.Size(36, 36), // 图标尺寸
image: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png", // 图标图片
imageSize: new AMap.Size(26, 26), // 图标图片尺寸
imageOffset: new AMap.Pixel(0, 0), // 图标图片偏移量
label: {
content: "起", // 文字内容
offset: new AMap.Pixel(-100, -100), // 文字相对于图标的偏移量
},
});
// 创建标记并添加到地图
let marker = new AMap.Marker({
position: e.lnglat,
offset: new AMap.Pixel(-10, -10),
title: "位置",
icon: customIcon,
// content: "起",
});
map.value.add(marker);
m_index++;
// 添加标记点击事件监听器
// marker.on("click", (event: any) => {
// console.log("删除", event);
// markerList = markerList.filter((item: any) => {
// item[0] == marker._position.pos[0] &&
// item[0] == marker._position.pos[0];
// });
// emits("changeMaps", markerList);
// // 在这里可以进行其他自定义逻辑操作
// map.value.remove(marker);
// m_index--;
// marker = null;
// });
});
};
onMounted(() => {
initMap();
});
</script>
<style lang="scss" scoped>
#container {
padding: 0px;
margin: 0px;
width: 400px;
height: 400px;
}
</style>