Мне нужно, чтобы получить текущее местоположение с помощью GPS программно в исходном режиме. Как я могу добиться этого? - PullRequest
0 голосов
/ 19 апреля 2020

Я использую карты реакции и геолокации. Я установил широту и долготу на

const LATITUDE = 37.78825;
const LONGITUDE = -122.4324

, когда мое приложение запускается и вызывается функция this.watchlocation. Широта и долгота меняются в моей текущей позиции, поэтому работает componentDidupdate, и сообщение отправляется на pubnub ... Но когда я путешествую на некоторое расстояние. Компонент Обновление не вызвано .. сколько я предполагаю пройти расстояние, чтобы снова отправить сообщение в PubNub. Я использую expo ~ 37.0.3 и "response-native-maps": "0.27.1"

  • Вот пример кода для этого

MAP. js

import MapView, { Marker, AnimatedRegion } from 'react-native-maps';

import PubNub from "pubnub";
const { width, height } = Dimensions.get('window');

const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;

const pubnub = new PubNub({
  subscribeKey: "demo",
  publishKey: "demo",
  uuid: "myUUIDv"
});

export default class Trackee extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      latitude: LATITUDE,
      longitude: LONGITUDE,
      coordinate: new AnimatedRegion({
        latitude: LATITUDE,
        longitude: LONGITUDE,
        latitudeDelta: 0,
        longitudeDelta: 0,
      }),
    };



  }

  componentDidMount() {
    this.watchLocation();
  }

  componentDidUpdate(prevProps, prevState) {



    if (this.state.latitude !== prevState.latitude) {
      pubnub.publish({
        message: {
          latitude: this.state.latitude,
          longitude: this.state.longitude,
        },
        channel: 'location',
      });
    }
  } 

  componentWillUnmount() {
    navigator.geolocation.clearWatch(this.watchID);
  }

  watchLocation = () => {
    const { coordinate } = this.state;

    this.watchID = navigator.geolocation.watchPosition(
      position => {
        const { latitude, longitude } = position.coords;

        const newCoordinate = {
          latitude,
          longitude,
        };

        if (Platform.OS === 'android') {
          if (this.marker) {
            coordinate.timing(newCoordinate).start(); // 500 is the duration to animate the marker
          }
        } else {
          coordinate.timing(newCoordinate).start();
        }

        this.setState({
          latitude,
          longitude,
        });
      },
      error => console.log(error),
      {
        enableHighAccuracy: true,
        timeout: 20000,
        maximumAge: 1000,
        distanceFilter: 0,
      }
    );
  };

  getMapRegion = () => ({
    latitude: this.state.latitude,
    longitude: this.state.longitude,
    latitudeDelta: LATITUDE_DELTA,
    longitudeDelta: LONGITUDE_DELTA,
  });



  render() {
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={styles.container}>
          <MapView style={styles.map} showUserLocation followUserLocation loadingEnabled region={this.getMapRegion()}>
            <Marker.Animated
              ref={marker => {
                this.marker = marker;
              }}
              coordinate={this.state.coordinate}

            />



        </MapView>

        </View>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  map: {
    ...StyleSheet.absoluteFillObject,
  },
});

1 Ответ

0 голосов
/ 19 апреля 2020

https://www.npmjs.com/package/react-native-get-location

вы можете попробовать использовать этот пакет для динамического получения текущего значения long long

...