React-Native-Maps在加载后适配坐标。

5

在GitHub上的react-native-maps仓库提供的示例中,展示了一个按钮来执行函数,根据标记列表设置适当的缩放:

  fitAllMarkers() {
    this.map.fitToCoordinates(MARKERS, {
      edgePadding: DEFAULT_PADDING,
      animated: true,
    });
}

https://github.com/airbnb/react-native-maps/blob/master/docs/mapview.md

如果已经初始化了一个标记点数组,能否使用适当的坐标显示来初始化地图?

当尝试在componentDidMount中设置正确的适应大小时,我收到以下错误信息:

Error using new LatLntBounds(LatLngBounds, int): Map size can't be 0. Most likely, layout has not yet occured for the map view

显然,在调用我的fitAllMarkers()函数之前太早了。是否有一个onLoad函数可以在地图初始化后立即触发?

2个回答

10

fitToCoordinates 不使用标记,而是使用经纬度对象数组(有一个特定的方法 fitToSuppliedMarkers 用于此)。使其正常工作的重要一点是提供对内部 MapView 的引用,以获取地图的引用。

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>
    }
}

我在这里留下代码,供以后来到这里的人参考。这是我回答仓库问题与https://github.com/airbnb/react-native-maps/issues/1003中重复的内容。

此外,任何来到这里的人都请查看地图视图文档的更新:https://github.com/airbnb/react-native-maps/blob/master/docs/mapview.md


4

当我使用onLayout属性时,将地图适应到所需坐标上需要太长时间。

我更喜欢使用onMapReady属性,在完全加载之前将地图适应到坐标。

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>
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接