首页 > 解决方案 > 如何在本机反应中自动显示当前位置

问题描述

如何在本机反应中自动显示当前位置这是我的屏幕,这里有一个按钮,通过单击该按钮我可以获得位置。但我想获得当前位置我打开了这个屏幕并显示当前位置的标记。请帮助我我是原生反应的新手。我想在这个项目的更改位置上实施。

  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-nativereact-native-androidreact-native-maps

解决方案


推荐阅读