Search code examples
react-nativereact-native-maps

React native maps move to coordinate change


In my app, I have google map. It is implemented as given below.

<MapView style={[styles.mapStyle, { flex: 1, width: this.state.mapWidth }]}
                            initialRegion={{
                                latitude: this.state.latitude,
                                longitude: this.state.longitude,
                                latitudeDelta: 0.1,
                                longitudeDelta: 0.1,
                            }}
                            provider={PROVIDER_GOOGLE}
                            onPress={this.onMapPress.bind(this)}
                            showsUserLocation={true}
                            followsUserLocation={true}
                            showsMyLocationButton={true}
                            showsCompass={true}
                            showsTraffic={true}
                            toolbarEnabled={true}
                            onMapReady={() => this.setState({ width: width - 1 })}
                        >
                            <Marker draggable
                                coordinate={{
                                    latitude: this.state.latitude,
                                    longitude: this.state.longitude,
                                }}
                                onDragEnd={(e) => this.setState({ x: e.nativeEvent.coordinate })}
                            />
                            <Circle
                                center={{
                                    latitude: this.state.latitude,
                                    longitude: this.state.longitude,
                                }}
                                radius={this.state.radius}
                                fillColor='rgba(253, 48, 4,0.5)'
                                strokeColor='rgba(253, 48, 4,1)'
                            />
   </MapView>

When I click on a button I change the state value of region of the the map.

changeRegion(){
    this.setState({ latitude: 6.86, longitude: 6.86 });
}

This successfully changes the position of the marker of the map.

My problem is, map doesn't move to selected position. How can I achieve that?


Solution

  • Create a ref for your Map

    const mapRef = React.createRef();
    

    Pass the ref to your Map

    <Map
      ref={mapRef}
      // Rest of your props
    />
    

    Modify your function

    changeRegion(){
      const latitude = 6.86;
      const longitude = 6.86;
      this.setState({ latitude, longitude });
      mapRef.current.animateToRegion({
        latitude,
        longitude,
        latitudeDelta: 0.1,
        longitudeDelta: 0.1
      })
    }