欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

高德地图

最编程 2024-03-28 16:15:24
...

高德开放平台

uni-app小程序引入高德地图获取定位

1.下包   改es6  module.exports.AMapWX = AMapWX;  =>  export default { AMapWX };

2.manifest.json修改配置

   /* 小程序特有相关 */
    "mp-weixin": {
        "appid": "  ",
        "setting": {
            "urlCheck": false,
            "minified": true
        },
        "usingComponents": true,
        "permission": {
            "scope.userLocation": {
                "desc": "你的位置信息将用于小程序位置接口的效果展示"
            },
            "scope.userFuzzyLocation": {
                "desc": "你的位置信息将用于小程序位置接口的效果展示"
            }
        },
        "requiredPrivateInfos": ["getLocation","chooseLocation"]
    },

3. 使用 

import amap from '@/js_sdk/amap-wx.130.js'
const amapObject = new amap.AMapWX({ key: 'e7f3f43e6e29e977e892f4aaf2c549cf' })
amapObject.getRegeo({
    success: (res) => {
        console.log(res, res[0].regeocodeData.formatted_address)
    },
    fail: (err) => {
        console.log(err)
    }
})

鼠标工具-绘制覆盖物

使用MouseTool可以在地图上绘制Marker、Polyline、Polygon和Circle

     var mouseTool
     changeGeometryArea() { // 保障区域
        this.mapVisible = true
        this.mapType = 2
        this.$nextTick(() => {
          this.initMap()
          this.addMouseTool()
          this.getwPolygon()
        })
      },
      initMap() {
        this.map = new AMap.Map('map', {
          // zoom: 11,
          resizeEnable: true,
          // position: [113.55929, 34.83369],
          mapStyle: 'amap://styles/6828b60c9a0ffe53dc8c212d00742717'
        })
        AMap.plugin('AMap.Geolocation', () => {
          var geolocation = new AMap.Geolocation({
            buttonPosition: 'RB',
            zoomToAccuracy: true,
            enableHighAccuracy: false,
            showMarker: true
          })
          geolocation.getCurrentPosition((status, result) => {
            if (status === 'complete') {
              console.log('initMap -> result', result)
              const position = [result.position.getLng(), result.position.getLat()]
              console.log('initMap -> position', position)
              this.map.setZoomAndCenter(13, position)
            }
          })
        })
        // 输入提示
        var autoOptions = {
          input: 'tipinput'
        }
        var auto = new AMap.Autocomplete(autoOptions)
        placeSearch = new AMap.PlaceSearch({
          map: this.map
        }) // 构造地点查询类
        AMap.event.addListener(auto, 'select', this.select)// 注册监听,当选中某条记录时会触发
      },
      addMouseTool() { // 鼠标工具-绘制保障区域
        mouseTool = new AMap.MouseTool(this.map)
          const that = this
          mouseTool.on('draw', function(e) {
              // event.obj 为绘制出来的覆盖物对象
              polygonAreaList.push(e.obj)
              const path = e.obj.getPath(); // 获取多边形的路径
              const pathArr = []; // 这个就是绘制的点的坐标数组
              for (let i = 0; i < path.length; i++) {
                pathArr.push([path[i].getLng(), path[i].getLat()]);
              }
              that.form.securityArea.push(pathArr);
          })
          mouseTool.polygon({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
          })
      },
      getwPolygon() { // 回显保障区域
        this.form.securityArea.forEach(it => {
          const polygon = new AMap.Polygon({ 
           strokeColor: '#e74a26',
            strokeWeight: 1,
            fillColor: 'red',
            fillOpacity: 0.3,
            path: it,
            zIndex: 50,
            draggable: true
          });
          this.map.add(polygon);
          polygonAreaList.push(polygon);
          this.map.setFitView([polygon])
        })
      },
      clearAll() { // 清除所有保障区域
        polygonAreaList.forEach(it => {
          this.map.remove(it)
        })
        this.form.securityArea = []
        polygonAreaList = []
      },

