In the actual development process, it was found that autonavi map and Baidu Map could not use satellite images to view problems in villages and towns, so the world Map developed by the government was used. Write a xue record and make a contribution to the open source spirit.

The explanation function is

  1. Introduction to Map of Heaven and Earth
  2. Map rendering
  3. Adding map controls
  4. Locate user coordinates, draw city boundaries, and relocate latitude and longitude by moving punctuation marks
  5. Add multiple dots and click to pop up the information box

Map of heaven and Earth official link

The project was developed using VUE-CLI3 and VUE2

1. Introduce the skymap CDN in public-index. HTML

<! --index.html-->
<script type="text/javascript" src="Http://api.tianditu.gov.cn/api?v=4.0&tk= your key"></script>
Copy the code

Key The key is displayed after the application is successfully created

2. Render dome

<! Create dome -->
 <div id="mapDiv" style="position:absolute; width:100%; height:100%"></div>
Copy the code
  // Lifecycle - after the mount is complete (DOM elements can be accessed)
 mounted() {
   this.onLoad()
  },
  methods(){
   onLoad(){
    let that=this  // If the method is mounted, there will be a pointer problem
    let zoom = 12; // Map initialization level, and zoom scale
    that.map = new T.Map("mapDiv");
    that.map.centerAndZoom(new T.LngLat(116.40769.39.89945), zoom); // Map initialization center, this is the latitude and longitude of Beijing}}Copy the code

3, add map type controls

 var ctrl = new T.Control.MapType([
        {
          title: "Map".// The name of the layer to display on the map control
          icon: "http://api.tianditu.gov.cn/v4.0/image/map/maptype/vector.png".// The layer icon to display on the map control (default icon size 80x80)
          layer: TMAP_NORMAL_MAP // MapType object, i.e. MapType.
        },
        {
          title: "Satellite hybrid".icon:
            "http://api.tianditu.gov.cn/v4.0/image/map/maptype/satellitepoi.png".layer: TMAP_HYBRID_MAP
        }
      ]);
       that.map.addControl(ctrl);
Copy the code

I have only added two types of satellites, for more types you can see the official documentation.

It is worth noting that the official documentation provides a wrong format of the code, can not be directly copied down to use

4. Locate user coordinates, draw city boundaries, and relocate latitude and longitude by moving punctuation marks

<! -- Add click button -->
 <button
    style="position: absolute; z-index: 500; border: 1px solid; right: 7%; bottom: 10%; color: red; background: green; padding: 10px;"
      @click="positionBtn"
    >Locate the coordinate</button>
Copy the code
  data() {
    // Where to store data
    return {
        cityName:""  // Save city name temporarily
    };
  },
  positionBtn() {
        let that =this
      // this.map.clearOverLays(); // Clean up the coverings on the map
      let lc = new T.LocalCity();  // Create an instance to get the location of the local city
      lc.location(function(e) {  // Locate using the IP address
        alert(e.cityName);
        let marker = new T.Marker(e.lnglat);  // e.lenglat, annotate the geographic coordinates of the points
        that.map.addOverLay(marker);  //addOverLay method to add a overlay to the map. An instance of a overlay can only be added once to the map.
        that.getMap(); // Create a map object

        marker.addEventListener("dragend", overlay_style); // Add an event listener.
        marker.enableDragging(); // Enable annotation drag and drop

        function overlay_style(e) {
          let p = e.target;
          alert(
            "The latitude and longitude of this region are:" + p.getLngLat().lng + ","+ p.getLngLat().lat ); }}); }, getMap() {let that= this
      // Create an object
      let administrative = new T.AdministrativeDivision(); // Create an instance to get the administrative division
      let config = {
        needSubInfo: false.// Whether the next-level information is required
        needAll: false.// Whether all child nodes are required.
        needPolygon: true.// Whether the administrative scope is required.
        needPre: true.// Whether all the information of the previous level is required.
        searchType: 1.// Query type. 0 indicates the query by code, and 1 indicates the query by name.
        searchWord: this.cityName// Query the name of the administrative division.
      };
      administrative.search(config, searchResult);// Method: initiate a search based on the search term, searchResult: callback parameter
      function searchResult(result) {
        if (result.getStatus() == 100) {
          let data = result.getData();
          that.showMsg(data);
        } else{ result.getMsg(); }}/ / specific content see AdministrativeDivisionResult class.
    },
    showMsg(data) {
      for (let i = 0; i < data.length; i++) {
        // Explain the superior administrative divisions
        if (data[i].parents) {
          let upLevel = "";
          if (data[i].parents.country) {
            upLevel += data[i].parents.country.name;
          }
          if(data[i].parents.province) { upLevel += data[i].parents.province.name; }}if (data[i].points) {
          // Draw administrative divisions
          this.polygon(data[i].points);
        }

        // Explain the lower administrative divisions
        if (data[i].child) {
          showMsg(data[i].child);
          console.log(data[i].child.points);
          if (data[i].child.points) {
            // Draw administrative divisions
            this.polygon(data[i].child.points);
          }
        }
      }
    },

    polygon(points) {
        let that=this
      let pointsArr = [];
      for (let i = 0; i < points.length; i++) {
        let regionLngLats = [];
        let regionArr = points[i].region.split(",");
        for (let m = 0; m < regionArr.length; m++) {
          let lnglatArr = regionArr[m].split("");
          let lnglat = new T.LngLat(lnglatArr[0], lnglatArr[1]);
          regionLngLats.push(lnglat);
          pointsArr.push(lnglat);
        }
        // Create a plane object, style
        let polygon = new T.Polygon(regionLngLats, {
          color: "#fd737a".weight: 3.opacity: 1.fillColor: "#FFFFFF".// Fill the color.
          fillOpacity: 0.3 // Fill transparency
        });
        // Add administrative planes to the map
        that.map.addOverLay(polygon);
      }
      // Display the best scale
      that.map.setViewport(pointsArr);
      alert(
        "Current map center point:" +
          that.map.getCenter().getLng() +
          "," +
          that.map.getCenter().getLat()
      );
    },
Copy the code

5, add multiple points, and click the pop-up information box

<! -- Add click button -->
  <button
      style="position: absolute; z-index: 500; border: 1px solid; right: 7%; bottom: 5%; color: red; background: green; padding: 10px;"
      @click="pointsBtn"
    >Add multiple points</button>
Copy the code
pointsBtn() {
        let that=this
      let data_info = [
        [
          116.417854.39.921988.Address: 8th Floor, Lotte Intime Department Store, No. 88, Wangfujing Street, Dongcheng District, Beijing
        ],
        [116.406605.39.921585.Address: Donghuamen Street, Dongcheng District, Beijing],
        [116.412222.39.912345.Address: No. 5, Zhengyi Road, Dongcheng District, Beijing]].for (let i = 0; i < data_info.length; i++) {
        let marker = new T.Marker(
          new T.LngLat(data_info[i][0], data_info[i][1]));// Create the annotation
        let content = data_info[i][2];
        that.map.addOverLay(marker); // Add annotations to the map
        that.addClickHandler(content, marker);
      }
     
   
    },
 addClickHandler(content, marker) {
        marker.addEventListener("click".function(e) {
          that.openInfo(content, e);
        });
      },
 openInfo(content, e) {
        let point = e.lnglat;
        that.marker = new T.Marker(point); // Create the annotation
        let markerInfoWin = new T.InfoWindow(content, {
          offset: new T.Point(0.- 30)});// Create an information window object
        that.map.openInfoWindow(markerInfoWin, point); // Open the info window
      },
Copy the code

Using a custom info-box involves using the ternary operator, which can be used to convert numbers to corresponding characters. Remember to enclose the ternary operator (), otherwise the previous HTML will not render

conclusion

The article that writes heaven and earth map on the net is quite little, in fact as long as stepped over pit or very good use. If you feel useful, you can invite me to drink a cup of milk tea to encourage you.