24

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?

Luke Berry
  • 1,927
  • 4
  • 19
  • 32
  • 1
    https://github.com/airbnb/react-native-maps/blob/master/example/examples/FitToSuppliedMarkers.js this seems to be an example of Zoom to Array. – Frank Phillips Sep 26 '16 at 15:15

1 Answers1

45

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>
    }
}
lilactown
  • 1,008
  • 11
  • 9
  • Thank you for this, but how would I change the zoom distance? Currently it is so far zoomed out all of the markers appear to be on top of each other. – Luke Berry Sep 28 '16 at 05:56
  • 9
    Ignore my previous comment, I'm an idiot. Thanks again. – Luke Berry Sep 28 '16 at 06:26
  • @denisw you pass latitudeDelta and longitudeDelta to the coords object, a value of 0.02 for both equals a few blocks. – razor7 Dec 13 '17 at 15:48
  • 1
    what is someArrayOfMarkers here..? @luke Berry – Anant kamat Jan 31 '19 at 12:14
  • 2
    @LukeBerry someArrayOfMarkers should look like: [ {latitude: 36.193852, longitude: 43.964365}, {latitude: 36.170168, longitude: 44.02348}, {latitude: 36.202618, longitude: 44.035115} ] – Muho May 05 '19 at 22:23
  • This doesn't zoom for me though. It just centers the map around the markers. How do you make it actually zoom in or out to fit all the markers on the screen? – Luke Ehresman Aug 14 '19 at 20:58
  • @LukeEhresman just add on the `` the `initialRegion={{ latitude: 0, longitude: 0, latitudeDelta: 0.015, longitudeDelta: 0.0121, }}` With your own values, this sets the initial zoom and after the markers are loaded the script will fit them – user3585918 Nov 12 '19 at 18:09