An opportunity to
Company to do a government domestic projects recently, due to the employees competitive superior conference (jing) is now (chui) good (niu) good (b) I say hope the future can be a big project, so the task of natural (demand came really fast) in my head, when I got the figure found a customized map element, is the three rivers in the graph below
If you want to use the GeoJSON method, you must know the coordinate system of the three rivers. However, UI said that the river given by the demand side is just a layer, she only pasted it on the map, and there is no coordinate data.
I need to render the map based on SVG. And add some extra elements.
Hence the article.
Pure when is a practice record.
Select the correct map component
Previously, our maps could only be drawn using GeoJSON format as the base map, but Echarts supports SVG as the base map in Geo and Map Series from the latest version 5.
- Geographic coordinate system (GEO) : The geographic coordinate system component. The geographic coordinate system component is used for map drawing, supporting the drawing of scatter diagrams and line sets in the geographic coordinate system.
- Map Series: maps are mainly used for the visualization of geographical data. Together with visualMap components, they are used to display data such as population distribution density of different regions.
The biggest difference between the geographic coordinate system and the map series is probably the drawing of scatter plots and line sets, which is written on the official website
If you want to visualize point data or line data, you can use scatter diagrams and line graphs on the geographic coordinate system components.
Of course, we learn Echarts can not eat API, naturally need to combine vivid examples, here is the official example of Paoding Cleu and scatter chart as the difference between the two, through the official configuration items we can see the configuration is different
series: [{
name: 'French Beef Cuts'.// The paoding man is equipped with a map series
type: 'map'.map: 'Beef_cuts_France'. }]Copy the code
geo: {
tooltip: {
show: true
},
map: 'iceland_svg'.// Scatter plots are mapped coordinates. },Copy the code
The visual difference is a scatter, and a scatter looks like this
Since our project required a lot of scatter points, we naturally chose the GEO component.
A named element
What is a named element? That is, named SVG elements.
If we want to interact with SVG elements, we need to mark them first, which is as simple as adding a name attribute to them. For example, if we take an SVG file and add the name attribute name=”named_rect” to the path, the path will be the named element.
The element with a name is very different from the element without a name. Once the element with a name is added, it can have interactive functions such as highlighting, fading in and out, text annotation, prompt box, etc., as examples, to send the official example
<svg xmlns="http://www.w3.org/2000/svg" version="1.2" fill-rule="evenodd" xml:space="preserve">
<path name="named_rect" d="M 0,0 L 0,100 100,100 100,0 Z" fill="# 765" />
<path d="M 150,0 L 150,100 250,100 250,0 Z" fill="# 567" />
</svg>
Copy the code
The rectangle on the left automatically has the hover effect because of the added name, while the rectangle on the right does not.
In addition, the named element with name can also be configured with geo. Regions in the Options of Echarts for a specific configuration effect, which will match our name.
Option = {geo: {map: 'some_svg', regions: [{name: 'element_name_1', itemStyle: {...}},}};Copy the code
Note:
- Only these SVG elements can be named:
rect
,circle
,line
,ellipse
,polygon
,polyline
,path
,text
,tspan
,g
. - Supports naming multiple elements with the same name so that they can be highlighted and selected at the same time.
Let’s start!
Next I will use slice as the base image, which UI exported to me via Figma.
Our goal is to use this file with Echarts to draw maps in the browser and do some simple interactions to familiarize ourselves with Echarts configuration items.
Add the named element to path
Once we have the SVG file, we need to open it with Chrome. The SVG opened with vscode is a string of XML tags that Chrome will parse (just like HTML) and render.
Each SVG vector file is essentially a graphic created from a number of defined lines and shapes. The most commonly used is probably the Path path tag, and it is the most powerful, allowing you to create various lines, curves, arcs, and so on.
To see the path of an area, open the F12 developer tool in a browser and point the small arrow at the rendered image
It is now clear that the entire base map is drawn with a large number of paths, the shape of which is defined by property D.
We don’t care how the D attribute is written, what we need to do now is to add the name attribute to the corresponding path in the SVG source file.
<path name=Zhaotong city d="M480.832..."
Copy the code
Basic usage
Then we need to use Echarts in the framework. Here we use React as the UI framework. Here is the basic structure
import React, { useEffect } from 'react'; import * as echarts from 'echarts'; import jQuery from 'jquery'; window.$ = jQuery; Export const Middle = () => {// Create Echarts const createMap = id => {}; useEffect(() => { createMap('map'); } []); return <div id='map' />; };Copy the code
We then use Echarts in the createMap function, where SVG is used as the base
const createMap = id= > {
const myChart = echarts.init(document.getElementById(id)!) ;//$.get() writes the path to your SVG file
$.get('/slice.svg'.function (svg) {
// First register an SVG string or parsed SVG DOM with echarts
echarts.registerMap('map', { svg: svg });
var option = {
toolTip: {},
// Start the geographic coordinate system component. The geographic coordinate system component is used for map drawing, supporting the drawing of scatter diagrams and line sets in the geographic coordinate system.
geo: {
map: 'map'.// Write the name of the registered map}}; myChart.setOption(option); }); };Copy the code
Now you can go ahead and browse and see what it looks like, and if anything happens, you can see something like this
Since I’m only adding a name to a path, this is the only element that will be highlighted as it moves.
Add text to the map
The hover effect above has a text effect, and there are two ways to add text
- Add text tags to SVG source files
- Echarts configured in
SVG source files are more basic, requiring us to write XML tags, such as this
<text xml:space="preserve" style="font-size:14px; font-style:normal; font-variant:normal; font-weight:bold; font-stretch:normal; text-align:center; text-anchor:middle; The fill: rgba (61215255 zhongguo kuangye daxue %); fill-opacity:1; stroke:none; font-family:DejaVu Sans; -inkscape-font-specification:Bitstream Vera Sans Bold" x="128.21919" y="112.48651" id="text3831" transform="The matrix (0.99999776, 0.00211681, 0.00211681, 0.99999776, 0, 0)">
<tspan sodipodi:role="line" x="550.59958" y="160.12965" id="tspan38351">Zhaotong city</tspan>
</text>
Copy the code
This is what I wrote in the SVG source file. The disadvantage is to find x and y points and write them in the corresponding X and Y attributes.
An easier way is to automatically add annotations using Echarts configuration options. Geo.
geo: {
map: 'map'.// Write the name of the registered map
// Text annotation configuration
label: {
show: true./ / show
color: 'rgba (61, 215, 255, 0.55)'./ / color}},Copy the code
The way I choose here is to write the text label in the source file, because I need to restore the design draft, the unified configuration cannot meet my requirements, the specific requirements are ok.
I added the name and text file here: map
Highlight emphasis
The default highlighting does not meet our requirements, so we can use emphasis to configure highlighting
geo: {
...
emphasis: {
focus: 'none'.// Focus on yourself when highlighted
itemStyle: {
areaColor: '#2080D7'.borderColor: '#2B91B7'.// The color of the map area.
borderWidth: 2.opacity: 1.shadowColor: 'rgba (74, 188, 251, 0.4)'.shadowBlur: 3.shadowOffsetX: 3.shadowOffsetY: 3,},label: {
show: false.// Text should not appear when highlighted}},},Copy the code
The specific configuration is in the official document of geo-. Emphasis
Now it looks like this
Regions User-defined pattern
If you want to set styles uniformly, you can use the geo. ItemStyle configuration
// Uniform style configuration
itemStyle: {
areaColor: '#1C3079'.borderColor: '#2ab8ff',},Copy the code
If you want to block custom configuration, you need to use the geo. Regions configuration item.
// Separate custom block Settings
regions: [{name: 'Zhaotong'.itemStyle: {
areaColor: 'rgba(44, 76, 187, 1)',}}, {name: 'Yuxi'.itemStyle: {
areaColor: 'rgba(44, 76, 187, 1)',}}, {name: Nujiang Lisu Ethnic Autonomous Prefecture.itemStyle: {
areaColor: 'rgba(44, 76, 187, 1)',}}, {name: 'Diqing Tibetan Autonomous Region'.itemStyle: {
areaColor: 'rgba(44, 76, 187, 1)',}}, {name: Chuxiong Yi Autonomous Prefecture.itemStyle: {
areaColor: 'rgba(16, 34, 84, 1)',}}, {name: Honghe Hani and Yi Autonomous Prefecture.itemStyle: {
areaColor: 'rgba(16, 34, 84, 1)',}}, {name: 'Lijiang City'.itemStyle: {
areaColor: 'rgba(16, 34, 84, 1)',}},],Copy the code
ItemStyle, geo-itemStyle, geo-.Emphasis. ItemStyle. They can customize the region style, global uniform style and highlight style respectively. You only need to query the parent configuration item.
Layout layout
If you want the entire map to fill the width and height of the div we set, you need to configure the following in Geo to fill the Echarts container.
layoutSize: '100%'.// Layout size
layoutCenter: ['50%'.'50%'].// Layout position
Copy the code
The series series
Series is the most important attribute in Echarts. It is indispensable for almost any chart configuration. With the Type attribute of Series, we can customize special effects such as broken line, bar, pie, scatter bubble, etc.
I need to use Series effectScatter and Series effectScatter in my project. The specific API can be checked through option. I will directly paste the code here
const mapData = [
{
name: 'Gushui Hydropower Station 1'.// Data name corresponding to option.tooltip.formatter
value: [190.215]./ / coordinates
},
{
name: 'Red Hydropower Station 8'.value: [366.260],}, {name: 'Red Water Power Station 9'.value: [436.270],}, {name: 'Red Hydropower Station 10'.value: [470.500],}, {name: 'Red Hydropower Station 11'.value: [520.310],},];Copy the code
var option = {
// Globally enable the prompt box style configuration, if configured here, there is a chance that all the following scatter graphs will not show the prompt box.
tooltip: {
show: true.// Open the global prompt dialog box
formatter: '{b}'.// Format, select display data name
backgroundColor: 'rgba (7, 26, 55, 0.8)'.borderColor: '#3DD7FF'.borderWidth: 1.padding: [3.5.3.5].textStyle: {
color: 'white',}},...series: [{// Scatter (bubble) diagram with ripple effects animation
type: 'effectScatter'.coordinateSystem: 'geo'.// The coordinate system used for this series
tooltip: {
show: false.// This series does not prompt the box
},
// Ripple effect configuration.
rippleEffect: {
brushType: 'stroke'.// The ripple is drawn stroke by stroke
scale: 4,},showEffectOn: 'render'.// Display the element 'Emphasis' when highlighted (hover) after drawing
symbol: 'circle'.// Mark graphics for ripple effects
symbolSize: [8.5].// Figure size, width and height
zlevel: 1./ / priority
// Graphic style
itemStyle: {
color: 'yellow',},// Array of data contents in series. Array items are usually concrete data items.
data: mapData.map(item= > item.value),
},
{
// Series type scatter (bubble) diagram.
type: 'scatter'.coordinateSystem: 'geo'.tooltip: {
show: true.// This series should prompt the box
},
symbol: 'pin'.emphasis: {
scale: true,},symbolSize: [30.33].symbolOffset: [0, -5].zlevel: 20.itemStyle: {
color: 'red',},data: mapData,
},
],
};
Copy the code
So that’s kind of how it works
Get coordinate axes
The value in mapData above represents the coordinate axis in this project (depending on the configuration of data, it can also be data), but we do not know what the coordinate axis is, if it is too time-consuming to try one by one, fortunately Echarts provides us with the API, we can listen for events to get coordinates
// Get the coordinates of the SVG base diagram
myChart.getZr().on('click'.function (params) {
var pixelPoint = [params.offsetX, params.offsetY];
var dataPoint = myChart.convertFromPixel({ geoIndex: 0 }, pixelPoint);
// When clicked on SVG, the coordinates will be printed.
// These coordinates can be used in 'series.data'.
console.log(dataPoint);
});
Copy the code
The event
If you want to operate on SVG elements, you can specify events
// 'name1' is the name of an SVG element.
myChart.on('click', { geoIndex: 0.name: 'name1' }, function (params) {
console.log(params);
});
Copy the code
If you want to bind a click event to a scatter graph in a series such as Scatter type, you can do this
myChart.on('click'.'series.scatter'.function (params: any) {
console.log(params);
});
Copy the code
Every project needs to adapt, so if you want Echarts map adaptation, you need to listen for the Window’s resize event and then call the Echarts instance’s resize method
window.addEventListener('resize'.() = >{ myChart? .resize(); });Copy the code
Currently, my project only needs these three event apis, and there are more customized events, which can be found in the documentation echarts-Event as required
conclusion
The above records are only a basic structure of the project and do not represent the final project quality. Based on the above structure, we have been able to make a wide variety of style effects and custom services on SVG maps.
If you feel that your own configuration is more troublesome, you can refer to the website Makeapie, find a case written by others, copy the configuration items.
Finally, I would like to promote the Github blog that I maintain for a long time
1. From learning to summary, record important knowledge points of the front-end, including in-depth Javascript, HTTP protocol, data structure and algorithm, browser principles, ES6, front-end skills, etc.
2. There is a directory in the README to find relevant knowledge points.
If it is helpful to you, welcome star and follow.
The address is here
Enjoy!!!!!