如何在本机中自动显示当前位置

问题描述 投票:0回答:1

如何在本机中自动显示当前位置这是我的屏幕,这里有一个按钮,点击该按钮我可以获得位置。但我想获得当前位置我打开这个屏幕并显示标记到当前位置。请帮助我我是新来回应本机。我想在更改位置实现此项目。

  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%'
    }


    });
react-native react-native-android react-native-maps
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.