Introduction of Baidu Map (the first script is for the introduction of Baidu Map, the last two are required only when the custom information window is used, and the third infobox.js is available in the official document)

    <script src="Http://api.map.baidu.com/api?v=3.0&ak= put his AK" type="text/javascript"></script> <! -- Baidu Map Custom Information Window --><script src="//api.map.baidu.com/api?type=webgl&v=1.0&ak= put your AK" type="text/javascript"></script>
    <script src="static/InfoBox.js" type="text/javascript"></script>
Copy the code

The Dom part is simple, just a container, as follows

  <div class="map-box" ref="mapContainer">
  </div>
Copy the code

Data definition section (mainly map instance, others not required)

  data () {
    return {
      map: null.// Map instance
      projectIconList: [{id: 0.src: require('.. /.. /images/project-icon-blue.png')},
        {id: 1.src: require('.. /.. /images/project-icon-green.jpg')},
        {id: 2.src: require('.. /.. /images/project-icon-grey.jpg')},
        {id: 3.src: require('.. /.. /images/project-icon-orange.jpg')},].projectIcon: null./ / project icon
      airportIcon: require('.. /.. /images/airport-icon.png'), / / icon at the airport
      myProjectIcon: null.// Project annotation icon
      myAirportIcon: null.// Airport icon
      lastInfoBox: null.// Message window
      markerList: [].// All overlay arrays (easy to empty)
      zoomNum: null.// Map zoom level
    };
  },
Copy the code

Map initialization method (here added some map controls, do not need to remove)

    /* * Map initialization * */
    mapInit () {
      this.map = new BMap.Map(this.$refs.mapContainer); // Create a map instance
      this.map.centerAndZoom(new BMap.Point(116.404.39.915), 8); // Initialize the map, set the map center point with latitude and longitude, and set the map display level
      this.map.enableScrollWheelZoom(true); // Enable mouse wheel zooming
      this.map.addControl(new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_RIGHT })); // Add panning zoom control
      this.map.addControl(new BMap.ScaleControl({ offset: new BMap.Size(10.5)}));// Add a scale control
      // this.map.addControl(new BMap.OverviewMapControl()); // Add a thumbnail control
      this.map.addControl(new BMap.MapTypeControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT, offset: new BMap.Size(30.20)}));// Add map type controls (map, satellite, blend)
      this.map.setCurrentCity('Beijing'); // The switching function of MapTypeControl is available only when city information is set
Copy the code

Baidu coordinate conversion method (here is WGS-84 coordinates to Baidu)

    /** * baidu coordinates conversion method *@param X Longitude of coordinates to be converted *@param Y The coordinate dimension to be converted *@param TranslateCallback conversion method callback function * coordinate constants * COORDINATES_WGS84 = 1, WGS84 coordinates * COORDINATES_WGS84_MC = 2, WGS84 plane Mercator coordinates * COORDINATES_GCJ02 = 3, Coordinates of GCJ02 * COORDINATES_GCJ02_MC = 4, the plane Mercator coordinates of GCJ02 * COORDINATES_BD09 = 5, latitude and longitude coordinates of BD09 * COORDINATES_BD09_MC = 6, Baidu bd09 Mercator coordinates * COORDINATES_MAPBAR = 7, mapbar map coordinates * COORDINATES_51 = 8,51 map coordinates */
    transformCoordinate (x, y, translateCallback) {
      let originalPoint = new BMapGL.Point(x, y);
      let convertor = new BMapGL.Convertor();
      let pointArr = [];
      pointArr.push(originalPoint);
      convertor.translate(pointArr, COORDINATES_WGS84, COORDINATES_BD09, translateCallback);
    },
Copy the code

Calculate, stick original code directly, otherwise also still do not understand

<! -- * @Author : XuXing * @Date :  2021/04/16
* @Version : 1.0* @content: Project list page map --><template>
  <div class="map-box" ref="mapContainer">
  </div>
</template>

<script>
import airportLocation from '.. /.. /.. /static/airportLocation';

