获取密钥:http://lbsyun.baidu.com/apiconsole/key
去百度地图申请应用;
百度地图api(ak值申请后可以获得,安全码在申请应用点击设置后可以查看)
BaiduMap_URL =‘https://api.map.baidu.com/geocoder/v2/?output=json&ak=ak值&mcode=安全码;com.mypw&location=’ 3. 根据RN提供的api获取当前经纬度/安卓需添加定位权限
第一步:
//获取经纬度 getLongitudeAndLatitude = () => { return new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition( location => { resolve([location.coords.longitude, location.coords.latitude]); }, error => { reject(error); } ); }); }; 第二步:
//获取网络数据 getNetData = url => { return new Promise((resolve, reject) => { fetch(url) .then(response => response.json()) .then(responseData => { resolve(responseData); }) .catch(error => { reject(error); }) .done(); }); }; 第三步:
//获取城市定位信息 getCityLocation = () => { return new Promise((resolve, reject) => { getLongitudeAndLatitude() //获取经纬度的方法返回的是经纬度组成的数组 .then(locationArr => { let longitude = locationArr[0]; let latitude = locationArr[1];
this.getNetData(BaiduMap_URL + latitude + ',' + longitude) .then(data => { if (data.status == 0) { resolve(data); } else { reject(data.code); } }) .catch(data => { reject(data.code); }); }) .catch(data => { reject(data.code); });}); }; 4. 使用方法:
getCityLocation() .then(res => { console.log(‘获取当前位置’, res); this._confirmCity(res); }) .catch(err => { logWarn(‘获取失败’ + err); }); //弹出定位框 _confirmCity(data) { let address = data.result.addressComponent;
if (address != ‘’) { Alert.alert( ``, 当前定位城市为${address.city},\n\n是否设为当前城市?\n, [ { text: ‘取消’, onPress: () => {}, }, { text: ‘确定’, onPress: () => {}, }, ], { cancelable: true, } ); } }