React Native 地图标注渲染

Onu*_*ker 5 javascript google-maps react-native react-native-maps

我用来react-native-maps显示我所在地区火车站的标记。每个标记都有一个标注,其中包含接近列车的实时数据。

问题是;对于地图上的每个标记,每个标注都会在后台渲染。此外,当我从实时 API 获得新数据时,每个标注都会被重新渲染。即使我只需要按下的标记的标注,这也会导致呈现数百个视图。应用程序截图

有没有办法确保在用户按下特定标记之前不会渲染标注?新闻发布后;我还想确保仅渲染和显示特定标记的标注。

我的代码:

地图屏幕:

const MapScreen = props => {
  // get user location from Redux store
  // this is used to center the map
  const { latitude, longitude } = useSelector(state => state.location.coords)

  // The MapView and Markers are static
  // We only need to update Marker callouts after fetching data
  return(
    <SafeAreaView style={{flex: 1}}>
    <MapView
        style={{flex: 1}}
        initialRegion={{
          latitude:  parseFloat(latitude) || 37.792874,
          longitude: parseFloat(longitude) || -122.39703,
          latitudeDelta: 0.06,
          longitudeDelta: 0.06
        }}
        provider={"google"}
      >
        <Markers />
      </MapView>
      </SafeAreaView>
  )
}

export default MapScreen
Run Code Online (Sandbox Code Playgroud)

标记组件:

const Markers = props => {
  const stationData = useSelector(state => state.stationData)

  return stationData.map((station, index) => {
    return (
      <MapView.Marker
        key={index}
        coordinate={{
          // receives station latitude and longitude from stationDetails.js
          latitude: parseFloat(stationDetails[station.abbr].gtfs_latitude),
          longitude: parseFloat(stationDetails[station.abbr].gtfs_longitude)
        }}
        image={stationLogo}
        zIndex={100}
        tracksInfoWindowChanges={true}
      >
        <MapView.Callout
          key={index}
          tooltip={true}
          style={{ backgroundColor: "#ffffff" }}
        >
          <View style={styles.calloutHeader}>
            <Text style={{ fontWeight: "bold" }}>{station.name}</Text>
          </View>
          <View style={styles.calloutContent}>
            <StationCallout key={index} station={stationData[index]} />
          </View>
        </MapView.Callout>
      </MapView.Marker>
    );
  });
};
Run Code Online (Sandbox Code Playgroud)

StationCallout 组件:

const StationCallout = (props) => {
  return(
    props.station.etd.map((route, index) => {
      const approachingTrains = function() {
        trainText = `${route.destination} in`;

        route.estimate.map((train, index) => {
          if (index === 0) {
            if (train.minutes === "Leaving") {
              trainText += ` 0`;
            } else {
              trainText += ` ${train.minutes}`;
            }
          } else {
            if (train.minutes === "Leaving") {
              trainText += `, 0`;
            } else {
              trainText += `, ${train.minutes}`;
            }
          }
        });

        trainText += " mins";

        return <Text>{trainText}</Text>;
      };

      return <View key={index}>
      {approachingTrains()}
      </View>;
    })
  )
};

export default StationCallout
Run Code Online (Sandbox Code Playgroud)

Onu*_*ker 0

其实我自己也找到了答案。我创建了对每个标记的引用,然后将 onPress 属性传递给 <MapView.Marker> 并将 showCallout 属性传递给其 Callout 组件。

标记组件:

export default function Markers() {
  const {
    stations: { station }
  } = require("../../bartData/stations");

  const [clickedMarkerRef, setClickedMarkerRef] = useState(null)

  return station.map((trainStation, index) => {
    return (
      <MapView.Marker
        key={trainStation.abbr}
        coordinate={{
          latitude: parseFloat(trainStation.gtfs_latitude),
          longitude: parseFloat(trainStation.gtfs_longitude)
        }}
        image={Platform.OS === "ios" ? station_ios : station_android}
        zIndex={100}
        tracksInfoWindowChanges={true}
        onPress={() => setClickedMarkerRef(index)}
      >
        <CalloutContainer
          key={trainStation.abbr}
          stationName={trainStation.name}
          stationAbbr={trainStation.abbr}
          showCallOut={clickedMarkerRef === index}
        />
      </MapView.Marker>
    );
  });
}
Run Code Online (Sandbox Code Playgroud)

Callout 组件仅在 showCallOut 为 true 时获取数据。 在标注组件中

useEffect(() => {
    if (props.showCallOut === true) {
      fetchTrainDepartures();

      const intervalId = setInterval(fetchTrainDepartures, 10000);
      return () => clearInterval(intervalId);
    }
  }, []);
Run Code Online (Sandbox Code Playgroud)

因此,除非您单击标记,否则本地状态将保持为 null 并且标注不会获取任何数据。

当您单击索引 0 处的标记时:

  • clickedMarkerRef 现在为 0。
  • showCallout 为 true => {clickMarkerRef === 索引}
  • 在 useEffect hook 下的 Callout.js 文件上 => props.showCallout 为 true。
  • 仅针对此标注获取数据。