多边形的绘制和编辑

使用AMap.Polygon和AMap.PolyEditor插件绘制和编辑多边形

      changeGeometry() { // GPS坐标 保障点位
          this.mapVisible = true
          this.mapType = 1
          this.$nextTick(() => {
            this.initMap() // 初始化地图
            this.polygonPoint() // 多边形保障点位区域
            this.setDefaultCursor('pointer') // 使用Map.setDefaultCursor设置地图默认的鼠标样式
            this.map.on('click', this.mapClickHandle) // s鼠标点击添加点位
          })
      },
      mapClickHandle(val) {
        console.log('mapClickHandle -> val', val)
        const { lat, lng } = val.lnglat
        // this.form.geometry.forEach((item, index) => {
        //   if (index === this.indexRadio) {
        //     item.lon = lng
        //     item.lat = lat
        //   }
        // })
        this.form.lngLat = lng + ',' + lat
        const obj = {
          lon: lng,
          lat: lat
        }
        this.form.securityPositions.push(obj)
        this.polygonPoint()
        // this.map.off('click', this.mapClickHandle)
        // this.setDefaultCursor()
      },
     polygonPoint() {
        this.map.remove(this.markerList)
        this.markerList = []
        console.log('polygonPoint ->securityPositions', this.form.securityPositions)
        const path = []
        this.form.securityPositions.forEach((item, index) => {
          if (item.lon && item.lat) {
            path.push([item.lon, item.lat])
            const marker = new AMap.Marker({
              map: this.map,
              position: [item.lon, item.lat],
              draggable: true
            }) 
           marker.sort = index 
           // marker.setLabel({
            //   offset: new AMap.Pixel(0, -10),
            //   content: `<div style="margin-bottom: 5px">编号:${index + 1}</div>
            //   <div style="margin-bottom: 5px">东经:${item.lon}</div>
            //       <div>北纬:${item.lat}</div>`,
            //   direction: 'top'
            // })
            marker.setLabel({
              offset: new AMap.Pixel(0, -5),
              content: `<div>${index + 1}</div>`,
              direction: 'center'
            })
            const _this = this
            marker.on('dragend', function(e) {
              console.log(e)
              _this.form.securityPositions.forEach((item, i) => {
                if (i === e.target.sort) {
                  item.lon = marker.getPosition().lng
                  item.lat = marker.getPosition().lat
                }
              })
              _this.polygonPoint()
            })
            this.markerList.push(marker)
          }
        })
        console.log(path)
        const polygon = new AMap.Polygon({ 
          strokeColor: '#e74a26',
          strokeWeight: 1,
          fillColor: 'red',
          fillOpacity: 0.3,
          path: path,
          zIndex: 50,
          draggable: true
       })
        const _this = this
        polygon.on('dragend', function(e) {
          // console.log(e)
          // console.log(polygon.getPath())
          const arr = []
          polygon.getPath().forEach(t => {
            arr.push({
              lon: t.lng,
              lat: t.lat
            })
          })
          _this.form.securityPositions = arr
          _this.polygonPoint()
        })
        this.map.add(polygon)
        this.markerList.push(polygon) 
       this.map.setFitView([polygon])
      },
      setDefaultCursor(value = null) {
        this.map.setDefaultCursor(value)
      },

