A sharing meeting of front end “unveiling the mystery of mapping”

Time:2020-10-31

A sharing meeting of front end “unveiling the mystery of mapping”

Record my technology sharing in the group, students with the same needs can refer to it
The whole sharing time is about 70 minutes

A sharing meeting of front end

1、 Why share front end related “map” knowledge

  1. (large screen display) many companies have corresponding large screen display systems, such as customer and asset distribution map in China or around the world
  2. (vividly depicted) showing geographical relations from the perspective of maps, which makes people look more intuitive than simple words
  3. For example, this year’s distribution map of various kinds of epidemic situation
  4. Generally speaking, it still looks cool and can improve a little bit of b-grid, and this is only a front-end category, so we need to understand it

2、 Brief introduction of map related technology

Here I only introduce a few of my commonly used

**Baidu map
This is famous, has many functions and now supports 3D very well. Note that GL v1.0 is a little different from the previous v2.0 map API. Don’t drop it
The disadvantages are obvious, for example, if you want a clean map, there is no shop on it and there is no logo, I suggest you use echards to play, because Baidu map has more things
Want to use Baidu map students can see here, super simple can complete registration with play
It’s very easy to use

** hcharts
Very cow, very easy to use, but its part of the function is to charge, before using to let the company to help you buy the corresponding function can be used for business oh
Because our company map library is our own research and development, there is no such online payment
Detailed address

** echarts
No one knows the front end of the library. It is recommended to use this technology when the requirements are very simple. Echards has been introduced when drawing bar charts or line charts in projects. At this time, there is no need to repeat references to save space
Maps drawn by echarts

**Our company’s own 2D, 3D map component library
I won’t introduce this in detail here. Some companies will also have independently developed map components. The design idea may be different from the above three. I will talk about it later

3、 Basic map of echarts

Take echarts, for example, because this is the best way to make

I built a new Vue project here

<template>
  <div class="home">
    <div id="map"></div>
  </div>
</template>

<script>
import echarts from "echarts";
import mapData from "./geo";

export default {
  name: "Home",
  data() {
    return {
      myChart: null,
    };
  },
  methods: {
    initMap() {
      this.myChart = echarts.init(document.getElementById("map"));
      echarts.registerMap ("world", MapData); // use it below the definition name. The advantage of this is that it can easily switch maps
      this.myChart.setOption({
        series: [
          {
            type: "map",
            Maptype: "world", // custom extended chart type
            label: {
              show: false,
            },
          },
        ],
      });
    },
  },
  mounted() {
    this.initMap();
  }
};
</script>
  1. Initialize as we usually use echards
  2. It’s a little different nextecharts.registerMap("world", mapData);It can be understood that this data is named ‘world’ to facilitate future switching (I will talk about the data here below)
  3. In option configuration, set the type as map, and use the ‘world’ type defined above

design sketch
A sharing meeting of front end

We can see that there is nothing special about the drawing of maps. The most important thing is thatmapDataData, this data is generally called geojson data, so let’s get to know it

4、 What exactly is geojson data

  1. Geojson is to express and store geographic data in JSON syntax, which can be said to be a subset of JSON. It is not specifically used by JS. This should be clear
  2. There are mountains, rivers, oceans and other geographic information on the map, so how to describe a river? At this time, we need to use geojson format file to describe
  3. It’s not necessary to use geojson. Geojson is just a set of specifications. Major parsers use this set of specifications to parse and generate corresponding scenes. We can develop our own specifications to achieve these. It’s just that we need to write and draw our own parsers because of poor compatibility

5、 Geojson in detail

English is good, you can browse the website first
1. Basic structure

{// can include points, lines, surfaces, a large set
  "Type": "featurecollection", // defines that this is a geojson file, and other values can also be found here, which will be described below
  "Features": [] // put the data to be drawn here
}

We’ll see later"type": "FeatureCollection"This line indicates that the file is a geojson specification file

2. Describe a feature
Spot data on the map

{
  "type": "FeatureCollection",
  "features": [
    {
      "Type": "feature" // indicates that the object is an element
      "Properties": {}, // style is put here, and I will talk about it later
      "Geometry": {// this contains specific data
        "Type": "point" // refers to drawing points
        "Coordinates": [105.380859375, 31.57853542647338] // the default values are longitude and latitude. If it is three-dimensional, it is XYZ. Of course, it is not necessarily the latitude and longitude (different coordinate systems) that will explain why
      }
    },
  ]
}

3. Describe multiple points (featurecollection)
**Advantages

  1. The writing is concise
  2. These point styles can be shared
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "Type": "multipoint", // multipoint, that is, to draw multiple points in succession
        "coordinates": [[105.380859375, 31.57853542647338],
        [105.580859375, 31.52853542647338]
        ]
      }
    },
  ]
}