export default {
  name: 'projectList'.components: {},
  props: ['dataList'.'clickedProject'],
  data () {
    return {
      map: null.// Map instance
      projectIconList: [{id: 0.src: require('.. /.. /images/project-icon-blue.png')},
        {id: 1.src: require('.. /.. /images/project-icon-green.jpg')},
        {id: 2.src: require('.. /.. /images/project-icon-grey.jpg')},
        {id: 3.src: require('.. /.. /images/project-icon-orange.jpg')},].projectIcon: null./ / project icon
      airportIcon: require('.. /.. /images/airport-icon.png'), / / icon at the airport
      myProjectIcon: null.// Project annotation icon
      myAirportIcon: null.// Airport icon
      lastInfoBox: null.// Message window
      markerList: [].// All overlay arrays (easy to empty)
      zoomNum: null.// Map zoom level
    };
  },
  created () {
    window.goDetail = this.goDetail;// Resolve an invalid string template @click
    // this.$set(this.dataList);
  },
  mounted () {
    this.mapInit();
  },
  computed: {
    formatStatus () {
      return (value) = > {
        return value === 0 ? 'To begin' : value === 1 ? 'in progress' : value === 2 ? 'Done' : 'Deferred'; }; }},watch: {
    dataList: {
      handler (newValue, oldValue) {
        // console.log('mapnewValue:', newValue);
        if (this.dataList.length > 0 && this.zoomNum >= 9) {
          this.createProjectMarker(); }},immediate: true.deep: true}},methods: {
    /* * Map initialization * */
    mapInit () {
      this.map = new BMap.Map(this.$refs.mapContainer); // Create a map instance
      this.map.centerAndZoom(new BMap.Point(116.404.39.915), 8); // Initialize the map, set the map center point with latitude and longitude, and set the map display level
      this.map.enableScrollWheelZoom(true); // Enable mouse wheel zooming
      this.map.addControl(new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_RIGHT })); // Add panning zoom control
      this.map.addControl(new BMap.ScaleControl({ offset: new BMap.Size(10.5)}));// Add a scale control
      // this.map.addControl(new BMap.OverviewMapControl()); // Add a thumbnail control
      this.map.addControl(new BMap.MapTypeControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT, offset: new BMap.Size(30.20)}));// Add map type controls (map, satellite, blend)
      this.map.setCurrentCity('Beijing'); // The switching function of MapTypeControl is available only when city information is set
      this.myAirportIcon = new BMap.Icon(this.airportIcon, new BMap.Size(34.40)); // Airport icon
      this.createProjectMarker();
      // Listen to the map zoom level
      this.map.addEventListener('zoomend'.e= > {
        this.zoomNum = this.map.getZoom();
        // console.log('ZoomNum:', this.zoomNum);
        if (this.zoomNum < 5) { // When the zoom level is less than 5, it is not displayed
          this.remove(this.markerList);
          this.markerList = [];
        } else {
          this.createProjectMarker(); }}); },/** * baidu coordinates conversion method *@param X Longitude of coordinates to be converted *@param Y The coordinate dimension to be converted *@param TranslateCallback conversion method callback function * coordinate constants * COORDINATES_WGS84 = 1, WGS84 coordinates * COORDINATES_WGS84_MC = 2, WGS84 plane Mercator coordinates * COORDINATES_GCJ02 = 3, Coordinates of GCJ02 * COORDINATES_GCJ02_MC = 4, the plane Mercator coordinates of GCJ02 * COORDINATES_BD09 = 5, latitude and longitude coordinates of BD09 * COORDINATES_BD09_MC = 6, Baidu bd09 Mercator coordinates * COORDINATES_MAPBAR = 7, mapbar map coordinates * COORDINATES_51 = 8,51 map coordinates */
    transformCoordinate (x, y, translateCallback) {
      let originalPoint = new BMapGL.Point(x, y);
      let convertor = new BMapGL.Convertor();
      let pointArr = [];
      pointArr.push(originalPoint);
      convertor.translate(pointArr, COORDINATES_WGS84, COORDINATES_BD09, translateCallback);
    },
    /** * identifies the project */
    createProjectMarker () {
      this.remove(this.markerList);
      this.markerList = [];
      this.dataList.forEach(item= > {
        let translateCallback = (data) = > {
          if (data.status === 0) {
            this.createMarker(data.points[0], item); }};// For data reasons, here centerLatitude=> longitude, centerLongitude=> latitude
        this.transformCoordinate(item.defaultPosition.centerLatitude, item.defaultPosition.centerLongitude, translateCallback);
      });
    },
    /** * Project dot and create overlay *@param Point Baidu BD09 longitude and latitude coordinates *@param ProjectInfo Project information */
    createMarker (point, projectInfo) {
      // console.log(projectInfo);
      let pt = new BMap.Point(point.lng, point.lat);
      this.projectIcon = this.projectIconList.find(icon= > icon.id === projectInfo.status).src;
      this.myProjectIcon = new BMap.Icon(this.projectIcon, new BMap.Size(34.40)); // Project annotation icon
      let marker = new BMap.Marker(pt, { icon: this.myProjectIcon });
      this.markerList.push(marker);
      this.map.addOverlay(marker);
      let opts = {
        position: point, // Specify the geographic location of the text annotations
        offset: new BMap.Size(-10, -20) // Set the text offset
      };
      let label = new BMap.Label(projectInfo.project_name, opts); // Create a text annotation object
      label.setStyle({ / / label style
        color: '# 333333'.fontSize: '16px'.lineHeight: '20px'.border: 'none'.background: '#ffffff'.textStrokeWidth: '2px'./ / not to take effect
        textStrokeColor: '#FFFFFF'./ / not to take effect
        textShadow: '2px 2px 2px #FFFFFF; ' / / not to take effect
      });
      marker.setLabel(label); // Set the project name, set the overlay's text label
      let projectStatus = this.formatStatus(projectInfo.status);
      let arr = [projectInfo.id,projectInfo.project_name,projectInfo.tempId]; // The onClick object cannot be passed
      // Click annotation to open the custom information window
      marker.addEventListener('click'.() = > {
        let html = `<div style="cursor: default"> <div style="display: flex; justify-content: space-between"> <span style="font-size: 18px; font-family: Source Han Sans CN; color: #333333; line-height: 30px; cursor: pointer" onClick="goDetail('${arr}') ">${ projectInfo.project_name }</span> <div style="background: #367BF1; border-radius: 4px; padding: 6px 12px; text-align: center; color: #ffffff; font-size: 14px; Word-wrap: break-word! Important; "> </div> <div style="margin-top: 12px"> <p style="font-size: 14px; font-family: Source Han Sans CN; font-weight: 400; color: #666666;" > Project type:${ projectInfo.templateTypeName }</p> <p style="font-size: 14px; font-family: Source Han Sans CN; font-weight: 400; color: #666666;" > Project status:${ projectStatus }</p>
          </div>
        </div>`;
        let infoBox = new BMapLib.InfoBox(this.map, html, {
          boxStyle: {
            background: '#FFFFFF'.width: '300px'.height: '120px'.borderRadius: '4px'.boxShadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2).padding: '17px 11px'.zIndex: 999
          },
          enableAutoPan: false.// Whether to enable automatic panning
          align: INFOBOX_AT_TOP, // Based on which location to locate
          offset: new BMap.Size(0.30)});if (this.lastInfoBox) {
          // Determine if the previous form exists, if so execute close
          this.lastInfoBox.close();
          this.lastInfoBox = null;
        } else {
          infoBox.open(marker); // Open the info window
          this.lastInfoBox = infoBox; }}); },/** * Change the center of the map according to the selected item */
    changeCenter () {
      // Convert the callback function to the method
      let translateCallback = (data) = > {
        if (data.status === 0) {
          let pt = new BMap.Point(data.points[0].lng, data.points[0].lat);
          this.map.centerAndZoom(pt, 9); // Set the click point to the center point of the map, and set the map display level}};this.$nextTick(() = > {
        // For data reasons, here centerLatitude=> longitude, centerLongitude=> latitude
        this.transformCoordinate(this.clickedProject.defaultPosition.centerLatitude, this.clickedProject.defaultPosition.centerLongitude, translateCallback);
      });
    },
    /** * Empty the cover *@param List overlay array */
    remove (list) {
      if (list && list.length > 0) {
        [...list].every(x= > (!this.map.removeOverlay(x))); }},/** ** airport */
    createAirportMarker () {
      this.remove(this.markerList);
      this.markerList = [];
      airportLocation.forEach(item= > {
        // Convert the callback function to the method
        let translateCallback = (data) = > {
          if (data.status === 0) {
            let pt = new BMap.Point(data.points[0].lng, data.points[0].lat);
            let marker = new BMap.Marker(pt, { icon: this.myAirportIcon });
            this.markerList.push(marker);
            this.map.addOverlay(marker);
            let opts = {
              position: data.points[0].// Specify the geographic location of the text annotations
              offset: new BMap.Size(-33, -20) // Set the text offset
            };
            let label = new BMap.Label(item.name, opts); // Create a text annotation object
            label.setStyle({ / / label style
              color: '# 333333'.fontSize: '16px'.lineHeight: '20px'.border: 'none'.background: '#ffffff'}); marker.setLabel(label);// Set the project name, set the overlay's text label}};this.transformCoordinate(item.longitude, item.latitude, translateCallback);
      });
    },
    /** * Jump project details */
    goDetail(project) {
      setTimeout(() = > {
        this.$router.push({
          path: "projectEdit".query: {
            pid: project.split(', ') [0].pname: project.split(', ') [1].tempid: project.split(', ') [2]}}); },100); }}};</script>

<style lang="less" scoped>@deep: ~'>>>'; @import ".. /.. /styles/common"; .map-box { width: 100%; height: 100%; } @{deep}.BMap_cpyCtrl {display: none! important; } @{deep}.anchorBL { a { display: none ! important; }} /* Hide the 3d map button for the map type control */ @{deep}. AnchorBR {div:nth-child(3) {display: none! important; }}</style>

Copy the code