百度地圖獲取定位 React Native
獲取金鑰: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,
}
);
}
}