mapView.vue 7.32 KB
<template>
  <div class="map-box" :style="{ height: `${mapHeight}px` }">
    <div :id="mapContainerId" style="width: 100%; height: 100%;z-index: 999999"></div>
    <!-- 使用原生 input 替代 el-input,避免触发 Element UI 的表单校验 -->
    <div class="map-address-input-wrapper">
      <input v-model="address"
             class="map-address-native-input"
             placeholder="请选择或输入地址"
             @blur.stop
             @click.stop
             @focus.stop />
    </div>
    <div id="myPageTop" style="position: absolute; top: 10px; width: 50%; left: 25%">
      <el-input id="input"
                v-model="input"
                class="input-with-select"
                placeholder="请输入关键字"
                @keyup.enter.native="searchAddress">
        <el-button slot="append"
                   icon="el-icon-search"
                   @click="searchAddress">
        </el-button>
      </el-input>
    </div>
  </div>
</template>

<script>
let map, marker, geocoder;
export default {
	name: "ProvinceCityMapView",
	props: {
		mapHeight: {
			type: Number,
			default: 300,
		},
	},

	data() {
		return {
			input: "",
			address: "",
			lnglat: [],
			geocoderAddress: {},
			mapapi: null,
			// 动态容器 ID(避免多个弹窗容器 ID 冲突)
			mapContainerId: `mapContainer_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
		};
	},

	created() {
		// this.mapInit()
	},

	methods: {
		async mapInit(lng, lat) {
			const mapapi = this.$mapapi;

			// 持续等待地图API加载(最多等待30秒,每100ms检查一次)
			if (!mapapi) {
				for (let i = 0; i < 300; i++) {
					await new Promise(resolve => setTimeout(resolve, 100));
					if (this.$mapapi) {
						mapapi = this.$mapapi;
						break;
					}
				}
				if (!mapapi) {
					console.error("地图API未加载,等待超时");
					return;
				}
			}

			// 等待地图API完全ready(最多等待30秒)
			try {
				await mapapi.ready(30000);
			} catch (err) {
				console.error("地图API加载超时:", err);
				return;
			}

			// 持续检查 GLMap.Map 构造函数是否可用(最多等待5秒)
			let retries = 50;
			while (retries > 0) {
				if (mapapi.GLMap && typeof mapapi.GLMap.Map === "function") {
					break;
				}
				await new Promise(resolve => setTimeout(resolve, 100));
				retries--;
			}

			if (!mapapi.GLMap || typeof mapapi.GLMap.Map !== "function") {
				console.error("地图构造函数未准备好");
				return;
			}

			// 确保地图容器已经渲染
			await this.$nextTick();

			// 多次尝试获取地图容器(最多等待2秒)
			let mapContainer = null;
			for (let i = 0; i < 20; i++) {
				mapContainer = document.getElementById(this.mapContainerId);
				if (mapContainer) {
					break;
				}
				await new Promise(resolve => setTimeout(resolve, 100));
			}

			if (!mapContainer) {
				console.error("地图容器未找到");
				return;
			}

			// 尝试创建地图实例(最多重试3次)
			let mapInstance = null;
			for (let i = 0; i < 3; i++) {
				try {
					mapInstance = await mapapi.invoke("Map", this.mapContainerId);
					if (mapInstance) {
						map = mapInstance;
						break;
					}
				} catch (err) {
					console.error(`地图实例创建失败(第${i + 1}次):`, err);
					await new Promise(resolve => setTimeout(resolve, 200));
				}
			}

			if (!map) {
				console.error("地图实例创建失败");
				return;
			}

			if (lng) {
				this.init(mapapi, map, lng, lat);
				return true;
			}
			mapapi.invoke("LocalCity", (res) => {
				console.log("IP", res);
				let { lng, lat } = res.center;
				this.init(mapapi, map, lng, lat, false);
			});
		},
		init(mapapi, map, lng, lat, isMark = true) {
			mapapi.invoke("centerAndZoom", mapapi.invoke("Point", lng, lat), 15);
			map.enableScrollWheelZoom(); // 启用滚轮放大缩小
			map.enableAutoResize(); // 启用自动适应容器尺寸变化
			geocoder = mapapi.invoke("Geocoder");
			if (isMark) {
				this.addMarker([lng, lat], true);
			}
			// 右键菜单
			mapapi.invoke("mapAddEventListener", "click", (e) => {
				console.log(e);
				this.getAddress(e.point);
			});
		},
		searchAddress() {
			const mapapi = this.$mapapi;
			console.log(mapapi, "mapapi");
			mapapi.invoke("getPoint", this.input, (res) => {
				console.log(this.input, res, "getPoint");
				// this.addMarker(res)
				this.getAddress(res);
			}, "全国");
			// let _this = this
			// placeSearch.search(this.input, function(status, result) {
			//   if (status === 'complete' && result.poiList.pois.length) {
			//     let lnglat = result.poiList.pois[0].location
			//     _this.getAddress(lnglat)
			//   }
			// })
		},
		addMarker(lnglat, isInit = false) {
			const mapapi = this.$mapapi;
			let lnglatXY;
			if (lnglat.lng) {
				const { lng, lat } = lnglat;
				lnglatXY = mapapi.invoke("Point", lng, lat);
			} else {
				lnglatXY = mapapi.invoke("Point", lnglat[0], lnglat[1]);
			}
			if (marker) {
				mapapi.invoke("removeOverlay", marker);
			}
			marker = mapapi.invoke("Marker", lnglatXY, {
				icon: mapapi.invoke("Icon", require("@/assets/address.png"), mapapi.invoke("Size", 26, 38)),
			});
			// if (!isInit) {
			//   mapapi.invoke('getLocation', lnglatXY, res => {
			//     console.log(res, 'getLocation')
			//     if (res) this.address = res.surroundingPois.length ? res.surroundingPois[0].address : res.address
			//   })
			// }
			mapapi.invoke("panTo", lnglatXY);
			mapapi.invoke("addOverlay", marker);
		},
		getAddress(e) {
			console.log(e);
			let self = this;
			const mapapi = this.$mapapi;
			let lnglat;
			let lng, lat;
			if (e.lng) {
				lng = e.lng;
				lat = e.lat;
				lnglat = mapapi.invoke("Point", lng, lat);
			} else {
				lng = e[0];
				lat = e[1];
				lnglat = mapapi.invoke("Point", lng, lat);
			}
			self.addMarker(lnglat);
			// 统一赋值为对象格式 {lng, lat},与父组件使用保持一致
			self.lnglat = { lng, lat };
			geocoder.getLocation(lnglat, (res) => {
				console.log(res);
				this.address = res.surroundingPois.length ? res.surroundingPois[0].address : res.address;
				this.geocoderAddress = res.content.address_detail;
			});
			// AMap.plugin('AMap.Geocoder', () => {
			//   const geocoder = new AMap.Geocoder()
			//   geocoder.getAddress(lnglat, (status, result) => {
			//     self.lnglat = lnglat
			//     self.address = result.regeocode.formattedAddress
			//     geocoder.getLocation(self.address, (status, result) => {
			//       if (status === 'complete' && result.info === 'OK') {
			//         this.geocoderAddress = result.geocodes[0]
			//       }
			//     })
			//   })
			// })
		},
		selectAddress(e) {
			// 这里获得点选地点的经纬度
			this.getAddress();
		},
	},
};
</script>

<style scoped lang="scss">
.map-box {
	position: relative;
	width: 100%;
}
#container {
	position: absolute;
	height: 100%;
}
#panel {
	position: absolute;
	max-height: 90%;
	overflow-y: auto;
	top: 80px;
	right: 10px;
	width: 280px;
}
.map-address-native-input {
	width: 100%;
	height: 32px;
	padding: 0 15px;
	font-size: 14px;
	line-height: 32px;
	color: #606266;
	background-color: #fff;
	background-image: none;
	border: 1px solid #dcdfe6;
	border-radius: 4px;
	box-sizing: border-box;
	outline: none;
	transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
	margin-top: 10px;
	&::placeholder {
		color: #c0c4cc;
	}

	&:hover {
		border-color: #c0c4cc;
	}

	&:focus {
		border-color: #409eff;
	}
}
</style>