如何使用反应本机地图视图将两个标记居中



我在两个不同的坐标上得到了两个标记。

人们通常如何使两个标记居中,以便您可以在地图上同时看到两个标记,无论它们有多远。

<MapView 
ref={ (map)=> this.map = map}
initialRegion={this.state.init} 
style={css.map}>    
    { this.state.marker1 !==0 && <MapView.Marker 
        coordinate={{
            'latitude':this.state.marker1.lat,
            'longitude':this.state.marker1.lng}}
        />}
    { this.state.marker2 !==0 && <MapView.Marker 
        coordinate={{
            'latitude':this.state.marker2.lat,
            'longitude':this.state.marker2.lng}}
        />}
</MapView>
您可以使用

MapViewfitToSuppliedMarkersfitToCoordinates方法。https://github.com/react-native-community/react-native-maps/blob/master/docs/mapview.md

对于像我这样遇到这种情况的人来说,你需要的是来自MapView的fitToSuppliedMarkers,从Marker identifiers。下面是一个示例:https://github.com/react-native-maps/react-native-maps/blob/master/example/src/examples/FitToSuppliedMarkers.tsx

您需要在 ComponentDidMount 或 useEffect 中使用 MapView 的 fitToSuppliedMarker 或 fitToT坐标方法,并确保将其放入 setTimeout 中,否则会导致性能问题。

useEffect(() => {
if (!destination) return;
setTimeout(() => {
  mapRef?.current?.fitToSuppliedMarkers(["destination", "origin"], {
    edgePadding: { top: 70, right: 70, bottom: 70, left: 70 },
  });
}, 500);
// console.log("2", destination);
  }, [origin, destination]);

注意边缘填充仅是谷歌地图https://github.com/react-native-maps/react-native-maps/blob/master/docs/mapview.md

最新更新