showModal = (props, event) => {
if (props === 1) {// 复制通告
this.getData();
} else if (props === 2) {
this.setState({data: {}});
}
this.setState({visible: true}, () => {
setTimeout(() => {
this.setState({
mapObj: new window.AMap.Map('add-notice-container', {
resizeEnable: true,
zoom: 16,
center: [120.00485, 30.292234]
})
}, () => {
window.AMap.service('AMap.Geocoder', () => {
const geocoder = new window.AMap.Geocoder({});
this.state.mapObj.on('click', (e) => {
this.setXY({x: e.lnglat.lng, y: e.lnglat.lat});
geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], (status, result) => {
if (status === 'complete' && result.info === 'OK') {
this.setFormattedAddress(result.regeocode.formattedAddress);
this.setAddressComponent(result.regeocode.addressComponent);
}
});
});
})
})
}, 500)
});
};
const toXY = (para) => {
console.log(para);
mapObj.plugin('AMap.Geocoder', function () {
const geocoder = new window.AMap.Geocoder({});
const marker = new window.AMap.Marker({
map: mapObj,
bubble: true
});
geocoder.getLocation(para, (status, result) => {
if (status === 'complete' && result.info === 'OK') {
result.geocodes[0].addressComponent.adcode = result.geocodes[0].adcode;
setXY({x: result.geocodes[0].location.lng, y: result.geocodes[0].location.lat});
// setFieldsValue({"location": result.geocodes[0].formattedAddress});
setAddressComponent(result.geocodes[0].addressComponent);
marker.setPosition(result.geocodes[0].location);
mapObj.setCenter(marker.getPosition())
}
});
});
};
代码中用到的其它方法,比如 setXY(),setFormattedAddress(),setAddressComponent(), 如下
setXY = (para) => {
this.setState({
xy: para
})
};
setFormattedAddress = (para) => {
this.setState({
formattedAddress: para
})
};
setAddressComponent = (para) => {
this.setState({
addressComponent: {
provinceName: para.province,
cityName: para.city,
areaName: para.district,
areaId: para.adcode
}
})
};
//定位
const location = () => {
mapObj.plugin('AMap.Geolocation', function () {
const geolocation = new window.AMap.Geolocation({});
mapObj.addControl(geolocation);
geolocation.getCurrentPosition();
//获取成功
window.AMap.event.addListener(geolocation, 'complete', function (data) {
const x = data.position.getLng(), //定位成功返回的经度
y = data.position.getLat(); //定位成功返回的纬度
setXY({x: x, y: y});
setFieldsValue({"location": data.formattedAddress});
setAddressComponent(data.addressComponent);
});
//获取失败
window.AMap.event.addListener(geolocation, 'error', function (data) {
if (data.info === 'FAILED') {
console.log('获取当前位置失败!')
}
});
});
};