React-Native-Maps fits Coordinate right after being loaded

13,803

Solution 1

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

Solution 2

When I use the onLayout prop it takes too long on fit the map to the desired coordinates.

I would prefer the onMapReady prop which fit the map to the coordinates before loads it completely.

render() {
      return (
        <MapView style={{flex: 1}}
           ref={(ref) => { this.mapRef = ref }}
           onMapReady = {() => this.mapRef.fitToCoordinates(this.props.myLatLongs, { edgePadding: { top: 10, right: 10, bottom: 10, left: 10 }, animated: false })}>
           /** ... */
        </MapView>
    }
Share:
13,803

Related videos on Youtube

Arkon
Author by

Arkon

Updated on June 04, 2022

Comments

  • Arkon
    Arkon almost 2 years

    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 ?