显示 MapView 时,标记未在安装上渲染

问题描述 投票:0回答:1

问题

我试图在地图上显示标记,但在初始安装时没有显示标记。

背景

当我注释掉并在 useEffect 挂钩中时,地图将动画到初始区域并也显示标记。

但是,之后我将尝试在初始安装时引入 useEffect - 我最终会得到相同的视图(缩小后没有标记)。我尝试调整安装的时间并设置一个状态以仅在地图渲染后加载动画,但无法解决问题

import React, { useRef, useEffect, useState } from 'react';
import { StyleSheet, View } from "react-native";
import MapView, { Marker } from "react-native-maps";
import Constants from "expo-constants";

export default function Map() {
  const mapRef = useRef<MapView | null>(null);
  const [isMapReady, setIsMapReady] = useState(false);

  const initialRegion = {
    latitude: -33.44579692321098, 
    longitude: 151.20927099608833,
    latitudeDelta: 0.05,
    longitudeDelta: 0.05,
  };

  // Test marker position - slightly offset from initial region for visibility
  const testMarkerPosition = {
    latitude: initialRegion.latitude + 0.01,
    longitude: initialRegion.longitude + 0.01,
  };

  useEffect(() => {
    if (isMapReady && mapRef.current) {
      // Only animate when map is ready
      mapRef.current.animateToRegion(initialRegion, 1000);
    }
  }, [isMapReady]);

  const handleMapReady = () => {
    setIsMapReady(true);
  };

  return (
    <View style={styles.container}>
      <MapView
        ref={mapRef}
        provider="google"
        style={styles.map}
        initialRegion={initialRegion}
        showsUserLocation={true}
        showsMyLocationButton
        zoomEnabled={true}
        minZoomLevel={10}
        maxZoomLevel={20}
        moveOnMarkerPress={false}
        onMapReady={handleMapReady}
      >
        {isMapReady && (
          <Marker
            coordinate={testMarkerPosition}
            title="Test Location"
            description="This is a test marker"
          />
        )}
      </MapView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  map: {
    width: "100%",
    height: "100%",
  },
});

react-native react-hooks mount react-native-maps
1个回答
0
投票

我认为你的情况有问题

{isMapReady && (
  <Marker
    coordinate={testMarkerPosition}
    title="Test Location"
    description="This is a test marker"
/>}

尝试在这里摆脱 isMapReady 条件。

© www.soinside.com 2019 - 2025. All rights reserved.