search
HomeWeb Front-endVue.jsDetailed explanation of the method of elegantly encapsulating echarts map in vue2 project

vue2How to elegantly encapsulate the echarts map in the project? The following article will introduce to you the more elegant way to encapsulate the echarts map in the vue2 project. I hope it will be helpful to you!

Detailed explanation of the method of elegantly encapsulating echarts map in vue2 project

I have written beforeA more elegant way to encapsulate echarts in the vue project. In large-screen visualization, in addition to data charts, which are commonly used, province and city maps are displayed. Regions are also very commonly used. This is a companion article. [Related recommendations: vuejs video tutorial]

When selecting an area on a regional map, a pop-up window is required to display data. There are various styles, various arrangements of data, graphic and text mashups, Video... In addition to encapsulating the echarts regional map module, this article also introduces the implementation of custom pop-up windows and the way of dynamically loading interface data in custom pop-up windows.

Knowledge that can be learned

  • 1. echarts map module encapsulation, reusable
  • 2. echarts map custom pop-up window (displaying custom styles, custom data, custom pictures), customization of other charts The pop-up window is available for reference.
  • 3. echarts map custom pop-up window dynamically displays interface data
  • 4. Based on the sister article, this map module is also adaptive
  • 5. Based on vue2, vue cli3, echarts 5

Renderings

Let’s take a rendering first and explain the implementation. Effect.

  • 1. Guangzhou area map
  • 2. Customized pop-up window that displays the name and area code of the selected area. A small picture is added to the pop-up window
  • 3. Basically, pictures, videos, etc. can be displayed on custom pop-up windows. Here we only show how to add pictures to custom pop-up windows. The same applies to videos, so I won’t introduce them. If you are interested, just try it yourself
  • 4. The pop-up window data is taken from the simulation interface

Detailed explanation of the method of elegantly encapsulating echarts map in vue2 project

Note

1. echarts in vue 5. Differences introduced between versions below x and versions above 5.x

5.x The following versions

import echarts from 'echarts'

5.x Above version

import * as echarts from 'echarts'

2. Remember to enable the runtime compilation function in vue.config.js

runtimeCompiler: true

implementation

data preparation

|-- public
	|-- data
		|-- 4401.json
		|-- mapdata.json
	|-- images
		|-- map-ic.png
  • 1, 4401.json is the geojson data of the Guangzhou area, used to display the regional map of Guangzhou to echarts
  • 2. mapdata.json is the fake data requested by the simulated interface. You can customize it at will. After obtaining the data, you can handle it according to the situation and pass it to the encapsulated echarts map module. The simulated interface request here is Knowledge can be found here: https://juejin.cn/post/6995147964427534373/
  • 3、map-ic.pngPictures used in the map custom pop-up window

echarts map module package

|-- src
    |-- components
        |-- chart
            |-- options    // 存放各种图表的option
                |-- map    // 地图option
                    |-- index.js

The specific code is as follows:

import * as echarts from 'echarts'

