RN的定位官方提供了API Gecolocation ,通过这个api我们可以拿到当前的经纬度,代码如下:
componentDidMount(){ navigator.geolocation.watchPosition( (position) => { let longitude = JSON.stringify(position.coords.longitude);//精度 let latitude = JSON.stringify(position.coords.latitude);//纬度 console.log(longitude+latitude); this.fetchData(longitude,latitude); }, (error) =>{ console.log(error); }, {enableHighAccuracy: true, timeout: 5000, maximumAge: 1000} ); }这样我们就可以拿到当前的经纬度,然后接下来不需要借助任何第三方插件,直接使用高德的 地理编码的api接口,具体地址是http://lbs.amap.com/api/webservice/guide/api/georegeo#geo
只要申请个web服务key就可以直接拿来用,继续上代码:
fetchData=(longitude,latitude)=>{ fetch('http://restapi.amap.com/v3/geocode/regeo?key=你的key&location='+longitude+','+latitude+'') .then((response)=>response.json()) .then((responseBody)=>{ console.log(responseBody); console.log(responseBody.regeocode.addressComponent.province); let city = responseBody.regeocode.addressComponent.province; let district = responseBody.regeocode.addressComponent.district; let township = responseBody.regeocode.addressComponent.township; if(responseBody.status ==1){ this.setState({ city:city, district:district, township:township, }) }else { ToastAndroid.show('定位失败',ToastAndroid.LONG) } }).catch((error)=>{ console.log(error); }) };