Zoom to specified markers react-native-maps

Luke Berry picture Luke Berry · Sep 19, 2016 · Viewed 16.7k times · Source

There is a section in the react-native-maps docs for zooming to an array of markers, however there are no code examples on how to do this either in the docs or in the examples folder (from what I can find)

Can anyone provide an example of how to do this?

Answer

Lokeh picture Lokeh · Sep 27, 2016

In the MapView component docs, there are a few methods: fitToElements, fitToSuppliedMarkers and fitToCoordinates. https://github.com/airbnb/react-native-maps/blob/master/docs/mapview.md#methods

If you want to zoom the map in on some collection of markers on load, you can use componentDidMount to zoom in after the initial render:

class SomeView extends Component {
    constructor() {
      this.mapRef = null;
    }

    componentDidMount() {
      this.mapRef.fitToSuppliedMarkers(
        someArrayOfMarkers,
        false, // not animated
      );
    }

    render() {
      <MapView
        ref={(ref) => { this.mapRef = ref }}
      >
        { someArrayOfMarkers }
      </MapView>
    }
}