Echarts地图背景贴图

188 阅读1分钟

由于echarts的地图系列没有提供背景贴图的api,所以我们做贴图的时候往往要另辟蹊径,我想的这个方法是通过custom系列实现的,缩放和移动都可以达到比较好的表现效果。

// 先建立地理坐标
chartInstance.setOption(
    {
        geo: {
            map: 'gansu',
            roam: true,
        },
    }
)

// 用两个地理坐标设定一个参考距离
const referDistance = chartInstance.convertToPixel({ geoIndex: 0 }, [105.724998, 34.578529])[0] - chartInstance.convertToPixel({ geoIndex: 0 }, [103.823557, 36.058039])[0];

chartInstance.setOption(
    {
        series: [
            {
                type: 'custom',
                coordinateSystem: 'geo',
                renderItem: (p, api) => {
                    return {
                        type: 'image',
                        // 通过地理坐标定位
                        position: api.coord([100.6, 37.6]),
                        style: {
                            image: require('./地图背景.png'),
                            // 根据参考距离调整贴图至与地图重合
                            x: (-9.5 * referDistance * p.coordSys.zoom) / 2,
                            y: (-8.3 * referDistance * p.coordSys.zoom) / 2,
                            width: 9.5 * referDistance * p.coordSys.zoom,
                            height: 8.3 * referDistance * p.coordSys.zoom,
                        }
                    }
                },
                // data随便放点数据
                data: [1, 1]
            }
        ]
    }
)

这里是提供一个思路,上面的参考坐标和调整参数根据自己实际情况调整即可