React-Native-Maps fits Coordinate right after being loaded

Arkon picture Arkon · Jan 31, 2017 · Viewed 10.2k times · Source

The example provided in the examples of the react-native-maps repo on GitHub shows a button to execute a function to set the appropriate zoom considering to a list of markers:

  fitAllMarkers() {
    this.map.fitToCoordinates(MARKERS, {
      edgePadding: DEFAULT_PADDING,
      animated: true,
    });
}

https://github.com/airbnb/react-native-maps/blob/master/docs/mapview.md

Would it be possible to initialize the map with the appropriate fit given an array of markers already initialized ?

When trying to set the right fit on the componentDidMount, I am receiving:

Error using new LatLntBounds(LatLngBounds, int): Map size can't be 0. Most likely, layout has not yet occured for the map view.

It is definitively too early to call my fitAllMarkers() function. Is there a onLoad function that can be triggered right after the map was initialized ?

Answer

Kanekotic picture Kanekotic · Feb 11, 2017

fitToCoordinates does not use markers it uses an array of latitude and longitude objects (there is a specific method for that fitToSuppliedMarkers). An important thing to make it work is to give a reference to the internal MapView, to get the reference to the map.

class Map extends Component {

    constructor() {
        super()
        this.mapRef = null;
    }

    render() {
      return    <MapView style={{flex: 1}}
                    ref={(ref) => { this.mapRef = ref }}
                    onLayout = {() => this.mapRef.fitToCoordinates(this.props.myLatLongs, { edgePadding: { top: 10, right: 10, bottom: 10, left: 10 }, animated: false })}>
                    <Polyline coordinates={this.props.myLatLongs} strokeWidth={4} strokeColor="#2962FF" /> 
                </MapView>
    }
}

I leave the code here for future people that arrive to this place. this is duplicated of my answer also in the issue of the repo https://github.com/airbnb/react-native-maps/issues/1003 .

Also anyone arriving here please see updates in documentation for mapview: https://github.com/airbnb/react-native-maps/blob/master/docs/mapview.md