小程式Echarts 構建中國地圖並錨定區域點擊事件
- 2020 年 3 月 18 日
- 筆記
小程式Echarts 構建中國地圖並錨定區域點擊事件
Step1 效果展示

使用的繪圖框架為 Echarts for Wexin
具體API文檔地址請點擊 ---->
Step2 條件準備
1.Github上下載echarts-for-weixin 項目

- 將組件 ec-canvans 全部導入你的小程式中,把ec-canvans 作為組件引用

3.在使用到的頁面註冊該組件
show.json
{ "component": true, "usingComponents": { "ec-canvas": "../../../ec-canvas/ec-canvas" } }show.wxml
<view class="box" > <ec-canvas id="mychart-dom-map" canvas-id="mychart-map" ec="{{ ec }}"></ec-canvas> </view>show.wxss
.box { width:100%; height:100%; position: absolute; top: 0; bottom: 0; left: 0; right: 0; } #mychart-dom-map { position: relative; width: 100%; padding-top: 20rpx; height: 720rpx; }Step3 邏輯實現
3.1 引入地圖數據 data.js
該數據是Canvas繪製地圖的關鍵,可以使用json 或者 js 形式進行導入,小程式中使用js 更為方便。
程式碼過長,託管在Gitee data.js
3.2 組件初始化
通過 pageInstance 綁定page 內事件,進行錨定。
show... 共同構成一個地圖展示組件,可以直接進行引入使用。
show.js
import * as echarts from '../../../ec-canvas/echarts.js'; import geoJson from 'data.js'; let chart = null; let dataList = [{ name: 'china' }]; let pageInstance = {} // 2、進行初始化數據 function initChart(canvas, width, height) { chart = echarts.init(canvas, null, { width: width, height: height }); canvas.setChart(chart); //容器初始化 echarts.registerMap('china', geoJson); //地圖數據註冊 var option = { tooltip: { triggerOn: "click", formatter: function (e, t, n) { pageInstance.BindEvent(e); return e.name } },//點擊響應事件 geo: { map: "china", roam: !1, scaleLimit: { min: 1, max: 2 }, zoom: 1.23, top: 120, label: { normal: { show: !0, fontSize: "10", color: "rgba(0,0,0,0.7)" } }, itemStyle: { normal: { //shadowBlur: 50, //shadowColor: 'rgba(0, 0, 0, 0.2)', borderColor: "rgba(0, 0, 0, 0.2)" }, emphasis: { areaColor: "#f2d5ad", shadowOffsetX: 0, shadowOffsetY: 0, borderWidth: 0 } } },//地圖顏色等配置 series: [{ name: "來源資訊", type: "map", geoIndex: 0, data: dataList }]//對應點擊事件響應 }; chart.setOption(option);//返回初始化結果 return chart; } Component({ /** * 組件的屬性列表 */ options: { addGlobalClass: true, multipleSlots: true }, properties: { }, /** * 組件的初始數據 */ data: { ec: { onInit: initChart } }, /** * 組件的方法列表 */ lifetimes: { created: function () { pageInstance = this; } }, methods: { BindEvent(e){ //點擊事件錨定 // e.name 是 省份 把 需要的操作在該事件內實現 } } })

