如何在React Native中自动显示当前位置

时间:2018-10-09 08:20:26

标签: react-native react-native-android react-native-maps

如何在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%'
    }


    });

0 个答案:

没有答案