map/src/pages/BaseMap/index.js
2025-03-01 17:08:27 +08:00

1368 lines
56 KiB
JavaScript
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.

import React, { useState } from 'react';
import { Select, Input, Card, Col, Row, Button, message, Modal, Spin, Form, Alert, Space } from 'antd';
import { DoubleLeftOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import LayerData from './LayerData';
// import LayerList from './LayerList';
import { AimOutlined, DoubleRightOutlined } from '@ant-design/icons';
import Header from '../../components/Header/index.js';
import { createPoint, updatePoint, getDetailByIdApi, queryUserLayers, getLayerPointsApi, getAllProvinceApi, getCityByProvinceApi, getDistrictByCityApi, getLayerShapesApi, getPointByAddressApi, deletePoint } from '../../api';
import Pop from './pop'
import { GaodeMap, Scene, Heatmap, PolygonLayer, Marker, MarkerLayer, Popup, MouseLocation, CanvasLayer, Scale, MapTheme, Zoom } from '@antv/l7';
const { confirm } = Modal;
// import { DrawPoint, DrawEvent } from '@antv/l7-draw';
import icon04 from '../../assets/icon/icon04.svg'
import styles from './index.less';
import './index.less';
import pop from './pop';
import { remove } from 'react-cookies';
const { Option } = Select;
const nullSearchLocation = () => {
message.error('坐标信息为空');
};
const nullSearchAddress = () => {
message.error('地址信息为空');
};
const errorSearchAddress = () => {
message.error('地址搜索信息异常,请联系开发人员');
};
const successSearchAddress = () => {
message.success('已成功进行地图定位');
};
// 省编码(全局)
let ProvinceAdcode = null;
let ProvinceData = null;
// 市编码(全局)
let CityAdcode = null;
let CityData = null;
// 区编码(全局)
let DistrictAdcode = null;
let DistrictData = null;
class BaseMap extends React.Component {
constructor() {
super();
this.state = {
map: null,
// 地图中心
center: {
// title: '石家庄',longitude: 114.502461,latitude: 38.045474
},
provinceList: [],// 省
provinceAdcode: '',//选中的省
provinceLabel: '',//选中的省
cityList: [],//市
cityAdcode: '',//选中的市
cityLabel: '',
districtList: [],//区
districtAdcode: '',//选中的区
zoom: 4,
inputExplainKey: 0,
inputExplainValue: "请输入地址详情信息",
inputContent: '',
heatMapList: [],
loading: false,
markerLayerList: [], // 点位图层
isModalOpen: false,
isEditModalOpen: false,
editPointId: '',
selectLayerList: [],
pointAdd: {},
pointEdit: {},
pointDrawer: null,
newPointLocation: '',
mouseLocation: {},
disabled: false,
popParameter: {},
isAlertOpen: false,
deletePointId: '',
pop: null,
removeMarker: null,
autoComplete: null, // 地图搜索提示
}
}
startLoading = () => {
this.setState({
loading: true,
});
}
stopLoading = () => {
this.setState({
loading: false,
});
}
// 钩子,打开执行
componentDidMount = () => {
this.getAllProvince();
this.createMap();
}
componentWillUnmount = () => {
// 组件卸载时,清除地图
this.state.map.map.destroy();
this.state.map.destroy();
this.setState = null;
console.log('组件卸载时,清除地图');
}
// 创建地图
createMap = () => {
const scene = new Scene({
id: 'container',
map: new GaodeMap({
pitch: 20,
style: 'light',
center: [118.405285, 39.904989],
zoom: 3,
plugin: ['AMap.AutoComplete', 'AMap.PlaceSearch'],
})
});
this.setState({
map: scene,
}, () => {
// 地图拖拽鼠标图标更改
let can = document.getElementsByClassName('amap-layer')[0];
can.addEventListener('mousedown', (e) => {
console.log('mousedown', can);
// can.className = 'amap-layer cursor-grab';
can.className = can.className.replace("amap-layer", "amap-layer cursor-grab");
can.addEventListener('mouseup', (e) => {
can.className = can.className.replace("cursor-grab", " ");
// console.log('mouseup',can.className.replace("cursor-grab"," "));
});
})
});
// 地图搜索提示功能
scene.on('loaded', () => {
// 比例尺插件
const scale = new Scale();
scene.addControl(scale);
// 地图主题插件
const mapTheme = new MapTheme({
position: 'bottomright', // 控件的位置
options: [
{
"text": "",
"value": "amap://styles/normal",
"img": "https://gw.alipayobjects.com/mdn/rms_816329/afts/img/A*-nqiT6Vu948AAAAAAAAAAAAAARQnAQ",
"key": "normal"
},
{
"text": "",
"value": "amap://styles/c422f5c0cfced5be9fe3a83f05f28a68?isPublic=true",
"img": "https://gw.alipayobjects.com/mdn/rms_816329/afts/img/A*J_wYQL_PaUEAAAAAAAAAAAAAARQnAQ",
"key": "light"
},
{
"text": "",
"value": "amap://styles/c9f1d10cae34f8ab05e425462c5a58d7?isPublic=true",
"img": "https://gw.alipayobjects.com/mdn/rms_816329/afts/img/A*U7M9QI1yat4AAAAAAAAAAAAAARQnAQ",
"key": "dark"
},
{
"text": "",
"value": "amap://styles/fresh",
"img": "https://gw.alipayobjects.com/mdn/rms_816329/afts/img/A*T-oBT4hB5ucAAAAAAAAAAAAAARQnAQ",
"key": "fresh"
},
{
"text": "",
"value": "amap://styles/grey",
"img": "https://gw.alipayobjects.com/mdn/rms_816329/afts/img/A*OREXQ4vgQRIAAAAAAAAAAAAAARQnAQ",
"key": "grey"
},
{
"text": "",
"value": "amap://styles/graffiti",
"img": "https://gw.alipayobjects.com/mdn/rms_816329/afts/img/A*4UApTKmeiy4AAAAAAAAAAAAAARQnAQ",
"key": "graffiti"
},
{
"text": "",
"value": "amap://styles/macaron",
"img": "https://gw.alipayobjects.com/mdn/rms_816329/afts/img/A*0GrCQLtDjNcAAAAAAAAAAAAAARQnAQ",
"key": "macaron"
},
{
"text": "",
"value": "amap://styles/darkblue",
"img": "https://gw.alipayobjects.com/mdn/rms_816329/afts/img/A*uWxqSZQlPkkAAAAAAAAAAAAAARQnAQ",
"key": "darkblue"
},
{
"text": "",
"value": "amap://styles/wine",
"img": "https://gw.alipayobjects.com/mdn/rms_816329/afts/img/A*OFPrTbg3an0AAAAAAAAAAAAAARQnAQ",
"key": "wine"
}
]
});
scene.addControl(mapTheme);
let op = mapTheme.getOptions();
console.log('op', op);
// AutoComplete(输入框提示) 插件
window.AMap.plugin(['AMap.AutoComplete', 'AMap.PlaceSearch'], () => {
// Autocomplete 实例配置
const autoOptions = {
city: '全国', //城市,默认全国
input: "tipinput", //使用联想输入的input的id
citylimit: true,
// closeResultOnScroll: false
};
// 创建Autocomplete对象
const autoComplete = new AMap.AutoComplete(autoOptions);
// 监听输入框的focus事件否则总是不触发提示
document.getElementById('tipinput').addEventListener('focus', (e) => {
autoComplete.search(e.target.value, (status, result) => {
// 搜索成功时result即是对应的匹配数据
// console.log('result', result);
});
});
this.state.autoComplete = autoComplete;
// 监听选中事件,将选中的地址信息显示在输入框中,暂时不需要,注解掉了
autoComplete.on('select', (e) => {
let adcode = e.poi.adcode;
console.log('select', e);
this.setState({
inputContent: e.poi.name, // 将选中的地址信息显示在输入框中
// provinceAdcode: adcode.substr(0, 2) + '0000',
}, () => {
// 改变adcode后不自动触发onProvinceChange函数手动触发
// let data = this.state.provinceList.find(o => o.value === this.state.provinceAdcode);
// this.onProvinceChange(this.state.provinceAdcode, data);
})
})
// 根据省市区码加载地图
if (ProvinceAdcode) {
this.onProvinceChange(ProvinceAdcode, ProvinceData);
}
if (CityAdcode) {
this.onCityChange(CityAdcode, CityData);
}
if (DistrictAdcode) {
this.onDistrictChange(DistrictAdcode, DistrictData);
}
});
// scene.map.plugin(['AMap.Autocomplete'], () => {
// // Autocomplete 实例配置
// const autoOptions = {
// city: '全国', //城市,默认全国
// input: 'tipinput' //使用联想输入的input的id
// };
// // 创建Autocomplete对象
// const autoComplete = new AMap.autoComplete(autoOptions);
// });
})
}
// 关闭点位窗口的提示界面
// Elmessage
//设置地图省份级别位置
gotoProvince = (data) => {
let zoom = data.zoom || 6;
let lng = data.len || 116.405285;
let lat = data.lat || 39.904989;
this.state.map.setZoomAndCenter(zoom, [lng, lat]);
}
//根据cityname、adcode、citycode设置地图位置
gotoCity = (data) => {
this.state.map.removeAllMarkers && this.state.map.removeAllMarkers();
let zoom = data.zoom || 10;
let lng = data.len || 116.405285;
let lat = data.lat || 39.904989;
this.state.map.setZoomAndCenter(zoom, [lng, lat]);
}
// 获取图层明细点位数据/热力图数据
getLayerPoints = (layerId, selected, nodeType) => {
if (selected) {
this.startLoading(); // 开启加载动画
getLayerPointsApi({
adcode: this.state.districtAdcode || this.state.cityAdcode || this.state.provinceAdcode,
layerId: layerId
}).then((e) => {
console.log("网络请求完成")
// 获取点位数据
let layerPointsData = e.data || [];
layerPointsData = layerPointsData.map((item) => {
item.lng = item.location.split(',')[0];
item.lat = item.location.split(',')[1];
item.value = 15;
return item;
});
if (nodeType === 1) {
// 在地图上添加点位
this.setMarkers(layerPointsData, layerId);
} else if (nodeType === 4) {
// this.setHeatMap(layerPointsData, layerId);
}
}).then(() => {
this.stopLoading();
});
} else {
let self = this;
let getLayers = self.state.markerLayerList;
for (let i = 0; i < getLayers.length; i++) {
if (getLayers[i].markerLayerOption.name == layerId) {
self.state.map.removeMarkerLayer(getLayers[i]);
}
}
self.hideHeatMap(layerId);
}
}
// 隐藏热力图
hideHeatMap = (layerId) => {
let heatMapList = this.state.heatMapList
for (let i = 0; i < heatMapList.length; i++) {
if (heatMapList[i].og.data[0].id === layerId || layerId === undefined || layerId === null || layerId === '') {
heatMapList[i].hide();
}
}
}
// 在地图上设置点位 【经度,纬度】
setMarkers = (data, layerId) => {
let self = this;
let map = this.state.map;
let LabelsData = data || [];
let markerLayer = new MarkerLayer({ name: layerId });
let el, popup, marker, icon, popHtml;
// 设置地图上的点位(图标)
for (let i = 0; i < LabelsData.length; i++) {
el = document.createElement('label');
el.style.width = '26px';
el.style.height = '26px';
el.id = 'marker' + i;
icon = LabelsData[0].logoImage;
if (icon && (icon.substr(0, 7) == "http://" || icon.substr(0, 6) == "https:" || icon.substr(0, 7) == "http:\\\\")) {
el.style.background = 'url("' + icon + '") no-repeat';
el.style.backgroundSize = 'cover';
} else {
el.className = icon;
}
marker = new Marker({
element: el,
}).setLnglat({ lng: LabelsData[i].lng, lat: LabelsData[i].lat })
// 设置弹框(点击事件)
marker.on('click', (e) => {
// 获取弹框内的html
this.setState({ popParameter: LabelsData[i] }, () => {
popHtml = document.getElementById('custom-pop');
popup = new Popup({
offsets: [0, 30],
closeOnClick: true,
autoClose: true,
})
.setLnglat(e.lngLat)
.setHTML(popHtml.innerHTML)
document.getElementById('marker' + i).style.width = '32px';
document.getElementById('marker' + i).style.height = '32px';
// 给弹框添加事件
popup.on('hide', () => {
document.getElementById('marker' + i).style.width = '26px';
document.getElementById('marker' + i).style.height = '26px';
});
this.setState({ pop: popup })
popup.on('open', () => {
// 编辑按钮
document.getElementsByClassName('edit-button')[0].onclick = () => {
// getDetailByIdApi({id:LabelsData[i].pointId,layerId:LabelsData[i].belongLayerId}).then((e) => {
// if (e.success) {
// console.log('获取点位详情成功',e);
// }else{
// alert('获取点位详情失败');
// console.log('获取点位详情失败',e);
// }
// })
if (this.state.cityAdcode == '' && this.state.districtAdcode == '') {
message.error('请至少选择行政区域至城市再进行点位创建');
return false;
}
let selectLayerList = this.refs.getLayerDataFun.state.selectLayerList;
selectLayerList = selectLayerList.filter((item) => {
if (item.isCustomize == 1) {
return item;
}
})
if (selectLayerList.length == 0) {
message.error('请至少选中一个个人图层');
return false;
};
this.setState({
selectLayerList: selectLayerList,
pointEdit:
{
pointId: LabelsData[i].pointId,
layerId: LabelsData[i].belongLayerId,
name: LabelsData[i].pointName,
// note: LabelsData[i].note,
address: LabelsData[i].address,
},
isEditModalOpen: true
})
};
// 删除按钮
document.getElementsByClassName('delete-button')[0].onclick = () => {
confirm({
icon: <ExclamationCircleFilled />,
title: '警告',
content: '是否确定删除点位,删除后信息将无法恢复',
onCancel() {
},
// 确定删除
onOk() {
self.deleteChannel();
},
});
};
});
this.state.map.addPopup(popup);
});
});
markerLayer.addMarker(marker);
}
this.setState({
markerLayerList: [...this.state.markerLayerList, markerLayer],
removeMarker: marker,
})
this.state.map.addMarkerLayer(markerLayer);
}
// 删除按钮
deleteChannel = () => {
this.startLoading();
this.state.pop.hide();
self = this;
let layerId = this.state.popParameter.belongLayerId;
deletePoint({ id: this.state.popParameter.pointId }).then((e) => {
if (e.success) {
message.success('点位删除成功!');
setTimeout(() => {
// 重新获取点位
self.refs.getLayerDataFun.changeUnitAmount(layerId);
let filter = this.state.districtAdcode || this.state.cityAdcode;
self.refs.getLayerDataFun.getBasicLayerMenu(filter);
this.getLayerPoints(layerId, true, 1);
self.stopLoading();
}, 1000);
this.getLayerPoints(layerId, false, 1);
} else {
message.error('点位删除失败!');
}
});
this.setState({
pop: null,
popParameter: {},
});
}
// 在地图上设置热力图 【经度,纬度】
// setHeatMap = (data, layerId) => {
// let self = this;
// let map = this.state.map;
// let LabelsData = data || [];
// let heatLayer = new Heatmap({nmae: layerId})
// .source(LabelsData)
// .shape('heatmap')
// .size('mag', [ 0, 1.0 ]) // weight映射通道
// .style({
// intensity: 2,
// radius: 20,
// rampColors: {
// colors: [
// '#FF4818',
// '#F7B74A',
// '#FFF598',
// '#91EABC',
// '#2EA9A1',
// '#206C7C'
// ].reverse(),
// positions: [ 0, 0.2, 0.4, 0.6, 0.8, 1.0 ]
// }
// });
// map.addLayer(heatLayer);
// // 加载热力图插件
// // var heatmap;
// // var points = [];
// // LabelsData.forEach(function (item) {
// // points.push(
// // {
// // "lng": Number(item.location.split(',')[0]),
// // "lat": Number(item.location.split(',')[1]),
// // "count": item.weight,
// // "id": layerId,
// // }
// // )
// // })
// // map.plugin(["AMap.Heatmap"],function(){
// // // 在地图对象叠加热力图
// // heatmap = new AMap.Heatmap(map, {
// // radius: 25, //热力图的每个点的半径大小 [0,+∞)
// // opacity: [0, 0.8], //热力图的透明度,分别对应heatmap.js的minOpacity和maxOpacity
// // gradient:{ //热力图的颜色渐变区间。 {JSON}:key 插值的位置, 0-1; value颜色值
// // 0.5: 'blue',
// // 0.65: 'rgb(117,211,248)',
// // 0.7: 'rgb(0, 255, 0)',
// // 0.9: '#ffea00',
// // 1.0: 'red'
// // },
// // });
// // // 设置热力图数据集
// // heatmap.setDataSet({data:points,max:100});
// // });
// // this.setState((state) => {
// // state.heatMapList.push(heatmap);
// // });
// }
// 获取围栏图层数据
getLayerShapes = (layerId, selected, adcode) => {
if (selected) {
return getLayerShapesApi({
adcode: adcode || this.state.districtAdcode || this.state.cityAdcode || this.state.provinceAdcode,
layerId: layerId
}).then((e) => {
let positionBorderData = e.data;
this.setPolygon(positionBorderData, layerId);
});
} else {
this.state.map.removeAllLayer();
}
}
// 在地图上设置围栏、面
setPolygon = (d, layerId) => {
let self = this;
let map = this.state.map;
let data = d || [];
let overlayList = [];
const layer = new PolygonLayer({})
.source(data)
.shape('extrude')
.size('h20', [100, 120, 160, 200, 260, 500])
.color('h20', [
'#816CAD',
'#A67FB5',
'#C997C7',
'#DEB8D4',
'#F5D4E6',
'#FAE4F1',
'#FFF3FC'
]);
map.addLayer(layer);
// paths.forEach(function(path) {
// if(path.type === "ENVELOPE"){
// var tmp1 = path.positionRectangle[0]
// var tmp2 = path.positionRectangle[1]
// var southWest = new AMap.LngLat(tmp1[0], tmp1[1])
// var northEast = new AMap.LngLat(tmp2[0], tmp2[1])
// var bound = new AMap.Bounds(southWest,northEast);
// var rectangle = new AMap.Rectangle({
// id: layerId,
// bounds: bound,
// strokeColor: path.borderColor,
// strokeWeight: 1,
// strokeOpacity: path.borderOpacity,
// fillOpacity: path.opacity,
// fillColor: path.themeColor,
// zIndex: 50,
// });
// overlayList.push(rectangle);
// }else if(path.type === "POLYGON"){
// var polygon = new AMap.Polygon({
// id: layerId,
// path: path.positionBorder,
// strokeColor: path.borderColor,
// strokeWeight: 1,
// strokeOpacity: path.borderOpacity,
// fillOpacity: path.opacity,
// fillColor: path.themeColor,
// zIndex: 50,
// });
// overlayList.push(polygon);
// }
// });
// let overlay = new AMap.OverlayGroup(overlayList);
// map.add(overlay)
// 缩放地图到合适的视野级别
// map.setFitView([ polygon ])
}
// 获取省
getAllProvince = () => {
return getAllProvinceApi().then((e) => {
let provinceData = e.data;
let provinceList = [];
for (let i in provinceData) {
provinceList.push({
'value': provinceData[i].provinceAdcode,
'label': provinceData[i].provinceName,
'zoom': 7,
'len': provinceData[i].centerCoordinate && provinceData[i].centerCoordinate.split(',')[0],
'lat': provinceData[i].centerCoordinate && provinceData[i].centerCoordinate.split(',')[1],
})
}
this.setState({
provinceList: provinceList
})
});
}
// 选择省 provinceAdcode:省编码 data:省数据
onProvinceChange = (provinceAdcode, data) => {
console.log("provinceList", this.state.provinceList)
console.log("data", data)
console.log("provinceAdcode", provinceAdcode)
let self = this;
// 清除点位图层
let getLayers = self.state.markerLayerList;
for (let i = 0; i < getLayers.length; i++) {
self.state.map.removeMarkerLayer(getLayers[i]);
}
// 清除子组件的已选图层
this.refs.getLayerDataFun.state.selectLayerList = [];
this.refs.getLayerDataFun.state.selectLayerIdList = [];
// 清除所选市
this.onCityChange();
data && this.gotoProvince(data)
// 根据所选省获取市
this.getCityByProvince(`${provinceAdcode}`);
// 根据所选省限制输入框的提示内容
data && this.state.autoComplete.setCity(data.value);
console.log("this.state.autoComplete", this.state.autoComplete.opt.city)
this.hideHeatMap();
this.setState({
provinceAdcode: provinceAdcode ? `${provinceAdcode}` : '', // 省编码
provinceLabel: data ? data.label : '', // 省名称
zoom: 8, // 缩放级别
cityAdcode: '',//选中的市
cityLabel: '',
districtList: [],//区
districtAdcode: '',
})
ProvinceAdcode = provinceAdcode;
ProvinceData = data;
}
// 获取市
getCityByProvince = (provinceAdcode) => {
if (provinceAdcode === undefined || provinceAdcode === null || provinceAdcode === "" || provinceAdcode === 'undefined') {
this.setState({
cityList: []
})
return false
}
return getCityByProvinceApi({ provinceAdcode: provinceAdcode }).then((e) => {
let cityData = e.data;
let cityList = [];
for (var i in cityData) {
cityList.push({
'value': cityData[i].cityAdcode,
'label': cityData[i].cityName,
'zoom': 10,
// 'len': cityData[i].centerCoordinate.split(',')[0],
'len': cityData[i].centerCoordinate && cityData[i].centerCoordinate.split(',')[0],
'lat': cityData[i].centerCoordinate && cityData[i].centerCoordinate.split(',')[1],
})
}
this.setState({
cityList: cityList
})
});
}
//选择市 cityAdcode:市编码 data:市数据
onCityChange = (cityAdcode, data) => {
console.log("document.getElementsByClassName('createTips___PYONM')", document.getElementsByClassName('createTips___PYONM'))
var self = this;
console.log("cityAdcode", cityAdcode)
if (cityAdcode === undefined || cityAdcode === null || cityAdcode === "" || cityAdcode === 'undefined') {
this.setState({
cityAdcode: '',
cityLabel: '',
districtAdcode: ''
})
return false
}
self.startLoading();
// 清除点位图层
let getLayers = self.state.markerLayerList;
for (let i = 0; i < getLayers.length; i++) {
self.state.map.removeMarkerLayer(getLayers[i]);
}
this.refs.getLayerDataFun.state.selectLayerIdList = [];
// 根据所选市获取区
this.getDistrictByCity(`${cityAdcode}`);
this.refs.getLayerDataFun.getBasicLayerMenu(`${cityAdcode}`).then(() => {
self.stopLoading();
});
data && this.gotoCity(data);
// 根据所选省限制输入框的提示内容
data && this.state.autoComplete.setCity(data.value);
console.log("this.state.autoComplete", this.state.autoComplete.opt.city)
this.hideHeatMap();
this.setState({
cityAdcode: cityAdcode ? `${cityAdcode}` : '',
cityLabel: data ? data.label : '',
center: data && [parseFloat(data.lat), parseFloat(data.len)],
zoom: 10,
districtAdcode: ''
})
CityAdcode = cityAdcode;
CityData = data;
}
// 获取区
getDistrictByCity = (cityAdcode) => {
if (cityAdcode === undefined || cityAdcode === null || cityAdcode === "" || cityAdcode === 'undefined') {
this.setState({
districtList: []
})
return false
}
return getDistrictByCityApi({ cityAdcode: cityAdcode }).then((e) => {
console.log("cityadcode", e.data)
let districtData = e.data;
let districtList = [];
for (var i in districtData) {
districtList.push({
'value': districtData[i].districtAdcode,
'label': districtData[i].districtName,
'zoom': 13,
'len': districtData[i].centerCoordinate && districtData[i].centerCoordinate.split(',')[0],
'lat': districtData[i].centerCoordinate && districtData[i].centerCoordinate.split(',')[1],
})
}
this.setState({
districtList: districtList
})
});
}
//选择区
onDistrictChange = (provinceAdcode, data) => {
var self = this;
if (provinceAdcode === undefined || provinceAdcode === null || provinceAdcode === "" || provinceAdcode === 'undefined') {
this.setState({
districtAdcode: '',
})
return false
}
self.startLoading();
let getLayers = self.state.markerLayerList;
console.log("getLayers✈······", getLayers)
for (let i = 0; i < getLayers.length; i++) {
self.state.map.removeMarkerLayer(getLayers[i]);
}
this.refs.getLayerDataFun.state.selectLayerIdList = [];
// this.state.map.remove(getOverlays);
this.refs.getLayerDataFun.getBasicLayerMenu(`${provinceAdcode}`).then(() => {
self.stopLoading();
});
data && this.gotoCity(data);
// 根据所选省限制输入框的提示内容
data && this.state.autoComplete.setCity(data.label);
console.log("this.state.autoComplete", this.state.autoComplete.opt.city)
this.hideHeatMap();
this.setState({
districtAdcode: provinceAdcode ? `${provinceAdcode}` : '',
center: data && [parseFloat(data.lat), parseFloat(data.len)],
zoom: 13,
})
DistrictAdcode = provinceAdcode;
DistrictData = data;
}
onSearchSwitch = (data) => {
if (data === "1") {
this.setState({
inputExplainKey: 1,
inputExplainValue: "请输入经纬度详情格式例如116.405285,39.904989",
inputContent: ""
})
} else {
this.setState({
inputExplainKey: 0,
inputExplainValue: "请输入地址详情信息",
inputContent: ""
})
}
}
// 地图搜索
onSearchMap = () => {
// 0地址 1经纬度
if (this.state.inputExplainKey === 1) {
// 判断经纬度是否为空
let location = this.state.inputContent
if (location === "" || location === null) {
nullSearchLocation();
return false;
} else {
let data = {
'zoom': 8,
'len': location.split(',')[0],
'lat': location.split(',')[1],
}
this.gotoCity(data)
let icon = "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png";
let searchPointMarker = new Marker().setLnglat({ lng: location.split(',')[0], lat: location.split(',')[1] });
this.state.map.addMarker(searchPointMarker);
successSearchAddress();
}
} else {
// 判断地址是否为空
let address = this.state.inputContent
if (address === "" || address === null) {
nullSearchAddress();
return false;
} else {
address = this.state.provinceLabel + this.state.cityLabel + address;
return getPointByAddressApi({ address: address }).then((e) => {
let coordinate = e.data;
if (coordinate === "" || coordinate === null) {
errorSearchAddress();
} else {
let data = {
'zoom': 8,
'len': coordinate.location.split(',')[0],
'lat': coordinate.location.split(',')[1],
}
this.gotoCity(data)
let icon = "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png";
let searchPointMarker = new Marker().setLnglat({ lng: coordinate.location.split(',')[0], lat: coordinate.location.split(',')[1] });
this.state.map.addMarker(searchPointMarker);
successSearchAddress();
}
});
}
}
}
// 开启点位创建
enableDrawPoint = () => {
if (this.state.cityAdcode == '' && this.state.districtAdcode == '') {
message.error('请至少选择行政区域至城市再进行点位创建');
return false;
}
let selectLayerList = this.refs.getLayerDataFun.state.selectLayerList;
selectLayerList = selectLayerList.filter((item) => {
if (item.isCustomize == 1) {
return item;
}
})
if (selectLayerList.length == 0) {
message.error('请至少选中一个个人图层');
return false;
}
// 提示文字
document.getElementsByClassName('createTips')[0].className = 'createTips show';
// 鼠标变十字
// this.state.map.map.setDefaultCursor('crosshair'); 将默认鼠标样式改为十字,地图内有元素会变为手指
document.getElementsByClassName('amap-layer')[0].className = 'amap-layer cursor-crosshair';
// 关闭地图双击放大
this.state.map.setMapStatus({
doubleClickZoom: false,
})
// 获取点击时鼠标的地图坐标
const mouseLocation = new MouseLocation();
this.state.map.addControl(mouseLocation);
this.setState({
// 按键不可用
disabled: !this.state.disabled,
selectLayerList: selectLayerList,
mouseLocation: mouseLocation,
});
// 开启地图的事件监听,双击添加,右键取消
// 双击事件
this.state.map.on('dblclick', this.dblclickEvent);
// 右键事件
this.state.map.on('contextmenu', this.contextmenuEvent);
// 键盘事件
const that = this;
document.onkeydown = function (event) {
if (event.key === 'Escape') {
that.disableDrawPoint();
document.onkeydown = null;
}
};
}
// 点位创建地图鼠标双击事件
dblclickEvent = (e) => {
// 开启双击地图放大 不能放在这,会导致弹框的同时放大地图,将开启放大放在弹框关闭事件中
// 取消提示文字
document.getElementsByClassName('createTips')[0].className = 'createTips hidden';
// 添加点位
this.showModal(this.state.mouseLocation.location.toString());
// 鼠标取消十字
// this.state.map.map.setDefaultCursor('auto');
document.getElementsByClassName('amap-layer')[0].className = 'amap-layer';
// 删除右键事件监听
this.state.map.off('contextmenu', this.contextmenuEvent);
// 删除鼠标经纬度组件
this.state.map.removeControl(this.state.mouseLocation);
this.state.mouseLocation = {};
// 按键可用
this.setState({
disabled: !this.state.disabled,
});
}
// 点位创建地图右键事件
contextmenuEvent = (e) => {
this.disableDrawPoint();
}
// 取消点位创建
disableDrawPoint = () => {
// 开启双击地图放大
this.state.map.setMapStatus({
doubleClickZoom: true
})
// 取消提示文字
document.getElementsByClassName('createTips')[0].className = 'createTips hidden';
// 鼠标取消十字
// this.state.map.map.setDefaultCursor('auto');
document.getElementsByClassName('amap-layer')[0].className = 'amap-layer';
// 删除鼠标经纬度组件
this.state.map.removeControl(this.state.mouseLocation);
this.state.mouseLocation = {};
// 删除双击事件监听
this.state.map.off('dblclick', this.dblclickEvent);
// 删除右键事件监听
this.state.map.off('contextmenu', this.contextmenuEvent);
// 按键可用
this.setState({
disabled: !this.state.disabled,
});
}
//弹出框事件
showModal = (newPointLocation) => {
// queryUserLayers().then((e) => {
// let data = e.data;
// let selectLayerList = [];
// for (var i in data) {
// selectLayerList.push({
// 'value': data[i].id,
// 'label': data[i].name,
// })
// }
// this.setState({
// isModalOpen: true,
// selectLayerList: selectLayerList,
// newPointLocation: newPointLocation,
// });
// });
// 关闭双击事件监听事件
this.state.map.off('dblclick', this.dblclickEvent);
this.setState({
isModalOpen: true,
newPointLocation: newPointLocation,
});
};
// 修改按钮
editChannel = () => {
this.startLoading();
self = this;
self.state.pop.hide();
let param = {
"id": this.state.pointEdit.pointId,
"name": this.state.pointEdit.name,
"note": this.state.pointEdit.note,
"address": this.state.pointEdit.address,
};
updatePoint(param).then((e) => {
if (e.success) {
setTimeout(() => {
// 重新获取点位
// self.getLayerPoints(self.state.popParameter.layerId, true, 1);
self.getLayerPoints(self.state.pointEdit.layerId, true, 1);
self.stopLoading();
}, 1000);
// self.getLayerPoints(self.state.popParameter.layerId, false, 1);
self.getLayerPoints(self.state.pointEdit.layerId, false, 1);
} else {
message.error('点位更新失败!');
console.log("点位更新失败!", e)
}
})
self.setState({
isEditModalOpen: false,
pop: null,
});
}
handleOk = (values) => {
this.startLoading();
// 开启双击地图放大
this.state.map.setMapStatus({
doubleClickZoom: true
})
createPoint({ //创建图层
"layerId": this.state.pointAdd.layerId,
"name": this.state.pointAdd.name,
"note": this.state.pointAdd.note,
"address": this.state.pointAdd.address,
"cityAdcode": this.state.cityAdcode,
"districtAdcode": this.state.districtAdcode,
"location": this.state.newPointLocation,
"provinceAdcode": this.state.provinceAdcode,
}).then((e) => {
let layerId = this.state.pointAdd.layerId;
if (e.success) {
message.success('点位创建成功!');
setTimeout(() => {
this.getLayerPoints(layerId, true, 1);
this.stopLoading();
// this.refs.getLayerDataFun.changeUnitAmount(this.state.pointAdd.layerId);
}, 1000);//true新增1点
let filter = this.state.districtAdcode || this.state.cityAdcode;
this.refs.getLayerDataFun.getBasicLayerMenu(filter)
// this.refs.getLayerDataFun.changeSelectStatus();
this.setState({
isModalOpen: false,
pointAdd: {},
});
} else {
message.error('点位创建失败!');
}
})
};
handleCancel = () => {
// 开启双击地图放大
this.state.map.setMapStatus({
doubleClickZoom: true
})
// this.state.pointDrawer.removeActiveFeature();
// this.state.pointDrawer.disable();
this.setState({
isModalOpen: false,
pointAdd: {},
});
};
handleEditCancel = () => {
this.setState({
isEditModalOpen: false,
pointEdit: {},
});
};
onLayerNameChange = (e) => {
this.setState({
pointAdd: {
"layerId": e,
"name": this.state.pointAdd.name,
"note": this.state.pointAdd.note,
"address": this.state.pointAdd.address,
},
})
}
onEditLayerNameChange = (e) => {
this.setState({
pointEdit: {
"layerId": e,
"name": this.state.pointEdit.name,
"note": this.state.pointEdit.note,
"address": this.state.pointEdit.address,
"pointId": this.state.pointEdit.pointId,
},
})
}
onPointAddNameChange = (e) => {
this.setState({
pointAdd: {
"layerId": this.state.pointAdd.layerId,
"name": e.currentTarget.value,
"note": this.state.pointAdd.note,
"address": this.state.pointAdd.address,
},
})
}
onEditPointAddNameChange = (e) => {
this.setState({
pointEdit: {
"layerId": this.state.pointEdit.layerId,
"name": e.currentTarget.value,
"note": this.state.pointEdit.note,
"pointId": this.state.pointEdit.pointId,
"address": this.state.pointEdit.address,
},
})
}
onPointAddAddressChange = (e) => {
this.setState({
pointAdd: {
"layerId": this.state.pointAdd.layerId,
"name": this.state.pointAdd.name,
"note": this.state.pointAdd.note,
"address": e.currentTarget.value,
},
})
}
onEditPointAddAddressChange = (e) => {
this.setState({
pointEdit: {
"layerId": this.state.pointEdit.layerId,
"name": this.state.pointEdit.name,
"note": this.state.pointEdit.note,
"pointId": this.state.pointEdit.pointId,
"address": e.currentTarget.value,
},
})
}
onLayerNoteChange = (e) => {
this.setState({
pointAdd: {
"layerId": this.state.pointAdd.layerId,
"name": this.state.pointAdd.name,
"note": e.currentTarget.value,
"address": this.state.pointAdd.address,
},
})
}
onEditLayerNoteChange = (e) => {
this.setState({
pointEdit: {
"layerId": this.state.pointEdit.layerId,
"name": this.state.pointEdit.name,
"note": e.currentTarget.value,
"pointId": this.state.pointEdit.pointId,
"address": this.state.pointEdit.address,
},
})
}
onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
}
hiddenLayer = () => {
let layer = document.querySelector('.layer-data-wrap');
let btn = document.querySelector('.hiddenBtn');
let icon = document.querySelector('.anticon-double-left');
console.log("hidden layer", icon);
layer.style.animationPlayState = 'running';
btn.style.animationPlayState = 'running';
icon.style.animationPlayState = 'running';
}
render() {
return (
<div id='base_map' className={styles.basseMap} >
<Spin id='spin-show' size='large' spinning={this.state.loading}></Spin>
<Header></Header>
{/* 筛选框 */}
<Card className={styles.selectWrap} bordered={false}>
<Row>
<Col span={12}>
<Input.Group compact style={{ display: "inline" }}>
<label className={styles.labelForm}>行政区域</label>
<Select
style={{ width: 120, marginLeft: 18 }}
onChange={this.onProvinceChange}
options={this.state.provinceList}
value={this.state.provinceAdcode}
allowClear />
<Select style={{ width: 120, marginLeft: 18 }} onChange={this.onCityChange} options={this.state.cityList} value={this.state.cityAdcode} allowClear />
<Select style={{ width: 120, marginLeft: 18 }} onChange={this.onDistrictChange} options={this.state.districtList} value={this.state.districtAdcode} allowClear />
</Input.Group>
</Col>
<Col span={12}>
<Input.Group compact style={{ display: "inline", float: "right" }}>
<label className={styles.labelForm}>查询</label>
<Select defaultValue="0" style={{ width: '80px' }} onChange={(e) => {
this.onSearchSwitch(e);
}}>
<Option value="0">地址</Option>
<Option value="1">经纬度</Option>
</Select>
<Input id="tipinput" style={{ width: '60%', height: 32, marginLeft: 18 }}
placeholder={this.state.inputExplainValue}
value={this.state.inputContent}
onChange={(e) => {
// console.log("input", e.target.value)
this.setState({
inputContent: e.target.value
})
}} />
<Button
type="primary"
style={{ color: '#2F66F2', backgroundColor: 'white', }}
icon={<AimOutlined />}
onClick={this.onSearchMap}
/>
</Input.Group>
</Col>
</Row>
</Card>
<div className={'createTips hidden'}>
<span>您已处于点位创建状态
可操作鼠标进行点位创建
左键单击为地图拖动效果
右键单击为取消点位创建
滚轮可控制地图放大缩小
<strong>左键双击</strong><strong></strong></span>
</div>
{/* 图层数据显示 */}
<LayerData
ref="getLayerDataFun"
adcode={{ cityAdcode: this.state.cityAdcode, districtAdcode: this.state.districtAdcode }}
getLayerPoints={this.getLayerPoints}
getLayerShapes={this.getLayerShapes}
startLoading={this.startLoading}
stopLoading={this.stopLoading}
/>
{/* <Button onClick={this.hiddenLayer} className='hiddenBtn'><DoubleLeftOutlined/></Button> */}
<div className={styles.btnRightWrap}>
<Button type="primary" className={styles.btnRight} onClick={this.enableDrawPoint} disabled={this.state.disabled}>点位创建</Button>
{/* <Button type='primary' danger className={styles.btnRight} onClick={() => this.state.pointDrawer?.disable()}>停止创建</Button> */}
<Modal title="点位创建"
open={this.state.isModalOpen}
onOk={this.handleOk}
onCancel={this.handleCancel}
className='add-point-modal'
>
<Form name='base' id='add-point-form' onFinish={this.handleOk} onFinishFailed={this.onFinishFailed}>
<Form.Item label="选择自定义图层"
rules={[
{
required: true,
message: '请输入图层名称!',
}
]}>
<Select name='name' value={this.state.pointAdd.layerId}
options={this.state.selectLayerList}
onChange={this.onLayerNameChange}
allowClear>
</Select>
</Form.Item>
<Form.Item label="点位名称"
rules={[
{
required: true,
message: '请输入点位名称!',
}
]}
>
<Input name='note'
value={this.state.pointAdd.name}
onChange={this.onPointAddNameChange} />
</Form.Item>
<Form.Item label="点位地址"
rules={[
{
required: true,
message: '请输入点位地址!',
}
]}
>
<Input name='note' value={this.state.pointAdd.address} onChange={this.onPointAddAddressChange} />
</Form.Item>
<Form.Item label="图层备注">
<Input name='note' value={this.state.pointAdd.note} onChange={this.onLayerNoteChange} />
</Form.Item>
</Form>
<Alert message="退出将丢失已填信息" type="warning" showIcon />
</Modal>
<Modal title="点位修改"
open={this.state.isEditModalOpen}
onOk={this.editChannel}
onCancel={this.handleEditCancel}
className='add-point-modal'
>
<Form name='base' id='add-point-form' onFinish={this.editChannel} onFinishFailed={this.onFinishFailed}>
{/* <Form.Item label="选择自定义图层"
rules={[
{
required: true,
message: '请输入图层名称!',
}
]}>
<Select name='name'
// value={this.state.pointEdit.layerId}
defaultValue={() => {
return this.state.selectLayerList.map((item) => {
if (item.value == this.state.pointEdit.layerId.toString()) {
return item;
}
});
}}
options={this.state.selectLayerList}
onChange={this.onEditLayerNameChange}
allowClear>
</Select>
</Form.Item> */}
<Form.Item label="点位名称"
rules={[
{
required: true,
message: '请输入点位名称!',
}
]}
>
<Input name='note'
value={this.state.pointEdit.name}
onChange={this.onEditPointAddNameChange} />
</Form.Item>
<Form.Item label="点位地址"
rules={[
{
required: true,
message: '请输入点位地址!',
}
]}
>
<Input name='note' value={this.state.pointEdit.address} onChange={this.onEditPointAddAddressChange} />
</Form.Item>
<Form.Item label="图层备注">
<Input name='note' value={this.state.pointEdit.note} onChange={this.onEditLayerNoteChange} />
</Form.Item>
</Form>
<Alert message="退出将丢失已填信息" type="warning" showIcon />
</Modal>
<Button disabled className={styles.btnRight}>点位导入</Button>
</div>
{/* 地图 */}
<div className={styles.mapWrap} id='redio-btn-group'>
<div style={{ width: '100%', height: '100vh' }} id="container" />
</div>
<div className='hideItem'>
<Pop popParameter={this.state.popParameter} className='hideItem'></Pop>
</div>
</div>
)
}
}
export default BaseMap