react-native-maps: fitToElements not working

in componentDidMount i set fitToElements(true) but the map doesn’t fit all markers to screen. Here my code:

componentDidMount(){
		let _markers = [];
		for (let i = 0; i < this.props.locations.length; i++) {
			let _placeMarker = {
				coordinate : {
					latitude: this.props.locations[i].latitude,
					longitude: this.props.locations[i].longitude
				},
				title: this.props.locations[i].name,
				color: 'blue',
				key: i + 1
			};
			_markers.push(_placeMarker);
		};
		this.setState({
      region: {
        latitude: this.props.locations[0].latitude,
        longitude: this.props.locations[0].longitude,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA
      },
      markers: _markers
    });
    this.refs.map.fitToElements(true);
}

And in the render()

                           <View>
   		      	<MapView
   		        	ref="map"
   		          provider={this.props.provider}
   		          style={styles.map}
   		          initialRegion={this.state.region}
   		          loadingEnabled={true}
   		          onPress={(e) => this.onMapPress(e)}
   		        >
   		          {this.state.markers.map(marker => (
   		            <MapView.Marker
   		              title={marker.title} 
   		              key={marker.key}
   		              coordinate={marker.coordinate}
   		              pinColor={marker.color}
   		            />
   		          ))}
   		        </MapView>
   		      </View>

But my map screen only show the initialRegion marker, i must zoom out the map to show all markers map1 I want to the map look like: map2

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 1
  • Comments: 16 (1 by maintainers)

Most upvoted comments

ref works for me on both Android and iOS

<MapView
      ref={mapRef => mapRef===null ? null : mapRef.fitToElements(true) }
      style={styles.map}
      region={region}
      showsUserLocation
      showsMyLocationButton
>
      { this.renderMarkers() }
</MapView>

try this

let markers = [];
		for (let i = 0; i < this.props.locations.length; i++) {
			let placeMarker = {
				latitude: this.props.locations[i].latitude,
				longitude: this.props.locations[i].longitude
				title: this.props.locations[i].name,
				key: i + 1
			};
			markers.push(placeMarker);
		};
<MapView
 ref={(ref) => { this.mapRef = ref; }}
onLayout={() => this.mapRef.fitToCoordinates(this.markers, { edgePadding: { top: 50, right: 10, bottom: 10, left: 10 }, animated: false })} >

I have the same problem… But fitToCoordinates is working!

I am having the same issue as @alvelig , fitToSuppliedMarkers works perfectly on iOS but fails on Android.

 componentDidMount() {

    this.mapRef.fitToSuppliedMarkers(
         ['hotel', '0'],
         false,
       );
  }

Using a timeout like @alvelig works as a quick fix for the time being, does anyone know of a more robust solution?