React-Native-Maps fits Coordinate right after being loaded
Asked Answered
R

2

5

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 ?

Redfield answered 31/1, 2017 at 0:27 Comment(0)
F
11

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

Fishbein answered 11/2, 2017 at 15:21 Comment(0)
D
4

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>
    }
Dallasdalli answered 5/3, 2020 at 18:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.