Исходный регион React native не обновляется с состоянием

#react-native #geolocation #react-native-maps

#react-native #геолокация #react-native-maps

Вопрос:

У меня есть база кода ниже

  componentDidMount() {
        //firebase.firestore().collection('locations').doc('test').set({ test: 'test' })

        Geolocation.getCurrentPosition(
            (position) => {
                if (position) {

                    this.setState({
                      region: {
                        latitude: Number(position.coords.latitude),
                        longitude: Number(position.coords.longitude),
                        latitudeDelta: 0.003,
                        longitudeDelta: 0.003,
                      },
                    });
                  }
                  alert(JSON.stringify(this.state.region))
            },
            (error) => alert(JSON.stringify(error)),
            { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 100 }
        );
        this.unsubscribe = this.locationRef.onSnapshot(this.getCollectionData);
       // firebase.firestore().collection("locations").get().then(QuerySnapshot => {  });
    }
 

И карта

   render() {
        return (<View style={{
            flex: 1,
            flexDirection: 'column',
          }}>
            <HeaderNavigationBar {...this.props} />
            <MapView showsUserLocation={true}
                // ref={map => this.map = map}
                initialRegion={this.state.region}
                style={styles.container}
            >
                {this.state.AllLocations.map((marker, index) => (
                    <MapView.Marker key={index}
                        coordinate={marker.locations.coords}
                        title={marker.Title}
                    />
                ))}
            </MapView>
          </View>);

    }
 

componentDidMount корректно обновляет состояние, но карта не показывает правильное положение, она принимает то, что было задано при построении

 constructor(props) {
        super(props);
        this.locationRef = firebase.firestore().collection('locations');
        this.unsubscribe = null;
        this.state = {
            isLoading: true,
            AllLocations: [],
            region: {
                latitude: 0,
                longitude: 0,
                latitudeDelta: 0.003,
                longitudeDelta: 0.003,
            }
        };
    }
 

Пожалуйста, помогите

Спасибо

Ответ №1:

initialRegion используется для первоначального отображения карты. В вашем случае вы получаете местоположение пользователя после рендеринга карты, поэтому оно не обновляется.

Чтобы противостоять этому, есть два способа.

1. используйте состояние загрузки, пока не получите местоположение использования, и предотвратите отображение карты до получения местоположения.

2: Используйте region , например region = {this.state.region} .

 <MapView showsUserLocation={true}
                // ref={map => this.map = map}
                initialRegion={this.state.region}
                region={this.state.region}
                style={styles.container}
            >
                {this.state.AllLocations.map((marker, index) => (
                    <MapView.Marker key={index}
                        coordinate={marker.locations.coords}
                        title={marker.Title}
                    />
                ))}
            </MapView>
 

Оба будут работать, это зависит от вашего варианта использования.

Комментарии:

1. Я добавил region={this.state.region}, но все равно никакого эффекта

2. Вероятно, проблема связана с местоположением, убедитесь, что вы получаете местоположение для своего API геолокации, оно плохо работает на многих телефонах, и вы можете попробовать состояние загрузки, пока не получите местоположение.

3. Я правильно получаю геолокацию, которую я проверил, разместив предупреждение

4. Да, добавление свойства region не работает. Местоположение фиксируется правильно. Кто-нибудь нашел ответ на эту проблему?

Ответ №2:

Попробуйте это

 {this.state.region ? (<MapView


                    style={[styles.map]}
                    initialRegion={this.state.region}
                    region={this.state.region}


                    provider={PROVIDER_GOOGLE}


                >


                    {this.state.AllLocations.map((marker, index) => (
                    <MapView.Marker key={index}
                        coordinate={marker.locations.coords}
                        title={marker.Title}
                    />
                ))}
                </MapView>) : (
                        <MapView
                            loadingEnabled={true}
                            style={styles.map}
                            showsMyLocationButton={true}
                            provider={PROVIDER_GOOGLE}
                            style={[styles.map]}
                        >
                        </MapView>
                    )
                }
 

Заданный region: null в конструкторе, он будет работать

Комментарии:

1. Это работает. Я создал отдельную функцию и сделал это.