This article is intended only to document my use of Amap


Introduction of depend on

In public/index.html

<script type="text/javascript"
      src="Https://webapi.amap.com/maps?v=2.0&key= * * * * * * * * * gold key of the map *********&plugin=Amap.Geocoder,AMap.GeoJSON,AMap.MarkerClusterer,AMap.Autocomplete,Map3D,AMap.DistrictSearch,AMap.Distri ctLayer,AMap.PolylineEditor">
</script>
<script src="https://webapi.amap.com/ui/1.1/main.js"></script>
<script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
Copy the code

Modify the configuration

Modify the configuration in vue.config.js

// Amap
configureWebpack(config) {
  config.externals = {
    'AMap': 'AMap' // Amap configuration
  };
},
Copy the code

Render map of Gaud on the page

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

<script>
import AMap from 'AMap';
import echarts from 'echarts';
import { getAlarmMarkerContent } from './mapUtil';
import { getPieOption } from './echart.pie.config';
import { screenApi } from '@/common/request/api.js'

export default {
  data() {
    return {
      warnIcon: require('@/assets/image/map-warn-icon.png'), / / warning icon
      fenceIcon: require('@/assets/image/icon-fence.png'), / / lock icon
      monitorIcon: require('@/assets/image/icon-monitor.png'), / / monitor icon
      brendIcon: require('@/assets/image/icon-brend.png'), // Inducible screen icon
      map: null.timer: null.colorList: ['#F8E71C'.'#EB646A'.'#50E3C2'.'#4A90E2'.'#4D63EE'].// Five imaginary line strokes are randomly selected
      colorCurIndex: 0.// The current position of dotted line stroke color
      allMarker: [].// All warning maker points
      polylineList: [].// All road lines
      parkingSpaceMarker: [].// Parking saturation pie map marker
      parkingNameMarker: [].// Parking lot name marker}},mounted() {
    this.MapInit(); // Initialize the map
    this.getParkingPosxy(); // Draw the parking lot boundary
    this.getAlarmList(); // Warning point (device fault marker)
    this.getRoadLine(); // Get the road segment
    this.parkingSpaceChart(); // Get parking saturation (pie chart)
    
    this.timer = setInterval(this.parkingSpaceChart, 10000); // The parking lot saturation is refreshed every 10 seconds
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
  	// Instantiate amap
    MapInit() {
      this.map = new AMap.Map("map", {
        center: [113.348489.23.006061].mapStyle: "amap://styles/3f5a24469182216607b4d03abc5c3efe".// Set the map display style, here is the UI design style key
        resizeEnable: true.zoom: 16.draggable: true.showLabel: true}); },// Interface: get parking boundary (map area)
    async getParkingPosxy() {
      const res = await screenApi.parkingPosxy();
      const allParkingPosxyList = res.data || [];
      allParkingPosxyList.forEach(item= > {
        const posxy = item.posxy || [];
        this.addArea(posxy); // Draw boundaries
      })
      this.dragParkingName(allParkingPosxyList); // Draw the parking lot name marker
    },
    // interface: get device alarm list (map point)
    async getAlarmList() {
      const res = await screenApi.getAlarmList();
      const alarmList = res.data || [];
      if(!Array.isArray(alarmList) || alarmList.length <= 0) return;
      this.dragMapAlarmMarker(alarmList); // Draw equipment alarm point
    },
    // Interface: get road segment (vector map)
    async getRoadLine() {
      const res = await screenApi.roadPosxy();
      const roadLineList = res.data || [];
      if(!Array.isArray(roadLineList) || roadLineList.length <= 0) return;
      this.dragMapRoadLine(roadLineList); // Create a road map
    },
    // Get parking saturation (pie chart)
    async parkingSpaceChart() {
      const res = await screenApi.parkingSpaceChart();
      const parkingList = res.data || [];
      if(!Array.isArray(parkingList) || parkingList.length <= 0) return;
      this.dragMapParkingPie(parkingList); // Draw a parking saturation pie chart
    },
    // Line (region)
    addArea(posxy) {
      if(! posxy || !Array.isArray(posxy) || posxy.length <= 0) return;
      var path = [];
      posxy.forEach(item= > {
        path.push(new AMap.LngLat(item.x, item.y))
      })
      const polygon = new AMap.Polygon({
        path: path,  
        fillColor: this.colorList[this.colorCurIndex], // Polygon fill color
        fillOpacity: 0.2.// Polygon fill transparency. The value ranges from 0 to 1, where 0 indicates full transparency and 1 indicates opacity. The default is 0.9
        borderWeight: 2.// Line width, default is 1
        strokeColor: this.colorList[this.colorCurIndex], // Line color
        strokeStyle: 'dashed'.// Outline style, solid line :solid, dashed line :dashed line
      });
      this.map.add(polygon);
      this.colorCurIndex = this.colorCurIndex + 1;
      if(this.colorCurIndex > 4) this.colorCurIndex = 0;
    },
    // Draw the parking lot name marker
    dragParkingName(parkList) {
      this.map.remove(this.parkingNameMarker)
      this.parkingNameMarker= []
      this.colorCurIndex = 0;
      parkList.forEach(item= > {
        var marker = new AMap.Marker({
          position: new AMap.LngLat(item.longitude, item.latitude),
          offset: new AMap.Pixel(-70, -15),
          content: `<div style="color: The ${this.colorList[this.colorCurIndex]}; font-size: 20px; width: 120px;" >${item.parkingName}</div>`
        });
        this.parkingNameMarker.push(marker)
        this.colorCurIndex = this.colorCurIndex + 1;
        if(this.colorCurIndex > 4) this.colorCurIndex = 0;
      })
      this.map.add(this.parkingNameMarker);
    },
    // Draw equipment alarm point
    dragMapAlarmMarker(alarmList) {
      this.map.remove(this.allMarker)
      this.allMarker= []
      alarmList.forEach(item= > {
        // Device type 0: fusioncube, 1: video surveillance device, 2: loop traffic bayonet device, 3: Bluetooth device, 4: server, 5: boot screen,
        // 6: switch, 7: channel gate, 8: berth sensing device, 9: broadcast device, 10: virtual bayonet device, 11 alarm button device
        let imgIcon = ' '
        switch(item.equipmentType) {
          case '1': imgIcon = this.monitorIcon; break; // 1: video surveillance device
          case '5': imgIcon = this.brendIcon; break; // 5: boot screen
          case '7': imgIcon = this.fenceIcon; break; // 7: switch
        }
        const content = getAlarmMarkerContent(this.warnIcon, imgIcon)
        var marker = new AMap.Marker({
          position: new AMap.LngLat(item.longitude, item.latitude),
          offset: new AMap.Pixel(-15, -15),
          content: content
        });
        this.allMarker.push(marker)
      })
      this.map.add(this.allMarker);
    },
    // Create a road map
    dragMapRoadLine(roadLineList) {
      this.map.remove(this.polylineList);
      this.polylineList = [];
      roadLineList.forEach(item= > {
        if(!Array.isArray(item.posxy)) return;
        const path = [];
        item.posxy.forEach(posxy= > path.push(new AMap.LngLat(posxy.x, posxy.y)))
        const polyline = new AMap.Polyline({
          path: path,  
          strokeWeight: 5.// Line width, default is 1
          strokeColor: item.color || 'red'.// Line color
          lineJoin: 'round' // The style of the inflection point
        });
        this.polylineList.push(polyline)
      })
      this.map.add(this.polylineList);
    },
    // Draw a parking saturation pie chart
    dragMapParkingPie(parkingList) {
      this.map.remove(this.parkingSpaceMarker);
      this.parkingSpaceMarker = [];
      for(let i=0; i<parkingList.length; i++) {
        this.parkingSpaceMarker.push(
          new AMap.Marker({
            position: new AMap.LngLat(parkingList[i].longitude, parkingList[i].latitude),
            offset: new AMap.Pixel(-80, -80),
            content: `<div style='height: 160px; width: 160px; background: transparent; ' id='echartBox${i}'></div>`
          })
        )
        parkingList[i].elementId = `echartBox${i}`;
      }
      this.map.add(this.parkingSpaceMarker);

      parkingList.forEach(item= > {
        const dom = document.getElementById(item.elementId);
        const myChart = echarts.init(dom);
        const option = getPieOption(item);
        myChart.setOption(option, true); })}.}}</script>
Copy the code

Pie chart configuration

Every. Pie. Config. Js file

export const getPieOption = dataRes= > {
  const emptyNum = dataRes.emptyBerthNum || 0; // The amount of free time
  const totalNum = dataRes.berthNumTotal || 0; / / the total number
  return {
    background: 'transparent'.animation: false.// Close the animation
    title: [{
      text: 'more than'.x: 'center'.top: '50%'.textStyle: {
        color: '#fff'.fontSize: 14,}}, {text: emptyNum,
      x: 'center'.top: '36%'.textStyle: {
        fontSize: 26.color: '#fff'.fontFamily: 'myFont'.foontWeight: 700,}}],polar: {
      radius: ['44%'.'50%'].center: ['50%'.'50%'],},angleAxis: {
      max: totalNum,
      show: false,},radiusAxis: {
      type: 'category'.show: true.axisLabel: {
        show: false,},axisLine: {
        show: false,},axisTick: {
        show: false}},series: [{type: 'pie'.radius: ['40%'.'50%'].silent: true.clockwise: true.startAngle: 90.z: 0.zlevel: 0.label: {
          show: false
        },
        data: [{value: emptyNum,
            name: "".itemStyle: {
              normal: {
                color: { // The color of the completed ring
                  colorStops: [{
                    offset: 0.color: '#FF4824' // The color at 0%
                  }, {
                    offset: 0.5.color: '#FADA16' // The color at 50%
                  }, {
                    offset: 1.color: '#B8E986' // Color at 100%}]},}}, {value: totalNum - emptyNum,
            name: "".label: {
              normal: {
                show: false}},itemStyle: {
              normal: {
                color: "Rgba (255255255,0.27)"}}}]}, {type: 'gauge'.radius: '35%'.startAngle: '0'.endAngle: '359.99'.splitNumber: '50'.center: ['50%'.'50%'].pointer: {
          show: false
        },
        title: {
          show: false
        },
        detail: {
          show: false
        },
        data: [{
          value: totalNum,
          name: ' '}].axisLine: {
          lineStyle: {
            width: 20.opacity: 0}},axisTick: {
          show: false
        },
        splitLine: {
          show: true.length: 2.lineStyle: {
            color: '#fff'.width: 1.type: 'solid',}},axisLabel: {
          show: false}}, {name: ' '.type: 'pie'.startAngle: 90.radius: ['50%'.'57%'].hoverAnimation: false.center: ['50%'.'50%'].itemStyle: {
          normal: {
            labelLine: {
              show: false
            },
            color: 'rgba (0, 0, 0, 0.27)',}},data: [{ value: totalNum }]
      },
      {
        name: ' '.type: 'pie'.startAngle: 90.radius: ['57%'.'59%'].hoverAnimation: false.center: ['50%'.'50%'].itemStyle: {
          normal: {
            labelLine: {
              show: false
            },
            color: 'rgba (255, 255, 255, 0.31)',}},data: [{ value: totalNum }]
      },
    ]
  };
}
Copy the code

mapUtil.js

// Get the content of device Alarm point style marker
export const getAlarmMarkerContent = (firstIcon, secendIcon) = > {
  const content = `<div style="display: flex; align-items: center;" > <img style="width: 25px; height:25px; margin-right: 5px;" src="${firstIcon}" /> <div style="display: flex; align-items: center; Background: rgba (0,0,0,0.67); border: 1px solid #ff4133; border-radius: 7px; Box-shadow: 0px 0px 30px 0px rgba(0,0,0,0.20); padding: 2px 10px;" > <img style="width: 25px; height:25px;" src="${secendIcon}" /> <span style="font-size: 16px; color: #FF4133; width: 70px; margin-left: 5px;" > Device failure </span> </div> </div> '
  return content;
}
Copy the code

Effect of map