1.在HTML5中使用Geolocation.getCurrentPosition()方法來獲取地理位置。html
語法:vue
navigator.geolocation.getCurrentPosition(success, error, options)
參數:git
success: 成功獲得位置信息時的回調函數,使用Position 對象做爲惟一的參數。 error: 獲取位置信息失敗時的回調函數,使用 PositionError 對象做爲惟一的參數,這是一個可選項。 options:一個可選的PositionOptions 對象,包含如下3個參數。 enableHighAccuracy 是一個Boolean值,用來代表應用是否使用其最高精度來表示結果,默認爲false。 timeout 是一個正的long值,代表的是設備必須在多長時間(單位毫秒)內返回一個位置,默認是Infinity。 maximumAge 是一個正的long值,代表能夠返回多長時間(即最終年齡,單位毫秒)內的可獲取的緩存位置。若是設置爲 0, 說明設備不能使用一個緩存位置,並且必須去獲取一個真實的當前位置。若是設置爲 Infinity ,那麼無論設 置的最終年齡是多少,設備都必須返回一個緩存位置。默認值:0
2.success - 成功獲得位置信息時的回調函數web
navigator.geolocation.getCurrentPosition(function(position)) { // 獲取成功時的的處理 //參數position是地理位置對象 }
position中返回的信息以下圖:瀏覽器
3.error - 獲取位置信息失敗時的回調函數緩存
navigator.geolocation.getCurrentPosition(function(position){ // 獲取成功時的的處理; //參數position是地理位置對象 },function(error)) { // 獲取失敗時的的處理; }
error中返回的信息以下圖安全
code屬性有如下值:app
- 1 地理位置信息的獲取失敗,由於該頁面沒有獲取地理位置信息的權限。 - 2 地理位置獲取失敗,由於至少有一個內部位置源返回一個內部錯誤。 - 3 獲取地理位置超時,經過定義PositionOptions.timeout 來設置獲取地理位置的超時時長。
message 返回一個開發者能夠理解的 DOMString 來描述錯誤的詳細信息。webapp
4.使用Geolocation.getCurrentPosition()注意事項:函數
5.使用Geolocation.getCurrentPosition()獲取經緯度信息,並轉換爲百度座標並進行逆地址解析:
以Vue項目爲例,首先根目錄index.html中引入百度API文件,以下圖:
獲取位置,標記marker並進行逆地址解析代碼以下:
// 1 查詢當前位置信息 getPosition() { navigator.geolocation.getCurrentPosition(this.getPositionSuccess, this.getPositionError, {"enableHighAccuracy": true, "timeout": 5000, "maximumAge": 5000}) }, // 1-1 查詢當前位置信息成功 getPositionSuccess(position) { this.latitude = String(position.coords.latitude) this.longitude = String(position.coords.longitude) let ggPoint = new BMap.Point(this.longitude, this.latitude) let pointArr = [] pointArr.push(ggPoint) let convertor = new BMap.Convertor() // 座標轉換 convertor.translate(pointArr, 1, 5, this.translateCallback) }, // 1-2 查詢當前位置信息失敗 getPositionError(error) { this.$toast({ message: `獲取地理位置失敗請重試~`, duration: 1000 }) }, // 座標轉換回調 translateCallback(data) { if (data.status === 0) { // 在地圖上標註marker let marker = new BMap.Marker(data.points[0]) map.addOverlay(marker) map.panTo(data.points[0]) // 逆地址解析 let myGeo = new BMap.Geocoder() let that = this myGeo.getLocation(data.points[0], function(result){ if (result){ // 獲取逆地址解析結果 that.clockSite = result.address } }) } },
座標轉換convertor.translate()方法說明:
語法:
convertor.translate(coords, from, to, fn)
參數:
coords:需轉換的源座標 from: 源座標類型 詳見:[類型詳情][4] to: 目標座標類型 詳見:[類型詳情][5] fn: 轉換結果回調
6.使用cordova+vue開發webapp中定位解決方法:
在cordova中安裝Geolocation插件後,方可在生成的app中獲取到地理位置信息,運行以下命令便可:
cordova plugin add cordova-plugin-geolocation