Files
tms-erp-web/src/components/address-map-picker/main.vue
T

424 lines
13 KiB
Vue

<template>
<el-dialog v-model="visible" title="地图选择地址" width="920px" append-to-body @opened="initMap">
<div class="address-map-picker__toolbar">
<el-input
v-model="keyword"
clearable
placeholder="输入地址关键词"
@keyup.enter="searchKeyword"
/>
<el-button type="primary" :loading="searching" @click="searchKeyword">搜索</el-button>
</div>
<div class="address-map-picker__content">
<div ref="map" class="address-map-picker__map"></div>
<map-search-results :results="searchResults" @select="selectSearchResult" />
</div>
<div class="address-map-picker__info">{{ status }}</div>
<template #footer>
<el-button @click="visible = false">取消</el-button>
<el-button
type="primary"
:disabled="!hasCoordinateValue(selected.longitude) || !hasCoordinateValue(selected.latitude) || resolving"
@click="confirm"
>
确定
</el-button>
</template>
</el-dialog>
</template>
<script>
import { normalizeMapSearchResults, searchAmapPlaceText } from '@/utils/map-search';
const AMAP_KEY = '13dcb15bc29bfe9c432d17ecd808b812';
const AMAP_SECURITY_CODE = 'f9d036ef29e376e15d309e0de5c0f7ab';
let amapLoader;
export default {
props: {
modelValue: {
type: Boolean,
default: false,
},
address: {
type: String,
default: '',
},
longitude: {
type: [String, Number],
default: '',
},
latitude: {
type: [String, Number],
default: '',
},
},
emits: ['update:modelValue', 'confirm'],
data() {
return {
visible: false,
keyword: '',
status: '可搜索地址或点击地图选点',
searching: false,
resolving: false,
selected: {},
amap: null,
marker: null,
geocoder: null,
searchResults: [],
mapInitializing: null,
};
},
watch: {
modelValue: {
immediate: true,
handler(value) {
this.visible = value;
if (value) {
this.keyword = this.address || '';
this.searchResults = [];
this.selected = this.buildInitialSelection();
this.status = this.selected.longitude
? this.selected.address || '已选点,可确认回填'
: '可搜索地址或点击地图选点';
}
},
},
visible(value) {
this.$emit('update:modelValue', value);
},
},
beforeUnmount() {
if (this.amap) {
this.amap.destroy();
}
},
methods: {
hasCoordinateValue(value) {
return value !== '' && value !== null && value !== undefined;
},
buildInitialSelection() {
// Number('') === 0,空字符串不能当有效坐标,否则会落到 [0,0](非洲附近)
if (!this.hasCoordinateValue(this.longitude) || !this.hasCoordinateValue(this.latitude)) {
return {};
}
const longitude = Number(this.longitude);
const latitude = Number(this.latitude);
if (
!Number.isFinite(longitude) ||
!Number.isFinite(latitude) ||
longitude < -180 ||
longitude > 180 ||
latitude < -90 ||
latitude > 90
) {
return {};
}
return {
longitude,
latitude,
address: this.address || '',
};
},
loadAmap() {
if (window.AMap && window.AMap.Map) {
return Promise.resolve();
}
if (!amapLoader) {
amapLoader = new Promise((resolve, reject) => {
window._AMapSecurityConfig = { securityJsCode: AMAP_SECURITY_CODE };
const script = document.createElement('script');
script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_KEY}`;
script.async = true;
script.onload = resolve;
script.onerror = () => reject(new Error('高德地图组件加载失败'));
document.body.appendChild(script);
});
}
return amapLoader;
},
initMap() {
if (this.mapInitializing) return this.mapInitializing;
this.mapInitializing = this.loadAmap()
.then(() => {
if (!window.AMap?.Map) {
throw new Error('高德地图组件未就绪');
}
return new Promise(resolve => {
this.$nextTick(() => {
if (!this.$refs.map) return resolve(null);
const initial = this.buildInitialSelection();
const hasPoint =
Number.isFinite(initial.longitude) && Number.isFinite(initial.latitude);
const center = hasPoint
? [initial.longitude, initial.latitude]
: [116.40769, 39.89945];
const zoom = hasPoint ? 14 : 11;
if (!this.amap) {
this.amap = new window.AMap.Map(this.$refs.map, {
center,
zoom,
});
this.amap.on('click', event => this.pickPoint(event.lnglat));
} else {
this.amap.resize();
this.clearMarker();
this.amap.setZoomAndCenter(zoom, center);
}
if (hasPoint) {
const point = new window.AMap.LngLat(initial.longitude, initial.latitude);
this.renderMarker(point);
this.selected = { ...initial };
this.status = initial.address || '已选点,可确认回填';
}
resolve(this.amap);
});
});
})
.catch(() => {
this.$message.error('高德地图组件加载失败,请稍后重试');
this.visible = false;
return null;
})
.finally(() => {
this.mapInitializing = null;
});
return this.mapInitializing;
},
ensureGeocoder() {
if (this.geocoder) return Promise.resolve(this.geocoder);
return new Promise((resolve, reject) => {
window.AMap.plugin(['AMap.Geocoder'], () => {
try {
this.geocoder = new window.AMap.Geocoder();
resolve(this.geocoder);
} catch (error) {
reject(error);
}
});
});
},
runGeocode(action, input) {
return this.ensureGeocoder().then(
geocoder =>
new Promise((resolve, reject) => {
const done = (status, result) => {
if (status === 'complete' && result) {
resolve(result);
} else {
reject(new Error('高德地图请求失败'));
}
};
if (action === 'location') {
geocoder.getLocation(input, done);
} else {
geocoder.getAddress(input, done);
}
})
);
},
searchKeyword() {
const keyword = String(this.keyword || '').trim();
if (!keyword) {
this.$message.warning('请输入地址关键词');
return;
}
if (this.searching) return;
this.searchResults = [];
this.searching = true;
this.initMap()
.then(map => (map ? searchAmapPlaceText(keyword) : null))
.then(pois => {
if (!pois) return;
this.searchResults = normalizeMapSearchResults(pois, keyword);
const first = this.searchResults[0];
if (!first?.location) {
throw new Error('未找到匹配地址');
}
return this.$nextTick().then(() => {
this.amap?.resize();
this.pickPoint(first.location, first.address || first.name || keyword);
});
})
.catch(() => {
this.status = '未找到匹配地址';
this.$message.warning('地图搜索无匹配地址');
})
.finally(() => {
this.searching = false;
});
},
selectSearchResult(item) {
if (item && item.location) {
this.pickPoint(item.location, item.address || item.name || '');
}
},
pickPoint(point, fallbackAddress = '') {
const longitude =
typeof point.getLng === 'function' ? point.getLng() : point.lng ?? point.longitude;
const latitude =
typeof point.getLat === 'function' ? point.getLat() : point.lat ?? point.latitude;
if (!Number.isFinite(Number(longitude)) || !Number.isFinite(Number(latitude))) {
this.$message.warning('选点坐标无效');
return;
}
const lnglat = new window.AMap.LngLat(Number(longitude), Number(latitude));
this.renderMarker(lnglat);
this.selected = {
longitude: Number(longitude),
latitude: Number(latitude),
address: fallbackAddress,
};
this.status = '正在解析地址...';
this.resolving = true;
this.runGeocode('address', lnglat)
.then(result => {
const detailAddress = result.regeocode?.formattedAddress || fallbackAddress;
const region = this.resolveRegionFromGeocode(result);
this.selected = {
...this.selected,
address: detailAddress,
...region,
};
this.keyword = detailAddress || this.keyword;
this.status = detailAddress || '已选点,可确认回填';
})
.catch(() => {
this.status = '地址解析失败,请重新选点';
this.$message.error('地址解析失败,请重新选点');
this.selected = {};
this.clearMarker();
})
.finally(() => {
this.resolving = false;
});
},
resolveRegionFromGeocode(result = {}) {
const component = result.regeocode?.addressComponent || {};
const city = Array.isArray(component.city) ? '' : String(component.city || '').trim();
const province = String(component.province || '').trim();
const district = String(component.district || '').trim();
const country = String(component.country || '').trim();
const adcode = String(component.adcode || '').trim();
return {
country,
province,
city: city || province,
district,
adcode,
regionCode: adcode,
provinceName: province,
cityName: city || province,
districtName: district,
countryName: country,
};
},
renderMarker(point) {
this.clearMarker();
this.marker = new window.AMap.Marker({ position: point });
this.marker.setMap(this.amap);
this.amap.setCenter(point);
},
clearMarker() {
if (this.marker) {
this.marker.setMap(null);
this.marker = null;
}
},
syncSelectedFromMarker() {
// 确认时以当前标记点坐标为准,避免换地址后仍回填上一次经纬度
if (!this.marker || typeof this.marker.getPosition !== 'function') {
return;
}
const point = this.marker.getPosition();
if (!point) {
return;
}
const longitude =
typeof point.getLng === 'function' ? point.getLng() : point.lng ?? point.longitude;
const latitude =
typeof point.getLat === 'function' ? point.getLat() : point.lat ?? point.latitude;
if (!Number.isFinite(Number(longitude)) || !Number.isFinite(Number(latitude))) {
return;
}
this.selected = {
...this.selected,
longitude: Number(longitude),
latitude: Number(latitude),
};
},
confirm() {
this.syncSelectedFromMarker();
if (!this.hasCoordinateValue(this.selected.longitude) || !this.hasCoordinateValue(this.selected.latitude)) {
this.$message.warning('请先搜索或点击地图完成选点');
return;
}
if (!this.selected.address) {
this.$message.warning('请等待地址解析完成后再确认');
return;
}
this.$emit('confirm', {
address: this.selected.address,
longitude: Number(this.selected.longitude),
latitude: Number(this.selected.latitude),
country: this.selected.country || this.selected.countryName || '',
province: this.selected.province || this.selected.provinceName || '',
city: this.selected.city || this.selected.cityName || '',
district: this.selected.district || this.selected.districtName || '',
adcode: this.selected.adcode || this.selected.regionCode || '',
regionCode: this.selected.regionCode || this.selected.adcode || '',
countryName: this.selected.countryName || this.selected.country || '',
provinceName: this.selected.provinceName || this.selected.province || '',
cityName: this.selected.cityName || this.selected.city || '',
districtName: this.selected.districtName || this.selected.district || '',
});
this.visible = false;
},
},
};
</script>
<style lang="scss" scoped>
.address-map-picker {
&__toolbar {
display: flex;
gap: 8px;
margin-bottom: 12px;
.el-input {
flex: 1;
}
}
&__map {
width: 100%;
min-width: 0;
height: 420px;
border: 1px solid #eff1f7;
}
&__content {
position: relative;
display: block;
min-width: 0;
overflow: visible;
.address-map-picker__map {
position: relative;
z-index: 1;
}
:deep(.map-search-results) {
z-index: 2000;
}
}
&__info {
margin-top: 10px;
color: #606266;
line-height: 1.6;
}
}
</style>