react-native - 想从 react native js+google api key 获取当前位置
问题描述
我想在文本/警报中获取当前位置,以响应本机想要文本中的城市名称
这是我的代码:
getData(){
Geocoder.init("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
Geocoder.from(41.89, 12.49)
.then(json => {
var addressComponent = json.results[0].formatted_address;
console.log(addressComponent);
console.log(addressComponent)
alert(addressComponent);
})
.catch(error => console.warn(error));
}
解决方案
地理定位 API 的完整示例。
正如我在评论中所说;你不需要谷歌 API 来获取设备的当前坐标。您可以使用地理位置 API
import React, { Component } from 'react';
import { View, Text } from 'react-native';
class FindMyLocationExample extends Component {
constructor(props) {
super(props);
this.state = {
latitude: null,
longitude: null,
error: null,
};
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 10000, maximumAge: 1000 },
);
}
render() {
return (
<View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Latitude: {this.state.latitude}</Text>
<Text>Longitude: {this.state.longitude}</Text>
{this.state.error ? <Text>Error: {this.state.error}</Text> : null}
</View>
);
}
}
推荐阅读
- javafx - 在 JavaFX 中保存和加载 ObservableList
- javascript - 如何在 JavaScript 中调用 Python 变量?
- r - R - 重新排序 NULL 列
- mysql - mysql 触发器中的 if else 块中的 Use Case 语句
- sql - 按非主键属性分组 min(Value) 并从同一行加入附加属性(使用原始 SQL 或 SQLalchemy)
- laravel - 提交表单vue后重定向到主页
- azure - 如何正确将 ASPNETCORE_ENV 设置为非开发值?
- ruby - 即使捆绑安装运行良好,gem 中的加载错误
- sql-server - 对于具有 IDENTITY 列的表上的 INSTEAD OF 触发器,如何处理 IDENTITY_INSERT?
- c# - TcpListener 在 UWP 应用程序上不起作用