react-nativegoogle-mapsdirections

How to fit the map in a destination point with MapViewDirections on react native?


How to fit the map in a destination point? I just need to fit the camera to the destination point, not to both coordinates (initial and destination like today). How do I do this? Another way to fit the coordinates to this?

{destination && (
  <Fragment>
    <Directions
      origin={region}
      destination={destination}
      onReady={result => {
        this.setState({ duration: Math.floor(result.duration) });
        this.mapView.fitToCoordinates(result.coordinates, {
          edgePadding: {
            right: getPixelSize(10),
            left: getPixelSize(10),
            top: getPixelSize(10),
            bottom: getPixelSize(50),
          },
          animated: true,
        });
      }}
    />
    <Marker
      onPress={this.pickLocationHandler}
      coordinate={destination}
      centerOffset={{ x: -18, y: -60 }}
      anchor={{ x: 0, y: 0 }}
    //opacity={0.6}
    >
      <LocationBox>
        <LocationText>{destination.title}</LocationText>
      </LocationBox>
    </Marker>
    <Marker
      coordinate={region}
      anchor={{ x: 0, y: 0 }}
      onPress={this.pickLocationHandler}>
      <LocationBox>
        <LocationTimeBox>
          <LocationTimeText>{duration}</LocationTimeText>
          <LocationTimeTextSmall>
            Tempo de Viagem
          </LocationTimeTextSmall>
        </LocationTimeBox>
        <LocationText>{location}</LocationText>
      </LocationBox>
    </Marker>
  </Fragment>
)}

It would be nice if anyone has some code that works together with GooglePlacesAutocomplete.


Solution

  • Assuming that you're using react-native-maps, you can use these methods:

    animateToRegion: takes two params:

    // focus on NYC
    
    this.mapView.animateToRegion({
      latitude: 40.730610,
      longitude: -73.935242,
      latitudeDelta: 0.026,
      longitudeDelta: 0.027,
    }, 2000)
    

    fitToCoordinates: takes two params:

    // focus on NYC
    
    this.mapView.animateToRegion([{
      latitude: 40.730610,
      longitude: -73.935242,
    }], {
      edgePadding: {
        top: 20,
        right: 20,
        bottom: 20,
        left: 20,
      },
      animated: true,
    })
    

    These methods need to be called on the ref to the your map, like how you do in your code example: this.mapView.fitToCoordinates(...)

    There are a bunch of methods that you can use to fit the camera to a destination point, potentially better suited to your use case than what I've described above. Check the RN Maps docs for more info.