多边形群组的绘制和编辑

 // securityArea : [ [ { "lat": 34.744435, "lon": 113.375884},{ "lat": 34.744435, "lon": 113.375884 }  ] ]     
 changeGeometryArea() { // 保障区域
        this.mapVisible = true
        this.mapType = 2
        this.$nextTick(() => {
          this.initMap()
          this.forpolygonPointArea()
          this.setDefaultCursor2('pointer')
          this.map.on('click', this.mapClickHandle2)
        })
      },
      forpolygonPointArea() {
        this.map.remove(this.doubleMarkerList)
        this.doubleMarkerList = []
        this.form.securityArea.forEach((it, index) => {
             this.polygonPointArea(it, index)
          })
      },
    polygonPointArea(securityPositions, ind) {
        console.log('polygonPoint ->securityPositions', securityPositions)
        const path = []
        securityPositions.forEach((item, index) => {
          if (item.lon && item.lat) {
            path.push([item.lon, item.lat])
            const marker = new AMap.Marker({
              map: this.map,
              position: [item.lon, item.lat],
              draggable: true 
           })
            marker.sort = index 
           marker.setLabel({
              offset: new AMap.Pixel(0, -5),
              content: `<div>${index + 1}</div>`,
              direction: 'center'
            })
            const _this = this
            marker.on('dragend', function(e) {
              securityPositions.forEach((item, i) => {
                if (i === e.target.sort) {
                  item.lon = marker.getPosition().lng
                  item.lat = marker.getPosition().lat
                }
              })
              // _this.form.securityArea[ind] = securityPositions
              _this.forpolygonPointArea()
            })
            this.doubleMarkerList.push(marker)
          }
        })
        // console.log(path)
        const polygon = new AMap.Polygon({ // 多边形保障点位区域
          strokeColor: '#e74a26',
          strokeWeight: 1,
          fillColor: 'red',
          fillOpacity: 0.3,
          path: path,
          zIndex: 50,
          draggable: true
        })
        const _this = this
        polygon.on('dragend', function(e) {
          // console.log(polygon.getPath())
          const arr = []
          polygon.getPath().forEach(t => {
            // arr.push([t.lng, t.lat])
            arr.push({
              lon: t.lng,
              lat: t.lat
            })
          })
          _this.form.securityArea[ind] = arr
          _this.forpolygonPointArea()
        })
        this.map.add(polygon)
        this.doubleMarkerList.push(polygon)
        this.map.setFitView([polygon])
      },
    mapClickHandle2(val) {
        const arr = []
        const { lat, lng } = val.lnglat
        // this.form.geometry.forEach((item, index) => {
        //   if (index === this.indexRadio) {
        //     item.lon = lng
        //     item.lat = lat
        //   }
        // })
        this.form.lngLat = lng + ',' + lat 
       // const obj = [lng, lat] 
       const obj = {
          lon: lng, 
         lat: lat
        }
        arr.push(obj)
        if (this.createPolygonArea || this.form.securityArea.length === 0) { // 新增区域  [   [         [ 1,2]       ]       ]
          this.form.securityArea.push(arr)
        } else { // 新增点位
          this.form.securityArea[this.form.securityArea.length - 1].push(obj)
        }
        this.createPolygonArea = false
        this.forpolygonPointArea() 
       // this.map.off('click', this.mapClickHandle)
        // this.setDefaultCursor1()
      },

轨迹回放

