import * as echarts from 'echarts';
|
// import * as shanghaiMap from 'echarts-china-cities-js/echarts-china-cities-js/shanghai.js'; // 修正地图数据文件路径
|
// import 'echarts-china-cities-js/echarts-china-cities-js/shanghai.js'; // 修正地图数据文件路径
|
import { shanghai, jingan } from '@/utils/chart/shanghai.js'; // 确保路径正确
|
|
/**
|
* 计算地图中心点和缩放比例
|
* @param {*} gridData 网格数据
|
* @returns
|
*/
|
function calCenterPointAndZoom(gridData) {
|
let centerLng = 0;
|
let centerLat = 0;
|
let maxLng = -180;
|
let minLng = 180;
|
let maxLat = -90;
|
let minLat = 90;
|
let zoom = 100;
|
gridData.forEach((g) => {
|
centerLng += g.centerLng;
|
centerLat += g.centerLat;
|
maxLng = Math.max(maxLng, g.centerLng);
|
minLng = Math.min(minLng, g.centerLng);
|
maxLat = Math.max(maxLat, g.centerLat);
|
minLat = Math.min(minLat, g.centerLat);
|
});
|
if (gridData.length > 0) {
|
centerLng /= gridData.length;
|
centerLat /= gridData.length;
|
}
|
|
console.log((maxLng - centerLng) / zoom);
|
|
return {
|
centerLng,
|
centerLat,
|
zoom
|
};
|
}
|
|
function generateGridMap(gridData) {
|
// 1. 创建临时DOM元素
|
const div = document.createElement('div');
|
div.style.width = '800px';
|
div.style.height = '400px';
|
document.body.appendChild(div);
|
// 注册上海市地图数据
|
// console.log(shanghaiMap);
|
|
// shanghaiMap(echarts);
|
echarts.registerMap('shanghai', { geoJSON: shanghai });
|
const chart = echarts.init(div);
|
|
// 1. 准备网格数据(转换为ECharts多边形格式)
|
const gridPolygons = gridData.map((grid, index) => ({
|
name: `grid_${index}`,
|
value: [grid.centerLng, grid.centerLat, grid.value], // 中心点经纬度和数值
|
coords: grid.coordinates // 网格四角经纬度坐标数组 [[lng1,lat1], [lng2,lat2], ...]
|
}));
|
const { centerLng, centerLat, zoom } = calCenterPointAndZoom(gridData);
|
|
// 2. 配置项
|
const option = {
|
// title: {
|
// text: 'Travel Routes'
|
// },
|
geo: {
|
map: 'shanghai', // 基础地图
|
center: [centerLng, centerLat],
|
roam: true, // 禁止缩放平移
|
zoom: zoom, // 地图缩放比例
|
label: { show: true }, // 显示地名标签
|
itemStyle: { areaColor: '#ddddddff', borderColor: '#999' }
|
},
|
// series: [
|
// {
|
// type: 'scatter',
|
// coordinateSystem: 'geo',
|
// data: [
|
// {
|
// name: '黄浦区',
|
// value: [121.490317, 31.222771, 100] // 中心点坐标+数值
|
// }
|
// ]
|
// }
|
// ]
|
series: [
|
{
|
type: 'custom',
|
coordinateSystem: 'geo',
|
renderItem: (params, api) => {
|
// 将经纬度转换为屏幕坐标
|
const grid = gridPolygons[params.dataIndex];
|
// const v = api.value(0);
|
const points = grid.coords.map((coord) => api.coord(coord));
|
// const points = grid.coords;
|
return {
|
type: 'polygon',
|
transition: ['shape'],
|
shape: { points },
|
style: api.style({
|
fill: grid.value[2],
|
stroke: 'white',
|
lineWidth: 1
|
})
|
};
|
},
|
data: gridPolygons,
|
label: { show: false }
|
}
|
]
|
};
|
|
chart.setOption(option);
|
// 3. 导出为图片(返回base64)
|
return chart.getDataURL({
|
type: 'png',
|
pixelRatio: 1,
|
backgroundColor: '#ddddddff'
|
});
|
}
|
|
export default { generateGridMap };
|