map/src/pages/BaseMap/index.js

571 lines
22 KiB
JavaScript
Raw Normal View History

2023-08-30 13:55:59 +08:00
import React from 'react';
import { Select, Input, Card, Col, Row, Button, message } from 'antd';
import axios from 'axios';
import LayerData from './LayerData';
import { AimOutlined } from '@ant-design/icons';
import Guide from '../../components/Guide/index.ts'
2023-10-16 20:52:36 +08:00
import { GaodeMap ,Scene, PointLayer } from '@antv/l7';
2023-08-30 13:55:59 +08:00
import styles from './index.less';
const { Option } = Select;
const AMap = window.AMap;
let infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});
const nullSearchAddress = () => {
message.error('地址信息为空');
};
const errorSearchAddress = () => {
message.error('地址搜索信息异常,请联系开发人员');
};
const successSearchAddress = () => {
message.success('已成功进行地图定位');
};
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: [],
}
}
// 钩子,打开执行
componentDidMount = () => {
this.getAllProvince();
this.createMap();
}
// 创建地图
createMap = () => {
const scene = new Scene({
id: 'container',
map: new GaodeMap({
pitch: 20,
style: 'light',
center: [ 116.405285, 39.904989 ],
zoom: 3
})
});
this.setState({
map: scene
});
// let map = new AMap.Map('container', {
// resizeEnable: true,
// center: [116.405285,39.904989],
// zoom: 4,
// });
// this.setState({
// map: map
// });
}
//根据cityname、adcode、citycode设置地图位置
gotoCity = (data) => {
let zoom = data.zoom || 10;
let lng = data.len || 116.405285;
let lat = data.lat || 39.904989;
this.state.map.setZoomAndCenter(zoom, [lng, lat]);
}
// 获取图层明细点位数据/热力图数据
2023-09-06 20:23:32 +08:00
getLayerPoints = (layerId, selected, nodeType) => {
2023-08-30 13:55:59 +08:00
if (selected) {
return axios.get('/api/basicMap/getLayerPoints', {
params: {
adcode: this.state.districtAdcode || this.state.cityAdcode || this.state.provinceAdcode,
layerId: layerId
}
}).then((e) => {
let layerPointsData = e.data.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);
}
});
} else {
let self = this;
let getLayers = self.state.map.getLayers();
for (let i = 0; i < getLayers.length; i++) {
// if (getLayers[i].CLASS_NAME === 'AMap.LabelsLayer' && getLayers[i].De.id === layerId) {
// self.state.map.remove(getLayers[i]);
// }
if (getLayers[i].name == layerId) {
self.state.map.removeLayer(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 || [];
2023-09-06 20:23:32 +08:00
let logoImage = data.length > 0 && data[0].logoImage;
map.addImage = (layerId, logoImage);
2023-08-30 13:55:59 +08:00
const pointLayer = new PointLayer({name: layerId})
.source(LabelsData, {
parser: {
type: 'json',
x: 'lng',
y: 'lat',
}
})
2023-09-06 20:23:32 +08:00
.shape(layerId)
.size(30)
2023-08-30 13:55:59 +08:00
.color('mag', mag => {
return mag > 4.5 ? '#5B8FF9' : '#5CCEA1';
})
.active(true)
.style({
opacity: 0.6,
strokeWidth: 3
});
map.addLayer(pointLayer);
//初始化图层
// var markers = [];
// var allowCollision = true;
// var layer = new AMap.LabelsLayer({
// id: layerId,
// zooms: [3, 20],
// zIndex: 1000,
// allowCollision,
// });
// layer.add(markers);
// // 图层添加到地图
// map.add(layer);
// // 初始化 labelMarker
// let curData, labelMarker;
// for (let i = 0; i < LabelsData.length; i++) {
// curData = {
// name: LabelsData[i].pointName,
// address: LabelsData[i].address,
// position: [LabelsData[i].location.split(',')[0],LabelsData[i].location.split(',')[1]],
// zooms: [5, 20],
// opacity: 1,
// zIndex: 10,
// fold: true,
// icon: {
// type: 'image',
// image: LabelsData[i].logoImage,
// size: [30, 30],
// anchor: 'center',
// },
// extData: {
// index: i
// }
// };
// labelMarker = new AMap.LabelMarker(curData);
// //整理详情显示信息
// let content = '<h3>详情信息</h3>';
// let detailVisibleFields = LabelsData[i].detailVisibleFields || [];
// for(let j = 0;j < detailVisibleFields.length;j++){
// let fieldNameStr = detailVisibleFields[j].fieldName;
// let fieldValue = LabelsData[i][fieldNameStr];
// content += '<p><label>' + detailVisibleFields[j].fieldShowName + '</label><span>' + fieldValue + '</span></p>'
// }
// labelMarker.content = content;
// labelMarker.on('click', self.markerClick);
// markers.push(labelMarker);
// }
// // 将 marker 添加到图层
// layer.add(markers);
}
// 点击点显示详细信息
markerClick = (e) => {
infoWindow.setContent(e.target.content);
infoWindow.open(this.state.map, e.target.getPosition());
}
// 在地图上设置热力图 【经度,纬度】
setHeatMap = (data, layerId) => {
let self = this;
let map = this.state.map;
let LabelsData = data || [];
// 加载热力图插件
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 axios.get('/api/basicMap/getLayerShapes', {
params: {
adcode: adcode || this.state.districtAdcode || this.state.cityAdcode || this.state.provinceAdcode,
layerId: layerId
}
}).then((e) => {
let positionBorderData = e.data.data;
this.setPolygon(positionBorderData, layerId);
});
} else {
this.state.map.removeAllLayer();
// let self = this;
// let getOverlays = self.state.map.getAllOverlays();
// for (let i = 0; i < getOverlays.length; i++) {
// if (getOverlays[i].De.id === layerId) {
// self.state.map.remove(getOverlays[i]);
// }
// }
}
}
// 在地图上设置围栏、面
setPolygon = (d, layerId) => {
let self = this;
let map = this.state.map;
let paths = d || [];
let overlayList = [];
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 axios.get('/api/mapCommon/getAllProvince').then((e) => {
let provinceData = e.data.data;
let provinceList = [];
for (var i in provinceData) {
provinceList.push({
'value': provinceData[i].provinceAdcode,
'label': provinceData[i].provinceName,
'zoom': 4,
'len': provinceData[i].centerCoordinate && provinceData[i].centerCoordinate.split(',')[0],
'lat': provinceData[i].centerCoordinate && provinceData[i].centerCoordinate.split(',')[1],
})
}
this.setState ({
provinceList: provinceList
})
});
}
// 选择省
onProvinceChange = (provinceAdcode, data) => {
var self = this;
let getLayers = this.state.map.getLayers();
// let getOverlays = this.state.map.getAllOverlays();
for (let i = 0; i < getLayers.length; i++) {
if (getLayers[i].CLASS_NAME === 'AMap.LabelsLayer') {
self.state.map.remove(getLayers[i]);
}
}
// this.state.map.remove(getOverlays);
this.getCityByProvince(`${provinceAdcode}`);
this.hideHeatMap();
this.setState ({
2023-10-17 20:04:49 +08:00
provinceAdcode: provinceAdcode ? `${provinceAdcode}` : '',
provinceLabel: data ? data.label : '',
2023-08-30 13:55:59 +08:00
zoom: 4,
2023-10-17 20:04:49 +08:00
districtList: [],//区
cityAdcode:'',//选中的市
cityLabel: '',
districtAdcode: '',
2023-08-30 13:55:59 +08:00
})
}
// 获取市
getCityByProvince = (provinceAdcode) => {
return axios.get('/api/mapCommon/getCityByProvince', {
params: {
provinceAdcode: provinceAdcode
}
}).then((e) => {
let cityData = e.data.data;
let cityList = [];
for (var i in cityData) {
cityList.push({
'value': cityData[i].cityAdcode,
'label': cityData[i].cityName,
'zoom': 10,
'len': cityData[i].centerCoordinate && cityData[i].centerCoordinate.split(',')[0],
'lat': cityData[i].centerCoordinate && cityData[i].centerCoordinate.split(',')[1],
})
}
this.setState ({
cityList: cityList
})
});
}
//选择市
onCityChange = (cityAdcode,data) => {
var self = this;
let getLayers = this.state.map.getLayers();
// let getOverlays = this.state.map.getAllOverlays();
for (let i = 0; i < getLayers.length; i++) {
if (getLayers[i].CLASS_NAME === 'AMap.LabelsLayer') {
self.state.map.remove(getLayers[i]);
}
}
// this.state.map.remove(getOverlays);
this.getDistrictByCity(`${cityAdcode}`);
this.refs.getLayerDataFun.getBasicLayerMenu(`${cityAdcode}`);
data && this.gotoCity(data);
this.hideHeatMap();
2023-10-17 20:04:49 +08:00
2023-08-30 13:55:59 +08:00
this.setState ({
2023-10-17 20:04:49 +08:00
cityAdcode: cityAdcode ? `${cityAdcode}` : '',
cityLabel: data ? data.label : '',
2023-08-30 13:55:59 +08:00
center: data && [parseFloat(data.lat), parseFloat(data.len)],
zoom: 10,
2023-10-17 20:04:49 +08:00
districtAdcode: ''
2023-08-30 13:55:59 +08:00
})
}
// 获取区
getDistrictByCity = (cityAdcode) => {
return axios.get('/api/mapCommon/getDistrictByCity', {
params: {
cityAdcode: cityAdcode
}
}).then((e) => {
let districtData = e.data.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;
let getLayers = this.state.map.getLayers();
// let getOverlays = this.state.map.getAllOverlays();
for (let i = 0; i < getLayers.length; i++) {
if (getLayers[i].CLASS_NAME === 'AMap.LabelsLayer') {
self.state.map.remove(getLayers[i]);
}
}
// this.state.map.remove(getOverlays);
this.refs.getLayerDataFun.getBasicLayerMenu(`${provinceAdcode}`);
data && this.gotoCity(data);
this.hideHeatMap();
this.setState({
2023-10-17 20:04:49 +08:00
districtAdcode: provinceAdcode ? `${provinceAdcode}` : '',
2023-08-30 13:55:59 +08:00
center: data && [parseFloat(data.lat), parseFloat(data.len)],
zoom: 13,
})
}
onSearchSwitch = (data) => {
if(data === "1"){
this.setState({
inputExplainKey: 1,
inputExplainValue: "请输入经纬度详情格式例如116.405285,39.904989",
inputContent: ""
})
}else{
this.setState({
inputExplainKey: 0,
inputExplainValue: "请输入地址详情信息",
inputContent: ""
})
}
}
onSearchMap = () => {
if(this.state.inputExplainKey === 1){
let location = this.state.inputContent
let data = {
'zoom': 13,
'len': location.split(',')[0],
'lat': location.split(',')[1],
}
this.gotoCity(data)
let searchPointMarker = new AMap.Marker({
icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
position: [location.split(',')[0], location.split(',')[1]]
});
this.state.map.add(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 axios.get('/api/mapCommon/getPointByAddress', {
params: {
address: address
}
}).then((e) => {
let coordinate = e.data.data;
if(coordinate === ""||coordinate === null){
errorSearchAddress();
}else{
let data = {
'zoom': 13,
'len': coordinate.location.split(',')[0],
'lat': coordinate.location.split(',')[1],
}
this.gotoCity(data)
let searchPointMarker = new AMap.Marker({
icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
position: [coordinate.location.split(',')[0], coordinate.location.split(',')[1]]
});
this.state.map.add(searchPointMarker);
successSearchAddress();
}
});
}
}
}
render(){
return (
<div className={styles.basseMap} id='base_map'>
{/* 筛选框 */}
<Card className={styles.selectWrap} bordered={false}>
<Row>
<Col span={12}>
<Input.Group compact style={{display:"inline"}}>
<label className={styles.labelForm}>行政区域</label>
2023-10-17 20:04:49 +08:00
<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/>
2023-08-30 13:55:59 +08:00
</Input.Group>
</Col>
<Col span={12}>
<Input.Group compact style={{display:"inline",float:"right"}}>
<label className={styles.labelForm}>查询</label>
<Select defaultValue="0" 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)=>{
this.setState({
inputContent: e.target.value
})
}}/>
<Button
type="primary"
style={{color: '#2F66F2', backgroundColor: 'white', }}
icon={<AimOutlined />}
onClick={this.onSearchMap}
/>
</Input.Group>
</Col>
</Row>
</Card>
{/* 图层数据显示 */}
<LayerData ref="getLayerDataFun" getLayerPoints = {this.getLayerPoints} getLayerShapes = {this.getLayerShapes}/>
{/* 地图 */}
<div className={styles.mapWrap}>
2023-09-06 20:23:32 +08:00
<div style={{width: '100%', height: '100vh'}} id="container" />
2023-08-30 13:55:59 +08:00
</div>
</div>
)
}
}
export default BaseMap