react-native - 如何在本机反应中自动显示当前位置
问题描述
如何在本机反应中自动显示当前位置这是我的屏幕,这里有一个按钮,通过单击该按钮我可以获得位置。但我想获得当前位置我打开了这个屏幕并显示当前位置的标记。请帮助我我是原生反应的新手。我想在这个项目的更改位置上实施。
import React, { Component } from 'react';
import { View, StyleSheet,Text,Button, Dimensions } from 'react-native';
import MapView from 'react-native-maps';
class SecondScreen extends Component{
constructor(props) {
super(props);
this.getLocationHandler = this.getLocationHandler.bind(this);
}
static navigationOptions =
{
title: 'Welcome',
headerStyle: {
backgroundColor:'steelblue'
},
headerTintColor: '#fff',
};
state ={
focusedLocation:{
latitude:12.84497121,
longitude:77.68119763,
latitudeDelta:0.0122,
longitudeDelta:Dimensions.get("window").width /
Dimensions.get("window").height * 0.0122
},
locationChoosen:false
}
pickLocationHandler = event => {
const coords = event.nativeEvent.coordinate;
this.map.animateToRegion({
...this.state.focusedLocation,
latitude :coords.latitude,
longitude : coords.longitude
});
this.setState(prevState =>{
return {
focusedLocation :{
...prevState.focusedLocation,
latitude:coords.latitude,
longitude:coords.longitude
},
locationChoosen:true
};
});
};
getLocationHandler = () =>{
navigator.geolocation.getCurrentPosition(pos =>{
const coordsEvent ={
nativeEvent :{
coordinate : {
latitude : pos.coords.latitude,
longitude : pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err);
alert("Fetching the position failed,Please pick one manually")
})
}
render() {
let marker =null;
if(this.state.locationChoosen){
marker = <MapView.Marker coordinate = {this.state.focusedLocation} />;
}
return (
<View style={{flex: 1}}>
<MapView
initialRegion={this.state.focusedLocation}
//{...getLocationHandler}
style={styles.map}
onPress = {this.pickLocationHandler}
ref = {ref => this.map = ref} >
{marker}
</MapView>
<Button title = "Locate me" onPress={this.getLocationHandler}/>
</View>
);
}
}
export default SecondScreen
const styles = StyleSheet.create({
map:{
width:"100%",
height:'90%'
}
});
解决方案
推荐阅读
- c# - MSTest V2 按顺序执行单元测试 -> [DoNotParallelize]
- javascript - Webpack 4 – 简单的 js 函数在捆绑文件后不起作用
- java - 将 HashMap 上的 Java Lambda foreach 转换为 Dictionary 上的 C# foreach
- java - 如何将 SVG 文本转换为 SVG 路径?
- python - 如何通过检查行 x+1-行 x 是否大于某个值来更改值(熊猫)
- c# - dotnet-counters ps 不显示任何进程
- javascript - 如何在 Vue-Material 对话框中添加滚动条
- blazor - 如何从另一个方法调用 EditForm 验证方法?
- jenkins - 无法在 Jenkins Pipeline 中创建新文件
- python - 如何使用列表理解从另一个列表中获取一些数据?