4. Describe a line string

  1. Each point is still depicted here, but the points are joined together to form a line
  2. Connection data on map
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "Type": "linestring", // where all the points are connected together to form a line
        "coordinates": [[105.6005859375, 30.65681556429287],
        [107.95166015624999, 31.98944183792288],
        [109.3798828125, 30.031055426540206],
        [107.7978515625, 29.935895213372444]]
      }
    },
  ]
}

5. Describe multilinestring

  1. Here the second group and the first group of lines, can be separated, not end to end
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "MultiLineString",
        "coordinates":
          [
            [
              [105.6005859375, 30.65681556429287],
              [107.95166015624999, 31.98944183792288],
              [109.3798828125, 30.031055426540206],
              [107.7978515625, 29.935895213372444]
            ],
            [
              [109.3798828125, 30.031055426540206],
              [107.1978515625, 31.235895213372444]
            ]
          ]
      }
    },
  ]
}

6. Describe a polygon

  1. The first point must be the same as the last point, so that the closed loop can be completed!!
  2. The format of 3D array needs attention
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "Type": "polygon", // note that this is a three-dimensional array
        "coordinates": [
          [
            [106.10595703125, 33.33970700424026],
            [106.32568359375, 32.41706632846282],
            [108.03955078125, 32.2313896627376],
            [108.25927734375, 33.15594830078649],
            [106.10595703125, 33.33970700424026]
          ]
        ]
      }
    },
  ]
}

7. there are multiple faces in one face

  1. In this way, we can describe the shape of a single circle in a polygon map
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [
              -39.7265625,
              -3.162455530237848
            ],
            [
              127.96875,
              -3.162455530237848
            ],
            [
              127.96875,
              74.1160468394894
            ],
            [
              -39.7265625,
              74.1160468394894
            ],
            [
              -39.7265625,
              -3.162455530237848
            ]
          ],
          [
            [
              -22.5,
              15.961329081596647
            ],
            [
              110.74218749999999,
              15.961329081596647
            ],
            [
              110.74218749999999,
              70.8446726342528
            ],
            [
              -22.5,
              70.8446726342528
            ],
            [
              -22.5,
              15.961329081596647
            ]
          ]
        ]
      }
    }
  ]
}

The results are as follows:
A sharing meeting of front end

8. Describe multiple faces
Advantages:

  1. The writing is concise
  2. These point styles can be shared
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "MultiPolygon",
        "coordinates": [
          [
          [
            [
              -39.7265625,
              -3.162455530237848
            ],
            [
              127.96875,
              -3.162455530237848
            ],
            [
              127.96875,
              74.1160468394894
            ],
            [
              -39.7265625,
              74.1160468394894
            ],
            [
              -39.7265625,
              -3.162455530237848
            ]
          ]
        ],
        [
          [
            [
              -22.5,
              15.961329081596647
            ],
            [
              110.74218749999999,
              15.961329081596647
            ],
            [
              110.74218749999999,
              70.8446726342528
            ],
            [
              -22.5,
              70.8446726342528
            ],
            [
              -22.5,
              15.961329081596647
            ]
          ]
        ]
        ]
      }
    }
  ]
}

Here, if it overlaps, it means the color is superimposed, as shown in the figure:
A sharing meeting of front end

9. Describe a group

  1. For example, in order to represent a specific landform, we can separate the geomorphic data
{
  "type": "FeatureCollection",
  "features": [
    {// can include points, lines, surfaces, a separate set
      "type": "GeometryCollection",
      "geometries": [
        {
          "type": "Point",
          "coordinates": [108.62, 31.02819]
        }, {
          "type": "LineString",
          "coordinates": [[108.896484375, 30.1071178870],
          [108.2184375, 30.91717870],
          [109.5184375, 31.2175780]]
        }
      ]
    }
  ]
 }

10. Different styles (properties)

{
  "type": "FeatureCollection",
  "features": [
     {
      "type": "Feature",
      "Properties": {// special properties
        "Stroke": "#fa9661", // outside color
        "Stroke width": 4.1, // outside width
        "Stroke opacity": 0.7, // outer transparency
        "Fill": "ා9e290c", // fill color
        "Fill opacity": 0.7 // fill color transparency
      },
      "geometry": {
        "Type": "point", // draw point
        "coordinates": [105.380859375, 31.57853542647338]
      }
    },
  ]
}

6、 Geojson related websites and tools

**To show the dry data, you can’t look hard. Here I recommend a great website to draw geojsonaddress

So let me introduce how to use this website to generate efficiently and debug geojson
A sharing meeting of front end

  1. That is, the final generated geojson, the changes here can affect the image in real time, and there will be error prompt, which is very convenient to write
  2. draw a straight line
  3. Draw a polygon, that is, faces. Pay attention to the first connection
  4. Draw rectangle, here should be a special encapsulation method to draw rectangle
  5. Draw points, here will mark for us on the map, the specific pictures need to be quoted in the project

