Matheus Cabral
Matheus Cabral

Reputation: 182

Map is always centered in the searched location marker

When I put the code: region={this.props.region} it works and center the map in the searched location but do not allows to select other markers in the map... it always came back to the searched location, if I take off this part of the code: region={this.props.region}, I can select other markers but when I search other location the camera do not move to the chosen location. How proceed in this case?

Here is some code:

<MapView
        provider="google"
        style={styles.map}
        //region={this.props.region}
        initialRegion={this.state.focusedlocation}
        ref={ref => (this.map = ref)}>
        {this.renderMarkers()}
        <MapView.Marker
          onPress={this.pickLocationHandler}
          coordinate={this.props.region}>
          <Image source={markerImage} style={styles.icon} />
        </MapView.Marker>
      </MapView>

Here below is the code to animate to the markers:

 pickLocationHandler = event => {
const coords = event.nativeEvent.coordinate;
console.log('Location picker Marker', coords);
this.map.animateToRegion({
  ...this.state.focusedlocation,
  latitude: coords.latitude,
  longitude: coords.longitude,
  latitudeDelta: LATITUDE_DELTA,
  longitudeDelta: LONGITUDE_DELTA,
});

Please open this snack to entire code

Upvotes: 4

Views: 1323

Answers (1)

Tuan Luong
Tuan Luong

Reputation: 4162

region used when you want to control the viewport of map. In your case, you can use animateCamera to move the map to your searched location.

this.map.animateCamera({
  center: {latitude, longitude}
})

UPDATE

map-view.js

export default class MapView extends Component {
  ...
  animateToLocation = (location) => {
    this.map.animateToRegion({
      latitude: location.latitude,
      longitude: location.longitude,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta: LONGITUDE_DELTA,
    });
  }
  ...
  render() {
    return (
      <View style={styles.container} {...this.props}>
      ...
    )
  }
}

map-container.js

class MapContainer extends React.Component {
  ...
  getCoordsFromName(loc) { 
    this.map.animateToLocation({
      latitude: loc.lat,
      longitude: loc.lng,
    })
  }

  render() {
    return (
      <View style={{ flex: 1}}>
          <MyMapView ref={ref => this.map = ref} region={this.state.region}/>
          <MapInput style = {{flex: 1, position : 'absolute'}} notifyChange={loc => this.getCoordsFromName(loc)} />
      </View>
    );
  }
}

Upvotes: 2

Related Questions