import { read, utils } from 'xlsx';
const moveArr = [];
async function readFile(url) {
  const f = await fetch(url);
  const ab = await f.arrayBuffer()
  const wb = read(ab);
  const ws = wb.Sheets[wb.SheetNames[0]]
  // console.log(utils.sheet_to_html(wb.Sheets[wb.SheetNames[0]]))
  utils.sheet_to_json(ws).forEach((it, index) => {
    if (index % 20 === 0) {
      moveArr.push([it['GPS经度(度)'], it['GPS纬度(度)']])
    }
  })
}
let marker1let passedPolylinelet pointArr
            marker1 = new AMap.Marker({   // 无人机图标
              map: this.map,
              resizeEnable: true,
              // offset: new AMap.Pixel(0, -10),
              icon: item.powerCategory === '直升机' ? type1 : item.powerCategory === '多旋翼' ? type2 : item.powerCategory === '固定翼' ? type3 : item.powerCategory === '垂直起降固定翼' ? type4 : icon1,
              position: new AMap.LngLat(item.currentPosition[0], item.currentPosition[1]),
              zIndex: 50
            }) 
           marker1.on('mouseover', function() { // 鼠标悬停提示信息
              marker1.setLabel({
                offset: new AMap.Pixel(0, -10),
                content: `<div style="margin-bottom: 10px; font-size: 16px;">无人机实时信息</div>
                  <div style="margin-bottom: 5px;">编号:${item.uavCode}</div>
                  <div style="margin-bottom: 5px;">机型:${item.powerCategory}</div>
                  <div style="margin-bottom: 5px;">东经:${item.currentPosition[0]}</div>
                  <div style="margin-bottom: 5px;">北纬:${item.currentPosition[1]}</div>`,
                direction: 'top'
              })
            })
            marker1.on('mouseout', function() {  // 鼠标离开
              marker1.setLabel({ 
               offset: new AMap.Pixel(0, -10),
                content: null,
                direction: 'top'
              })
            })
            const that = this
           // 移动中
            this.moving = marker1.on('moving', function (e) {
              // setPath: 设置组成该折线的节点数组
              passedPolyline.setPath(e.passedPath)
              // const length = e.passedPath.length
              // console.log(length, moveArr.length)
              // let flag = true
              // if (length === moveArr.length - 2 && flag) {
              //   console.log('done')
              // that.$message.success('任务已完成', 1);
              //   flag = false
              //   AMap.event.removeListener(that.moving);
              // }
            }) 
           // 移动结束
            this.moveend = marker1.on('movealong', function (e) {
                const item = that.taskList.find(it => it.id === that.taskId)
                console.log(that.realTimeTaskList)
                taskUpdate({
                  ...item,
                  taskRate: 100,
                  taskState: '已完成'
                }).then(res => {
                  if (res.statusCode === 1) {
                    item.taskRate = 100
                    that.getTaskList()
                      }
                })
            })
              // 航线
              const polyline = new AMap.Polyline({
                path: path,
                 // isOutline: true,
                // outlineColor: '#ffeeff',
                // borderWeight: 1,
                strokeColor: color,
                strokeOpacity: 1,
                strokeWeight: 2,
                // 折线样式还支持 'dashed, solid'
                strokeStyle: 'solid',
                // strokeStyle是dashed时有效
                strokeDasharray: [10, 3],
                lineJoin: 'round',
                lineCap: 'round',
                zIndex: 20
              })
              polyline.setMap(this.map)
              // 移动轨迹
              passedPolyline = new AMap.Polyline({
                strokeColor: '#AF5',
                strokeWeight: 6,
                strokeStyle: 'dashed'
              })
               passedPolyline.setMap(this.map)
    start() {  // 开始     
 if (!this.movingFlag) {
        marker1.moveAlong(moveArr, 500)
        this.movingFlag = true
      } else {
        // 恢复点标记的动画效果
        marker1.resumeMove()
      }
    },
    pause() {  // 暂停
      if (this.movingFlag) { 
       // 暂定点标记的动画效果
        marker1.pauseMove()
      }
    },

默认样式信息窗体展示创建默认样式的信息窗体,以及信息窗体的打开操作。

    //在指定位置打开信息窗体
    function openInfo() {
        //构建信息窗体中显示的内容
        var info = [];
        info.push("<div class='input-card content-window-card'><div><img style=\"float:left;width:67px;height:16px;\" src=\" https://webapi.amap.com/images/autonavi.png \"/></div> ");
        info.push("<div style=\"padding:7px 0px 0px 0px;\"><h4>高德软件</h4>");
        info.push("<p class='input-item'>电话 : 010-84107000   邮编 : 100102</p>");
        info.push("<p class='input-item'>地址 :北京市朝阳区望京阜荣街10号首开广场4层</p></div></div>");

        infoWindow = new AMap.InfoWindow({
            content: info.join("")  //使用默认信息窗体框样式,显示信息内容
        });
       infoWindow.setContent(content);       infoWindow.open(map, e.target.getPosition());        infoWindow.open(map, map.getCenter());
        infoWindow.close()