A sharing meeting of front end

  1. Click to enter the edit mode, the mouse will appear the small hand mark on the graph, then you can drag the graph to move, the operation can choose whether to keep or not
  2. Delete mode, click to delete the specified figure, operation can choose whether to keep

A sharing meeting of front end
Click the graph to display the operation box as shown in the figure

  1. Add style properties. The current style properties are shown above
  2. Save your changes
  3. Delete this graphic

A sharing meeting of front end

  1. Click open to use the local geojson file to import and draw
  2. Under save, click geojson to download the generated code file to local

7、 The idea of self-made geojson analysis and drawing tool

  1. We can only do a converter, that is, you can write whatever you think is good, and finally convert it to geojson format
  2. Draw graphics directly in your favorite format
  3. If you use canvas to implement, it is better to draw the corresponding graph, that is, graphics overlay needs special processing, and the style directly reads the data in properties for setting
  4. Drawing latitude and longitude is also a problem, after all, it is not easy to calculate latitude and longitude on the plane
  5. So to sum up, it seems that it is not so difficult to draw a flat map. As long as the data is correct, half of the success will be achieved

8、 Basic concept of map (tile map, vector map)

**Have you found that when the map we use is zoomed in, the area is a block, a block is loaded into the image
**If you open the network of the console, you can see a lot of PNG requests
**How to quickly render the huge data and details of map?
**The following are two main map drawing modes

Grid Tile Map

As the name suggests, the picture is like a tile stacked grid into a map, a bit like a puzzle, is not it a bit tall
But there are many problems to be solved. For example, if you look at the map from the perspective of overlooking the world, the tile image of the world will appear. When the height is less than a certain value, another set of tiles will be used. In a certain height range, the method of magnifying tile image is used to simulate the decline of visual field, Every request for tile image needs to pass: 1: the coordinates of the current view (latitude and longitude); 2: the width and height of the current view; 3: the height of the current viewing angle

Grid tiles with 256256 or 512512 size images are used as media. This technology usually renders the images in advance on the server. The front-end loads images according to the scale level of the map to splice them. At present, it is still used on a large scale, but there are some disadvantages in this way

Due to the impact of network bandwidth overhead and storage space constraints, offline deployment costs are high, and a single set of topics is nearly 500 g (China).
It takes a long time to render after editing the style.
There is no 3D building data and no height information in 3D scene.
Data confidentiality is poor.

Vector map

As the name suggests, it is a vector drawing graphics, as long as it is not a photo, it will be much smaller. For the reason why the vector is light and not distorted, we can refer to the sharing of SVG in the last articleSvg practice

Vector tiles adopt the same hierarchical cutting scheme as grid tiles. The difference is that tile data transfers geographic data, including roads, land, buildings, etc. by rendering maps in the front end, it has the following advantages:

It takes less server space, reduces network overhead, and only 5g space is needed for localization deployment (China).
It is easy to change the base map style
Because of the geographic data itself, we can extend the 3D space based on the data, such as 3D architecture.
Data confidentiality is strong.

9、 Different coordinate systems

**The earth itself is an ellipsoid, it is really difficult to draw it on a rectangle in a plane way. Now there are many drawing methods, but each has its own advantages and disadvantages. Interested friends can check the specific details. I will briefly introduce the more common ways

  1. Latitude and longitude EPSG: 4326, which is the default coordinates of the map
    Now define the latitude and longitude on the sphere, and then draw the scale on the square paper, and draw the corresponding
  2. Mercator projection (EPSG: 3785)
    Put the earth in a cylinder. If there is a light source inside the earth, then the projection of the earth on the cylinder is the map
  3. Mars coordinate system

Mars coordinates are the coordinates obtained by the National Bureau of Surveying and mapping on the basis of the original coordinates for national security. The basic domestic electronic maps and navigation equipment are obtained by using this coordinate system or secondary encryption based on this coordinate system.
The real name of Mars coordinates should be gcj-02 coordinates. Basically, all domestic electronic maps adopt Mars coordinate system, and even Google Map China part has made a special offset for the Chinese government.

  1. Baidu coordinate system

The Mars coordinates are encrypted on the international standard coordinate WGS-84. Since domestic electronic maps should be encrypted at least once with Mars coordinates, baidu is more willful, and directly studies a set of encryption algorithm, and comes to a secondary encryption. This is the baidu coordinate bd-09 as we know it. Of course, only Baidu map uses Baidu coordinates

  1. WGS-84 coordinate system

Gs-84 coordinate is an international standard, which is used in satellite navigation and original GPS equipment. Foreign Google map, OpenStreetMap, mapbox, openlayer and so on use this coordinate.

