import React, {Component} from 'react';
import {StyleSheet, Text, View}from 'react-native';
exportdefault classTestGeo extends Component {
state={
longitude:'',//经度
latitude: '',//纬度
city: '',
district:'',
street:'',
position:'',//位置名称
};
componentWillMount= () =>{this.getPositions();
};
getPositions= () =>{return new Promise(() =>{/** 获取当前位置信息*/navigator.geolocation.getCurrentPosition(
location=>{this.setState({
longitude: location.coords.longitude,//经度
latitude: location.coords.latitude,//纬度
});//通过调用高德地图逆地理接口,传入经纬度获取位置信息
fetch(`http://restapi.amap.com/v3/geocode/regeo?key=97c933e33025b3843b40016900074704&location=${this.state.longitude},${this.state.latitude}&radius=1000&extensions=all&batch=false&roadlevel=0`, {
method: "POST",
headers: {"Content-Type": "application/x-www-form-urlencoded"},
body: ``
})
.then((response)=>response.json())
.then((jsonData)=>{//console.log(jsonData)
try{this.setState({
city: jsonData.regeocode.addressComponent.city,
district: jsonData.regeocode.addressComponent.district,
street: jsonData.regeocode.addressComponent.township,
position: jsonData.regeocode.formatted_address,
});
}catch(e) {
}
})
.catch((error) =>{
console.error(error);
});
},
error=>{
console.error(error);
}
);
})
}
render() {return(
经度:{this.state.longitude}
纬度:{this.state.latitude}
城市:{this.state.city}
区域:{this.state.district}
街道:{this.state.street}
详细位置:{this.state.position}
);
}
}const styles =StyleSheet.create({
container: {
flex:1,
justifyContent:'center',
alignItems:'center',
backgroundColor:'#F5FCFF',
},
instructions: {
textAlign:'center',
color:'#333333',
marginBottom:5,
},
});