高德地圖實時定位出現的標記重複問題

最近新需求:大體是實現實現實時定位在制定範圍內打卡
一、一開始照着官方文檔這麼寫的 把整個_getPosition()函數放在定時器中 就出現標記重複的問題,其實這個代碼的正確解釋應該是 實時建立多個單獨的定位
二、百度不到相關的解決方案,只能看高德文檔 終於找到了
解決方法 把geolocation.getCurrentPosition() 拆分出來放在定時器中 就解決了瀏覽器

_getPosition () { // 調用瀏覽器定位服務
      let geolocation = null
      this.myMap.plugin('AMap.Geolocation', () => {
        geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位,默認:true
          noIpLocate: 1,
          timeout: 100, // 超過10秒後中止定位,默認:無窮大
          maximumAge: 0, // 定位結果緩存0毫秒,默認:0
          convert: true, // 自動偏移座標,偏移後的座標爲高德座標,默認:true
          showButton: false, // 顯示定位按鈕,默認:true
          buttonPosition: 'LB', // 定位按鈕停靠位置,默認:'LB',左下角
          buttonOffset: new AMap.Pixel(10, 20), // 定位按鈕與設置的停靠位置的偏移量,默認:Pixel(10, 20)
          showMarker: true, // 定位成功後在定位到的位置顯示點標記,默認:true
          showCircle: true, // 定位成功後用圓圈表示定位精度範圍,默認:true
          panToLocation: false, // 定位成功後將定位到的位置做爲地圖中心點,默認:true
          zoomToAccuracy: false // 定位成功後調整地圖視野範圍使定位位置及精度範圍視野內可見,默認:false
        })
        this.myMap.addControl(geolocation)
        geolocation.getCurrentPosition((status, result) => {
          if (status === 'complete') {
            this.onComplete(result)
          } else {
            this.onError(result)
          }
        })
      })
    }

正確代碼緩存

this.interval = setInterval(() => {
  this._getPositionFunc()
}, 2000)

 _getPosition () { // 調用瀏覽器定位服務
      this.myMap.plugin('AMap.Geolocation', () => {
        this.geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位,默認:true
          noIpLocate: 1,
          timeout: 100, // 超過10秒後中止定位,默認:無窮大
          maximumAge: 0, // 定位結果緩存0毫秒,默認:0
          convert: true, // 自動偏移座標,偏移後的座標爲高德座標,默認:true
          showButton: false, // 顯示定位按鈕,默認:true
          buttonPosition: 'LB', // 定位按鈕停靠位置,默認:'LB',左下角
          buttonOffset: new AMap.Pixel(10, 20), // 定位按鈕與設置的停靠位置的偏移量,默認:Pixel(10, 20)
          showMarker: true, // 定位成功後在定位到的位置顯示點標記,默認:true
          showCircle: true, // 定位成功後用圓圈表示定位精度範圍,默認:true
          panToLocation: false, // 定位成功後將定位到的位置做爲地圖中心點,默認:true
          zoomToAccuracy: false // 定位成功後調整地圖視野範圍使定位位置及精度範圍視野內可見,默認:false
        })
        this.myMap.addControl(this.geolocation)
        this._getPositionFunc()
      })
    },
    _getPositionFunc () {
      this.geolocation.getCurrentPosition((status, result) => {
        console.log('11')
        if (status === 'complete') {
          this.onComplete(result)
        } else {
          this.onError(result)
        }
      })
    }
相關文章
相關標籤/搜索