Geojson sets the coordinate system
Because of the different coordinate systems, even if a point is drawn, the coordinates will not be exactly the same, so we need to tell the geojson users which coordinate system to analyze

{
  "type": "FeatureCollection",
  "CRS": {// define the coordinate system (the coordinate system that uses longitude and latitude if not written) is the default EPSG:4326 。
    "Type": "name", // type "and" properties ". For compulsory ownership
    "properties": {
      "Name": "urn: OGC: def: CRS: EPSG: 54013" // specific rules are defined here
    }
  },
  "features": [
     {},
  ]
}

Use online rules

{
  "type": "FeatureCollection",
  "crs": {
    "Type": "link", // here it becomes link
    "properties": {
      "href": " http://example.com/crs/42 ", // here is the resource link you set
      "Type": "proj4" // proj4 "," ogcwkt ", esriwkt" can only be in these three formats
    }
  },
  "features": [
     {},
  ]
}

10、 Faster front end data – > Web assembly

**Web assembly is a new encoding method, which has smaller file size, faster startup speed and faster running speed. Compared with the web application built by JavaScript, the performance is improved significantly. It is the compiler target of many programming languages, including C + +, C, rust, etc.
Web assembly is a new specification developed by W3C community group composed of mainstream browser manufacturers. * *

Web assembly can obviously improve the speed of calculation, and it is suitable for map library

  1. The combination of web assembly and JavaScript will not replace JS in a short time
  2. . wasm file at the end of the file
  3. Web assembly has a complete set of semantics. In fact, wasm is a small size and fast loading binary format. Its goal is to give full play to the hardware capabilities to achieve native execution efficiency
    Web assembly runs in a sandboxed execution environment, and can even be implemented in existing JavaScript virtual machines. In the web environment, web assembly will strictly abide by the same origin policy and browser security policy.
    A web assembly is used to optimize, test, test or program. You can view the source code of the wasm module on a web page in this text format.
    Web assembly is designed to be versionless, feature testable and backward compatible in the web. Web assembly can be called by JavaScript, enter the JavaScript context, or call browser functions like web API. Of course, web assembly can run not only on browsers, but also in non web environments.
  4. Parsing – decoding a web assembly is faster than parsing JavaScript

Compile and optimize – it takes less time to compile and optimize because more optimizations have been done before the file is pushed to the server, and JavaScript needs to compile code multiple times for dynamic types
Re optimization – the web assembly code does not need to be re optimized because the compiler has enough information to get the correct code the first time it runs
Execution – execution can be faster, and web assembly instructions are closer to machine code
Garbage collection – at present, webassembly does not directly support garbage collection. Garbage collection is controlled manually, so it is more efficient than automatic garbage collection. MVP (minimizing viable products) in browsers is fast. In the next few years, with the development of browsers and the increase of new features, it will become faster in the next few years.

Now that these are concepts, let’s go

11、 Hello level web assembly

Chinese official website
The implementation of the official website also needs to configure the environment, which is very formal. In fact, we want to have a taste of it at the entry level. As long as you can click C + + you can use my next method to realize it

Online generation
Online generation

A sharing meeting of front end

  1. Click to convert C + + code to web assembly format
  2. Click to download the converted file
  3. It’s a binary file

References

fetch("/test.wasm")
      .then((res) =>  res.arrayBuffer ()) // get the buffer format
      .then((bytes) =>  WebAssembly.compile (bytes)) // to bytecode
      .then((mod) => {
        const instance = new WebAssembly.Instance(mod);
        const exp = instance.exports;
        console.log(exp._Z7showNumv())
      });
  1. exp._ Z7shownumv instead of exp.showNum We can modify this in the “wat” column, but it is not easy to modify with more code. There should be an option to prohibit changing the name during conversion. Here we just expand it
  2. Note that there will be cross domain, because it belongs to the file protocol, you can start a service locally

development cost

  1. It’s not just front-end technology that’s needed
  2. There are a little more bugs, such as not easy to debug, and some students encounter problems such as different compilation results
  3. Imperfect community
  4. It is suggested that this technology should be used in modules with high encapsulation and large amount of computation

12、 I write the code of 2D and 3D project

Here, I will show the code structure and problems of the two projects I have written in the group. After all, it involves security issues. But the general idea is to divide the map into several levels: world, country, province, city and district (province and urban area is China’s classification method), which is equivalent to a state machine, and then do corresponding things in each state, such as dotting and connecting, Each time the layer state is changed, other layers will be hidden to show the corresponding field of view

end.

Map is also a useful part of the front-end. I just got involved in map related projects this year, but after learning geojson and other knowledge in detail, it will be very smooth to use map related component library
This is it this time. I hope to make progress with you