0

你好我想知道是否有一種方法來提供WatchPosition()函數特定的緯度/經度,從一個座標數組提供。如何使用WatchPosition()函數地理位置來觀看其他座標

我在創建使用類似默認座標系的回調函數時遇到問題。拉特座標。 long

換言之,我想創建某種類型的函數,它可以以類似的方式使用,但提供了我的任意座標集,以便watchPosition()可以在循環遍歷數組時更新位置,並且不同的位置被設置。

if(navigator.geolocation) { 

    navigator.geolocation.watchPosition(function(position) { 
     var pos = new google.maps.LatLng(position.coords.latitude, 
             position.coords.longitude); 

}

回答

2

我需要做同樣的事情,所以我寫了一個測試腳本使用模擬一個更換navigator.geolocation對象。這裏是我的代碼:

// Replace real geolocation with mock geolocation 
delete navigator.geolocation;  
navigator.geolocation = { 
    isMock: true, 
    paused: true, 
    delay: 100, 
    shouldFail: false, 
    failsAt: -1, 
    unFailsAt: -1, 
    errorMessage: "There was an error retrieving the position!", 
    currentTimeout: -1, 
    lastPosReturned: 0, 
    overrideAccuracy: 0, // accuracy in m to return for all positions (overrides any existing accuracies defined in the waypoints) 
    useOverrideAccuracy: false, // Whether to override acurracies defined in the waypoints with the above override accuracy  

    _geoCall: function(method, success, error, repeat) { 

     return this.currentTimeout = window[method].call(null, __bind(function() { 

     var nextPos; 

     if(!this.paused && this.lastPosReturned < this.waypoints.length - 1){ 
      nextPos = this.lastPosReturned++;    
     }else{ 
      this.lastPosReturned = nextPos = 0; 
     } 


     if(!this.shouldFail && nextPos == this.failsAt) this.shouldFail = true; 
     if(this.shouldFail && nextPos == this.unFailsAt) this.shouldFail = false; 

     if(repeat) this._geoCall("setTimeout", success, error, true); 

     if (this.shouldFail && (error != null)) {    
      return error(this.errorMessage); 
     } 
     else if (success != null && !this.paused) {     
      var result = this.waypoints[nextPos]; 
      result.isMock = true; 
      if(this.useOverrideAccuracy) result.coords.accuracy = this.overrideAccuracy;    
      success(result); 
      return nextPos; 
     } 
     }, this), this.delay); 

    }, 
    getCurrentPosition: function(success, error) { 
    return this._geoCall("setTimeout", success, error, false); 
    }, 
    watchPosition: function(success, error) { 
    this._geoCall("setTimeout", success, error, true); 
    return this.currentTimeout; 
    }, 
    clearWatch: function(id) { 
    return clearInterval(this.currentTimeout); 
    }, 
    waypoints: [] 
}; 

然後,我只需要填充navigator.geolocation.waypoints陣列位置的物體。

+0

我想用watchPosition跟蹤自己的位置,然後使用相同的函數觀察其他人的位置,他們的座標是從數組中提供的。 – Kayoti

+0

所以你想同時接收「真實」位置更新和模擬位置更新?你可以使用我的代碼進行模擬位置更新,但將其重命名爲navigator.mockGeolocation。然後,您將能夠同時觀看真實位置(navigator.geolocation.watchPosition)和模擬位置(navigator.mockGeolocation.watchPosition)。 – DaveAlden

+0

Awsome謝謝 – Kayoti

相關問題