1.在HTML5中使用Geolocation.getCurrentPosition()方法來獲取地理位置。
語法:
navigator.geolocation.getCurrentPosition(success, error, options)
參數:
2.success - 成功得到位置信息時的回調函數
navigator.geolocation.getCurrentPosition(function(position)) { // 獲取成功時的的處理 //參數position是地理位置對象 }
position中返回的信息如下圖:
3.error - 獲取位置信息失敗時的回調函數
navigator.geolocation.getCurrentPosition(function(position){ // 獲取成功時的的處理; //參數position是地理位置對象 },function(error)) { // 獲取失敗時的的處理; }
error中返回的信息如下圖
code屬性有以下值:
- 1 地理位置信息的獲取失敗,因為該頁面沒有獲取地理位置信息的權限。
- 2 地理位置獲取失敗,因為至少有一個內部位置源返回一個內部錯誤。
- 3 獲取地理位置超時,通過定義PositionOptions.timeout 來設置獲取地理位置的超時時長。
message 返回一個開發者可以理解的 DOMString 來描述錯誤的詳細信息。
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)
參數:
6.使用cordova+vue開發webapp中定位解決方法:
在cordova中安裝Geolocation插件后,方可在生成的app中獲取到地理位置信息,運行如下命令即可:
cordova plugin add cordova-plugin-geolocation
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com