react native 官網(wǎng)介紹了這個(gè) api Geolocation 但是這個(gè)api只能返回 經(jīng)緯度 所以要把經(jīng)緯度 通過逆地理位置轉(zhuǎn)義 http://recode.ditu.aliyun.com/jsdoc/geocode_api.html 可通過這個(gè)阿里的開放接口
在 react native 中,我們所用的是react native 自帶的api定位功能,無需引入第三方j(luò)s。
react native 定位是通過Geolocation這個(gè)模塊來實(shí)現(xiàn)的。想了解更多關(guān)于Geolocation的知識(shí)請(qǐng)點(diǎn)擊下面 Geolocation自行了解,這里我們主要將他的幾個(gè)方法。
static getCurrentPosition(geo_success, geo_error?, geo_options?)
Invokes the success callback once with the latest location info. Supported options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool) On Android, this can return almost immediately if the location is cached or request an update, which might take a while.
static watchPosition(success, error?, options?)
Invokes the success callback whenever the location changes. Supported options: timeout (ms), maximumAge (ms), enableHighAccuracy (bool), distanceFilter(m)
static clearWatch(watchID)
第一個(gè)方法是獲取第一次定位時(shí)的位置信息,第一個(gè)為成功時(shí)的回掉函數(shù),還有error時(shí)的回掉,第三個(gè)是傳狀態(tài)的。
在請(qǐng)求成功函數(shù)中有以下屬性:
在請(qǐng)求失敗函數(shù)中有4種情況(err.code狀態(tài)值):
1為用戶拒絕定位請(qǐng)問
2暫時(shí)獲取不到位置信息
3為請(qǐng)求超時(shí)
4未知錯(cuò)誤
第三個(gè)options是可選參數(shù),屬性如下:
enableHighAccuracy——指示瀏覽器獲取高精度的位置,默認(rèn)為false。當(dāng)開啟后,可能沒有任何影響,也可能使瀏覽器花費(fèi)更長的時(shí)間獲取更精確的位置數(shù)據(jù)。
timeout——指定獲取地理位置的超時(shí)時(shí)間,默認(rèn)不限時(shí)。單位為毫秒。
maximumAge——最長有效期,在重復(fù)獲取地理位置時(shí),此參數(shù)指定多久再次獲取位置。默認(rèn)為0,表示瀏覽器需要立刻重新計(jì)算位置。
static watchPosition(success, error?, options?)
是多次改變了位置信息時(shí)才會(huì)觸發(fā),一般觸發(fā)的可能性可能用戶多次刷新數(shù)據(jù),如一個(gè)人行車到其他城市,這時(shí)如果設(shè)置一個(gè)監(jiān)聽函數(shù),只要watchid不一樣,就會(huì)不斷的觸發(fā)
由于可能會(huì)出現(xiàn)緩存的情況,所以Geolocation 為我們提供了一個(gè)可以清除緩存的方法watchPosition(),改方法是 用于上一次的定位信息進(jìn)行清除的。
對(duì)了,要啟動(dòng)react native 的定位功能的話,如果你是android 用戶,你需要先在AndroidManifest.xml中加入以下權(quán)限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
具體實(shí)現(xiàn)
import Geolocation from 'Geolocation'; ...... getlocal() { Geolocation.getCurrentPosition( val => { let ValInfo = '速度:' + val.coords.speed + '\n經(jīng)度:' + val.coords.longitude + '\n緯度:' + val.coords.latitude + '\n準(zhǔn)確度:' + val.coords.accuracy + '\n行進(jìn)方向:' + val.coords.heading + '\n海拔:' + val.coords.altitude + '\n海拔準(zhǔn)確度:' + val.coords.altitudeAccuracy + '\n時(shí)間戳:' + val.timestamp; this.setState({ LocalPosition: ValInfo }); console.log("打印地理位置:"+`${val.coords.longitude},${val.coords.latitude}`) GET_GPRS({ "l":`${val.coords.latitude},${val.coords.longitude}`, "type":111, }).then(res => { console.log(JSON.stringify(res)) }) }, val => { let ValInfo = '獲取坐標(biāo)失敗:' + val; this.setState({ LocalPosition: ValInfo }); //如果為空的話 沒允許開啟定位服務(wù) }, ); }
這里的 GET_GPRS 是自己封裝的 fech請(qǐng)求
記得開啟 位置訪問權(quán)限
打印結(jié)果如下:
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com