ReactNative 定位问题

来源:互联网 发布:淘宝古着是什么意思 编辑:程序博客网 时间:2024/06/05 15:37

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);    })};

这样就把我们刚才得到的经纬度 转换为有用的json数据了!定位成功,想要的都在json里面,直接调用就OK了

0 0