firebase - 访问当前位置并将其发送到 firebase
问题描述
我有一个我正在使用的本机应用程序react-native-maps
。我想将当前位置发送到 firebase,并且我想在用户从当前位置超过 100 米时提醒他。我怎样才能做到这一点?
附加信息:
- React Native 版本“0.57.5”
- 反应原生火力基地“^5.2.3”
- 反应原生地图“^0.22.1”
提前致谢。
解决方案
您可以在组件已安装后查询用户的当前位置并继续侦听位置变化,然后计算与不同位置的距离变化:
componentDidMount() {
this.getLocation(); // Get users current location
}
componentDidUpdate(prevProps, prevState) {
// If prevState changes
if (prevState.newLatitude !== this.state.newLatitude) {
// calculate the distance between initial and new coordinates
this.getDistance();
}
}
componentWillUnmount() {
// Remember to clear all listeners
navigator.geolocation.clearWatch(this.watcher);
}
getLocation() {
navigator.geolocation.getCurrentPosition((position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude
}, () => {
this.sendToFirebase();
this.watchUserPosition(); //continue listening for location changes
});
},
(error) => {
//Handle error
},
{ enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 },
);
}
watchUserPosition() {
this.watcher = navigator.geolocation.watchPosition(
(position) => {
this.setState({
newLatitude: position.coords.latitude,
newLongitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 10 },
);
}
现在,在获得初始经度和纬度后,您可以继续比较您从中获得的新经度和纬度watchUserPosition
。这相当于将经度和纬度转换为米,并检查以米为单位的初始坐标与以米为单位的新坐标的差异。
为此,您可以使用Geolib 库
getDistance() {
let initial = {latitude: this.state.latitude, longitude: this.state.longitude};
let newCoord = {latitude: this.state.newLatitude, longitude: this.state.newLongitude};
const distance = geolib.getDistance(initial, newCoord);
if (distance >== 100) {
Alert.alert("Success!", "You have reached 100meters!");
this.sendToFirebase(); // whatever you are saving to firebase
}
}
或者,您可能需要考虑使用Firebase Geo-Fire
推荐阅读
- aws-sdk - AWS CloudFront 开发工具包 - 测试是否可以提供文件
- mysql - 查找所有因升级而遇到“bios error”的主机。可以使用任何数据库,如 MySQL/Oracle
- xml - 有没有办法从 OWL (RDF/XML) 文件中快速访问所有注释和子注释?
- python - 求函数的最小值?
- rest - 如何从 Spring Data REST 中的集合关联中删除元素?
- javascript - 使用 jest.mock 时如何修改单个方法
- c - 如何在 C 中读取文本文件的特定部分?
- php - PHP - 合并两个对象数组,包括其他对象
- javascript - 在Angular 8中将数字转换为度数
- python - OSError: [Errno 22] 写入 tar 文件的参数无效