【问题标题】:Mapbox React Native accessing map methodMapbox React Native 访问地图方法
【发布时间】:2022-08-19 00:51:52
【问题描述】:

我在 React Native 中使用 MapboxMapboxGL.MapView 对象的文档列出了几种方法,但我无法使用它们。例如,getVisibleBounds() 据说是这样工作的:

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

我已经这样实现了:

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

onRegionDidChange 函数定义为:

const mapRef = useRef();

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

这样做会给:mapRef.getVisibleBounds is not a function.

地图本身工作正常,我想我只是不确定使用该功能的正确方法。我也尝试过使用this._map.getVisibileBounds(),但这给出了:

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

我在这里和 Github 上看到过类似的问题,但是它们要么没有答案,要么已经过时。

    标签: react-native mapbox mapbox-gl-js mapbox-gl react-native-mapbox-gl


    【解决方案1】:

    我设法通过使用文档中提供的examples 来解决这个问题。

    首先是使用类组件而不是功能组件,那么MapView中的ref应该指定为ref={c =&gt; (this._map = c)},如下所示:

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

    最后将this 绑定到类构造函数中的函数:

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

    方法本身定义如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多