Search code examples
react-nativereact-native-maps

How to go to my current location using custom button in react-native-maps?


I am using react-native-maps on android. I put a custom button clicking on which should go to supplied coordinates (my current location)

<MapView
          ref={(map) => { this.map = map; }}
          provider={PROVIDER_GOOGLE}
          style={{ height: '100%', width: '100%' }}
          annotations={markers} 
          showsUserLocation={true}
          showsMyLocationButton={true}
          initialRegion={this.state.region}
          onRegionChangeComplete={this.onRegionChange}
        >

my button -

<TouchableOpacity onPress={this.gotToMyLocation} style={[Style.alignJustifyCenter, {
          width: 60, height: 60,
          position: "absolute", bottom: 20, right: 20, borderRadius: 30, backgroundColor: "#d2d2d2"
        }]}>
          <Image
            style={{ width: 40, height: 40 }}
            source={Images.myLocation}
          />
        </TouchableOpacity>

gotToMyLocation method -

gotToMyLocation(){
    console.log('gotToMyLocation is called')
    navigator.geolocation.getCurrentPosition(
      ({ coords }) => {
        console.log("curent location: ", coords)
        console.log(this.map);
        if (this.map) {
          console.log("curent location: ", coords)
          this.map.animateToRegion({
            latitude: coords.latitude,
            longitude: coords.longitude,
            latitudeDelta: 0.005,
            longitudeDelta: 0.005
          })
        }
      },
      (error) => alert('Error: Are location services on?'),
      { enableHighAccuracy: true }
    )
  }

console.log(this.map) always shows undefined.

I want to move map to my current location when clicking the button.


Solution

  • Actually i found out a silly mistake where binding the method would make it work. may be useful to someone. this.gotToMyLocation = this.gotToMyLocation.bind(this);