Santa
Santa

Reputation: 21

Mapbox React Native accessing map method

I am using Mapbox in React Native and the documentation of the MapboxGL.MapView object lists several methods, but I am unable to use them. For example, getVisibleBounds() is said to work like this:

const visibleBounds = await this._map.getVisibleBounds();

I have implemented it like this:

<View style={container}>
    <Mapbox.MapView
        ref={mapRef}
        styleJSON={JSON.stringify(defaultStyle)}
        zoomLevel={16}
        centerCoordinate={[lat, lng]}
        onRegionDidChange={onRegionDidChange}
        style={{ flex: 1 }}
    >
    </Mapbox.MapView>
</View>

The onRegionDidChange function is defined as:

const mapRef = useRef();

const onRegionDidChange = async () => {
    try {
        const currentBounds = await mapRef.getVisibleBounds();
        console.log(currentBounds);
    } catch (error) {
        console.warn(error);
    }
};

Doing this gives: mapRef.getVisibleBounds is not a function.

The map itself works fine, I guess I am just unsure of the correct way to use the function. I have also tried using this._map.getVisibileBounds(), but this gives:

undefined is not an object (evaluating '_this.map.getVisibleBounds')

I have seen similar questions asked on here and Github, however they are either unanswered or outdated.

Upvotes: 1

Views: 923

Answers (1)

Santa
Santa

Reputation: 21

I managed to figure this out by using the examples provided in the documentation.

I used a class component, then the ref in MapView should be specified as ref={c => (this._map = c)} like this:

<Mapbox.MapView
    ref={c => (this._map = c)}
    styleJSON={JSON.stringify(defaultStyle)}
    zoomLevel={16}
    centerCoordinate={[lat, lng]}
    onRegionDidChange={this.onRegionDidChange}
    style={{ flex: 1 }}
>

And finally bind this to your function in the class constructor:

constructor(props) {
    this.onRegionDidChange = this.onRegionDidChange.bind(this);
}

The method itself is defined as follows:

async onRegionDidChange() {
    try {
        const currentBounds = await this._map.getVisibleBounds();
        console.log(currentBounds);
    } catch (error) {
        console.warn(error);
    }
}

Edit: for a functional component, just create a variable let mapRef = null; and specify the ref as: ref={(c) => (mapRef = c)} then the function as:

let getBounds = async () => {
    try {
        const bounds = await map.getVisibleBounds();
        console.log(bounds);
    } catch (error) {
        console.warn(error);
    }
};

Upvotes: 1

Related Questions