const getSimpleMap = (jsonMap, data, config) => {
  if (!echarts.getMap(jsonMap.mark)) {
    echarts.registerMap(jsonMap.mark, jsonMap.json)
  }
  const defaultConfig = {
    tooltip: {
      // 窗口外框
      trigger: 'item',
      padding: 0,
      borderWidth: 0,
      borderColor: '#FFFFFF',
      backgroundColor: '#FFFFFF',
      formatter: (params) => {
        const { data } = params
        const str = `
Detailed explanation of the method of elegantly encapsulating echarts map in vue2 project${data.name}
区号:
${data.hoverObj == null ? '' : data.hoverObj.adcode}
` return str } }, geo: { map: jsonMap.mark, type: 'map', layoutCenter: ['50%', '50%'], layoutSize: '150%', zoom: 0.65, roam: false, itemStyle: { normal: { areaColor: 'rgba(201, 229, 255, 1)', shadowColor: 'rgba(142, 201, 255, 1)', shadowOffsetX: -5, shadowOffsetY: 12 } } }, series: [ { type: 'map', map: jsonMap.mark, // 自定义扩展图表类型 zoom: 0.65, // 缩放 animationDuration: 1200, itemStyle: { // 地图样式 normal: { borderColor: '#FFFFFF', borderWidth: 3, areaColor: 'rgba(201, 229, 255, 1)' } }, label: { show: true, color: '#666666', fontSize: 12, fontWeight: 400 }, emphasis: { // 鼠标移入动态的时候显示的默认样式 label: { show: true, color: '#FFFFFF', fontSize: 15, fontWeight: 600 }, itemStyle: { areaColor: 'rgba(102, 182, 255, 1)', borderColor: '#FFFFFF', borderWidth: 2 } }, layoutCenter: ['50%', '50%'], layoutSize: '150%', data: data } ] } const opt = Object.assign({}, defaultConfig, config) const { legend, tooltip, series, geo, grid } = opt const chartOpt = { grid, legend, tooltip, geo, series } return chartOpt } export default { getSimpleMap }

The custom pop-up window is mainly implemented in formatter of tooltip , customize the html pop-up window, and display the data to be displayed in params to the corresponding place and it is OK.

I personally like to implement the designed pop-up window style directly in pure html, and then copy it directly into formatter. Every time you encounter a different design, just modify the html in formatter and match the data to be displayed. It can be further encapsulated here. If you are interested, you can try it.

Page call

<chart-view
      class="map-view"
      :chart-option="mapOpt"
      height="100%"
      @click="handleMapClick" />
  • 1, :chart-option="mapOpt"This is passed to the encapsulated echarts map module Parameter, the interface data needs to be processed, see the next section for details
  • 2, @click="handleMapClick"Here is the data of the corresponding area when the map is clicked, used for the next step Operations, such as map drill-down

Interface data processing

initMap(url) {
    mapRequest(url).then((res) => {
        const mapData = res.data
        const jsonMap = { mark: this.mapName, json: mapData }

        const data = mapData.features.map((item) => {
          const { name, adcode } = item.properties

          let hoverObj = {}

          const objIndex = findElem(this.mapPopData, &#39;adcode&#39;, adcode)
          if (objIndex !== -1) {
            hoverObj = this.mapPopData[objIndex]
          } else {
            hoverObj = null
          }
          return {
            name,
            hoverObj: hoverObj
          }
        })
        this.mapOpt = this.$eChartFn.getSimpleMap(jsonMap, data)
    }).catch((err) => {
        console.log(err, &#39;加载地图失败&#39;)
    })
}

Here, the mapgeojson data and the interface return data are matched, and the pop-up data is corresponding Regional data effects.

MapgeojsonThe data must have the adcode field, so the interface data mapPopData is best to add this field for matching. hoverObj in the above code is the matched data of each area, and finally forms an array data. Pass parameters to the encapsulated echarts module through the following code

this.mapOpt = this.$eChartFn.getSimpleMap(jsonMap, data)

For specific code, please refer to the index.js file in the echartMapTest folder

Code Overview

The files involved are as follows (specific Reference Code):

|-- public
	|-- data
		|-- 4401.json
		|-- mapdata.json
	|-- images
		|-- map-ic.png
|-- src
	|-- api
		|-- map.js    // 获取地图geojson数据、地图弹窗接口模拟数据
    |-- components
        |-- chart
            |-- index.vue    // 图表单文件组件,供界面调用
            |-- index.js    // 实现自动化导入options里的图表option
            |-- options    // 存放各种图表的option
                |-- map    // 地图option
                    |-- index.js
    |-- views
        |-- echartMapTest    // 实例所在
            |-- index.vue
            |-- index.scss
            |-- index.js
	|-- utils
		|---utils.js
|-- main.js    // 全局引入echarts图表

代码

代码总览的目录去代码里找着看就行了。

  • https://github.com/liyoro/vue-skill

总结

以上,就是对echarts地图模块的封装,还有自定义弹窗的实现。使用和复用都比较方便了。

最近才发现 www.makeapie.com 停服了,挺好用的东西来的,感谢这么多年的奉献。

有需求的可转移到 PPChart,算是一个替代品了

(学习视频分享:vuejs教程web前端

The above is the detailed content of Detailed explanation of the method of elegantly encapsulating echarts map in vue2 project. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
What Happens When the Vue.js Virtual DOM Detects a Change?What Happens When the Vue.js Virtual DOM Detects a Change?May 14, 2025 am 12:12 AM

WhentheVue.jsVirtualDOMdetectsachange,itupdatestheVirtualDOM,diffsit,andappliesminimalchangestotherealDOM.ThisprocessensureshighperformancebyavoidingunnecessaryDOMmanipulations.

How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?May 13, 2025 pm 04:05 PM

Vue.js' VirtualDOM is both a mirror of the real DOM, and not exactly. 1. Create and update: Vue.js creates a VirtualDOM tree based on component definitions, and updates VirtualDOM first when the state changes. 2. Differences and patching: Comparison of old and new VirtualDOMs through diff operations, and apply only the minimum changes to the real DOM. 3. Efficiency: VirtualDOM allows batch updates, reduces direct DOM operations, and optimizes the rendering process. VirtualDOM is a strategic tool for Vue.js to optimize UI updates.

Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use