React native Geolocation定位

react native 版本为0.57.4
最近在做公司的巡检app,需要用到定位并且显示到地图上,本来用的mapbox地图可以自己定位添加得到地图上,
在模拟器上可以定位显示到地图上,但是用的地图是外国的地图,在安卓真机上得需要Google框架才能定位, 需要购买Google Play services 的手机才可以,所以要自己获取经纬度并且添加到地图上

react native 有专门的地理定位(Geolocation)API

在这里我需要郑重地说一下,在网上一些文章里边是这样引入Geolocation的,

var  Geolocation =require('Geolocation');

起初我也是这样引入的,在安卓真机上测试的时候没有啥问题,但是打包成apk后。一打开apk就闪退,后来排查是因为这样引入的原因
所以一定要这样引入

import Geolocation from 'Geolocation'

还有定位还需要在AndroidManifest.xml 里边开权限,这里演示的是安卓,ios暂时不讲
在这里插入图片描述
调用 getCurrentPosition 方法得到经纬度

getLocation(){
         Geolocation.getCurrentPosition((location) => {
            let coordinate = [location.coords.longitude,location.coords.latitude]
            this.setState({
                currentLocation:coordinate
            })
        });
     }

watchPosition() 持续监听位置,每当位置变化之后都调用 success 回调。返回一个watchId(整型)

 beginWatch(){
          this.state.watchID = Geolocation.watchPosition((location) => {
               let coordinate = [location.coords.longitude,location.coords.latitude]
               this.setState({
                    currentLocation:coordinate
                })
            }
          );
     }

停止监听位置变化

 stopWatch() {
        Geolocation.clearWatch(this.state.watchID);
    }

但这个只能获取到经纬度和一些其他信息,要想获取到具体的地址可以调用百度地图或者高德地图的位置服务
例如 高德开发平台的web服务api
https://lbs.amap.com/api/webservice/guide/api/georegeo

猜你喜欢

转载自blog.csdn.net/wyw223/article/details/84312074