在获取当前位置后无法设置初始区域

时间:2019-12-05 23:17:32

标签: reactjs react-native react-hooks react-native-maps

我正在将功能组件与Hooks配合使用,并且正在获取用户当前位置,并将其分配给MapView initialRegion,但该组件不会重新呈现。

我试图将引用refMapView组件一起使用来调用animateToRegion(),但是它不起作用。

有什么我想念的吗?

这是我的代码示例:

import React, { useState, useEffect, useRef } from 'react';
import { View, Text, Image, Platform, ScrollView, ActivityIndicator } from 'react-native';
import { DateMenu, Dropdown, DropdownTextInput, InputField} from '../../../GlobalReusableComponents/TextFields';
import { Space } from '../../../GlobalReusableComponents/Separators';
import { Button } from 'react-native-elements';
import axios from 'axios';
import MapView, { Marker } from 'react-native-maps';
import useReverseGeocoding from '../../../context/useReverseGeocoding';
import useCurrentLocation from '../../../context/useCurrentLocation';
import { getLocationAsync } from '../../../util/getCurrentLocation';
import { textStyles, buttonStyles } from '../../../globalStyles/styles';
import EStyleSheet from 'react-native-extended-stylesheet';

const latitudeDelta = 0.025
const longitudeDelta = 0.025

const JobLocationScreen = (props) => {
    const [region, setRegion] = useState({
        latitude: 38.907192,
        longitude: -30.036871,
        latitudeDelta,
        longitudeDelta
    });
    const [latitude, setLatitude] = useState(null);
    const [longitude, setLongitude] = useState(null);
    const [reverseGeocodingApi, reverseGeocodingdata, isReverseGeacodingDone, reverseGeocodingErrorMessage] = useReverseGeocoding();
    let mapRef = useRef(null);

    useEffect(() => {
        getYourCurrentLocation();
    },
    [])

    useEffect(() => {
        animateToRegion();
    },
    [region])

    const onMapReady = () => {
        if(!isMapReady) {
            setIsMapReady(true);
        }
    };

    const getYourCurrentLocation = async () => {
        const { location } = await getLocationAsync();
        console.log(location);
        setRegion(region);
    }

    const onRegionChangeComplete = (selectedRegion) => {
        setRegion(selectedRegion);
        reverseGeocodingApi(selectedRegion);
    }

    const animateToRegion = () => {
        mapRef.animateToRegion(region, 1000);
    }

    const onNextButtonPress = () => {
        props.navigation.state.params.setSelectedValue(jobTags);
        props.navigation.pop();
    }

    const _renderMapWithFixedMarker = () => {
        return (
            <View style={{flex: 1}}>
                <MapView
                    ref={ref => {
                        mapRef = ref
                    }}
                    onMapReady={onMapReady}
                    style={styles.map}
                    initialRegion={region}
                    onRegionChangeComplete={(selectedRegion) => onRegionChangeComplete(selectedRegion)}
                />
                <View style={styles.pinBadge}>
                    <Text
                        style={{color: EStyleSheet.value('$primaryDarkGray')}}
                    >
                        Move to choose Location
                    </Text>
                </View>
                <View style={styles.markerFixed}>
                    <Image style={styles.marker} source={require('../../../assets/pin.png')} />
                </View>
            </View>
        );
    }

    return (
        <View style={styles.container}>
            <View 
                pointerEvents='none'
                style={styles.inputFieldContainer}
            >
                <InputField
                    maxLength={35}
                    placeholder='Selected Address'
                    value={isReverseGeacodingDone? reverseGeocodingdata.results[0].formatted_address : 'Loading ...'}
                />
            </View>
            {_renderMapWithFixedMarker()}
            <View style={styles.bodyContainer}>
                <View style={styles.buttonContainer}>
                    <Button
                        title="Confirm Your Location"
                        buttonStyle={buttonStyles.button}
                        onPress={() => onNextButtonPress()}
                    />
                </View>
            </View>
        </View>
    );
}

JobLocationScreen.navigationOptions = ({navigation}) => {
    return {
        title: 'Select your Location'
    }; 
};

export default JobLocationScreen;

const styles = EStyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '$primaryBackgroundColor'
    },
    inputFieldContainer: {
        backgroundColor: '#f8f9f9', 
        paddingVertical: 20,
        paddingHorizontal: 20
    },
    map: {
        flex: 1
    },
    pinBadge: {
        position: 'absolute',
        paddingVertical: 10,
        paddingHorizontal: 15,
        top: '38%',
        alignSelf: 'center',
        borderRadius: 25,
        backgroundColor: '#ffffff',
        shadowColor: '#acaeb4',
        shadowOffset: {
            width: 0,
            height: 3,
        },
        shadowOpacity: 0.5,
        shadowRadius: 5,

        elevation: 5
    },
    markerFixed: {
        left: '50%',
        marginLeft: -10,
        marginTop: -6,
        position: 'absolute',
        top: '50%'
    },
    marker: {
        width: 20, 
        height: 41
    },
    bodyContainer: {
        marginHorizontal: 20
    },
    buttonContainer: {
        position: 'absolute', 
        bottom: 20,
        width: '100%'
    }
})

2 个答案:

答案 0 :(得分:1)

您需要使用refname.current访问ref才能访问该值。

 <MapView ref={mapRef}

,然后在要访问它时,使用.current

const animateToRegion = () => {
   mapRef.current.animateToRegion(region, 1000);
}

请参见docs

Conceptual Demo

答案 1 :(得分:0)

react-native-maps-super-cluster

 <MapView ref={mapRef}

const animateToRegion = () => {
   mapRef.current.getMapRef().animateToRegion(region, 1000);
}