1. 程式人生 > 其它 >vue2使用echarts內建地圖實現點選事件

vue2使用echarts內建地圖實現點選事件

vue2中echarts的安裝和顯示中國地圖:https://www.cnblogs.com/sunshine233/p/16140522.html

滑鼠事件: https://echarts.apache.org/zh/api.html#echartsInstance.on echarts.getMap():https://echarts.apache.org/zh/api.html#echarts.getMap

demo地址:https://gitee.com/twoflowers/echarts_geo_demo.git


程式碼如下:
<template>
  <div id="app">
<div id="echart_map" ref="echart_map"></div> </div> </template> <script> export default { data() { return { myChart: null, }; }, mounted() { this.showScatterInGeo(this.cityCode); this.clickGoNext(); }, methods: { /* geo:地理座標系元件( https://echarts.apache.org/zh/option.html#geo) 地理座標系元件用於地圖的繪製,支援在地理座標系上繪製散點圖
*/ showScatterInGeo() { this.myChart = this.$echarts.init(this.$refs.echart_map); var chinamap = require("echarts/map/json/china.json"); //使用 require 引入地圖元件,而不是在開頭的 import this.$echarts.registerMap("china", chinamap); this.option = { geo: { type: "map", map:
"china", label: { normal: { color: "#000000", show: true, //省份名稱 }, }, }, series: [ { name: "在地圖中顯示散點圖", type: "scatter", coordinateSystem: "geo", //設定座標系為 geo data: [ //這裡放標註點的座標[{name: "北京",value: [116.46, 39.92]}] { name: "北京", value: [116.41995, 40.18994] }, { name: "鄭州", value: [113.665412, 34.757975] }, { name: "天津", value: [117.205126, 39.034933] }, { name: "昆明", value: [102.81844, 24.906231] }, { name: "廣州", value: [113.26453, 23.155008] }, ], label: { formatter: "{b}", position: "right", show: false, }, emphasis: { label: { show: true, }, }, }, ], }; // 4. myChart.setOption this.myChart.setOption(this.option); }, /* 滑鼠事件: https://echarts.apache.org/zh/api.html#echartsInstance.on echarts.getMap() :https://echarts.apache.org/zh/api.html#echarts.getMap 1. 只有用echarts的地圖,才能使用 echarts.getMap("china").geoJson.features */ clickGoNext() { var that = this; var dataList = that.$echarts.getMap("china").geoJson.features; // console.log("dataList:", dataList); // 滑鼠事件 this.myChart.on("click", function (res) { console.log("click city:", res.name); dataList.forEach((element) => { if (element.properties.name == res.name) { console.log("city code:", element.id); } }); }); }, }, }; </script> <style scoped> #echart_map { width: 100%; height: 500px; background-color: #f1f3f4; } </style>

 效果如下: