import React, { memo, useEffect } from 'react';
import axios from 'axios';
import turfBbox from '@turf/bbox';
import config from '../../../config/api';
import { generateGeojsonData } from '../../../util/layerService';
const { geojson: { GET_URL } } = config;
const PointScatter = memo((props) => {
const { map, layer: { layerId: id, serviceInfo, styleState }, changeServiceInfo } = props;
// 构造id
const layerId = `thematicLayer_geojson_pointScatter_layer_${id}`;
const sourceId = `thematicLayer_geojson_pointScatter_source_${id}`;
// 图层组件卸载需要移除该图层
useEffect(() => {
return () => {
if (map.getLayer(layerId)) {
map.removeLayer(layerId);
map.removeSource(sourceId);
}
};
}, [layerId, sourceId]);
useEffect(() => {
let { bounds, path, legend } = JSON.parse(serviceInfo);
console.log('11111',JSON.parse(serviceInfo));
const { radius, color, hoverColor, opacity, strokeWidth, strokeColor, strokeOpacity } = JSON.parse(styleState);
let sactterDataSource = null; // 散点图源数据
// 判断该图层是否已存在,已经存在,可以设置图层样式
if (map.getLayer(layerId)) {
map.setPaintProperty(layerId, 'circle-opacity', 1 - opacity / 100);
map.setPaintProperty(layerId, 'circle-stroke-opacity', 1 - strokeOpacity / 100);
map.setPaintProperty(layerId, 'circle-stroke-color', `rgb(${strokeColor.r},${strokeColor.g},${strokeColor.b})`);
map.setPaintProperty(layerId, 'circle-stroke-width', strokeWidth);
map.setPaintProperty(layerId, 'circle-color', ["case",
["boolean", ["feature-state", "hover"], false],
`rgb(${hoverColor.r},${hoverColor.g},${hoverColor.b})`,
`rgb(${color.r},${color.g},${color.b})`
]);
map.setPaintProperty(layerId, 'circle-radius', radius);
return;
}
// 获取专题数据
function getThematicDatas() {
return new Promise((resolve, reject) => {
axios.get(path).then((res) => {
try {
if (res.status !== 200) {
return null;
}
const results = res.data.data.results;
resolve(results);
} catch (error) {
reject(new Error(error));
}
});
});
}
getThematicDatas()
.then(results => {
sactterDataSource = generateGeojsonData(results, 'pointScatter');
bounds = turfBbox(sactterDataSource);
// 修改目录树中bounds值
changeServiceInfo({ id, bounds, legend });
addLayer();
})
function addLayer(){
map.addSource(sourceId, {
type: 'geojson',
data: sactterDataSource,
generateId: true
});
const pointLayer = {
'id': layerId,
'source': sourceId,
'type': 'circle',
'paint': {
'circle-radius': radius,
"circle-color": ["case",
["boolean", ["feature-state", "hover"], false],
`rgb(${hoverColor.r},${hoverColor.g},${hoverColor.b})`,
`rgb(${color.r},${color.g},${color.b})`
],
'circle-opacity': 1 - opacity / 100,
'circle-stroke-width': strokeWidth,
'circle-stroke-color': `rgb(${strokeColor.r},${strokeColor.g},${strokeColor.b})`,
'circle-stroke-opacity': 1 - strokeOpacity / 100
}
};
map.addLayer(pointLayer);
map.fitBounds(bounds);
}
}, [layerId, sourceId, map, serviceInfo, styleState]);
return null;
});
export default PointScatter;