ReactNative 定位问题

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了

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值