react native maps onPress 标记掉落问题

react native maps onPress marker drop problem

我一直试图在触摸地图时在地图上放置一个图钉,但我不断收到错误消息: 更新由 airmap null latitude

管理的视图 属性 'region' 时出错

我已经创建常量 markerPress 并将其添加到 MapView onPress 中,然后更新 MapView.Marker

我曾尝试将标记 useState 从 null 更改为空对象,但没有成功。请帮忙。

import React, {useState, useEffect} from 'react';
import {StyleSheet} from 'react-native';
import MapView, { PROVIDER_GOOGLE } from 'react-native-maps';
import * as Location from "expo-location";




function HomeScreen({navigation}) {
    const [location, setLocation] = useState(null);
    const [mapRegion, setMapRegion] = useState(null);
    const [errorMsg, setErrorMsg] = useState(null);
    const [marker, setMarker] = useState(null)

    const markerPress = (event) => {
        setMarker({ marker: event.nativeEvent.coordinate })
    }






    useEffect(() => {
        (async () => {
            let { status } = await Location.requestPermissionsAsync();
            if (status !== "granted") {
                setErrorMsg("Permission to access location was denied");
            }

            let coordinates = await Location.getCurrentPositionAsync({});
            setLocation(location);

            setMapRegion({
                longitude: coordinates.coords.longitude,
                latitude: coordinates.coords.latitude,
                longitudeDelta: 0.0922,
                latitudeDelta: 0.0421
            });
        })();
    }, []);


    return  (
        <MapView
            provider={PROVIDER_GOOGLE}
            onPress={markerPress}
            style={{flex:1}}
            customMapStyle = { generatedMapStyle }
            showsUserLocation={true}
            followsUserLocation={true}
            showsMyLocationButton={true}
            initialRegion={mapRegion}>
            {
                marker &&
                <MapView.Marker coordinate={marker} />

            }
        </MapView>
    )
}

const styles = StyleSheet.create({
    map: {
        ...StyleSheet.absoluteFillObject
    }
})

您应该将 setMarker 调用更改为:

setMarker(event.nativeEvent.coordinate);

event.nativeEvent.coordinate 已经是 coordinate 属性的有效值。


因此传递给 coordinate 的正确对象如下所示:

{
  latitude: ...,
  longitude: ...
}

你通过了这个:

{
  marker: {
    latitude: ...,
    longitude: ...
  }  
}