根据用户的当前位置在 Mapview 中绘制折线?

Draw polylines in Mapview based on the current location of the user?

该应用会更新用户的位置,每当它更新时,我希望它创建一条路径(多段线),以便用户可以查看他们之前去过的路径。我怎样才能做到这一点?每当调用 onRegionChange 时,它应该添加一条折线。

constructor(props) {
    super(props);

    this.state = {
      latitude: null,
      longitude: null,
      error: null
    };
  }

  componentDidMount() {
    this.watchId = navigator.geolocation.watchPosition(
      (position) => {
        let region = {
          latitude:       position.coords.latitude,
          longitude:      position.coords.longitude,
          latitudeDelta:  0.00922*1.5,
          longitudeDelta: 0.00421*1.5
        }
        let coordinates = [
          {latitude: position.coords.latitude, longitude: position.coords.longitude}
        ]
        this.onRegionChange(region, region.latitude, region.longitude);
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 10 },
    );
  }

  onRegionChange(region, lastLat, lastLong) {
    this.setState({
      mapRegion: region,
      lastLat: lastLat || this.state.lastLat,
      lastLong: lastLong || this.state.lastLong
    });
  }

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

  render() {
    return (
      <View style={styles.container}>
        <MapView
          style={styles.map}
          region={this.state.mapRegion}
          followUserLocation={true}
          onRegionChange={this.onRegionChange.bind(this)}>
          <MapView.Marker
            coordinate={{
              latitude: (this.state.lastLat) || -36.82339,
              longitude: (this.state.lastLong) || -73.03569,
            }}
            title = {"You are here"}
            description = {"Hi there!"}
          />
        </MapView>
      </View>
    );
  }

我通过添加这段代码设法修复了它

constructor(props) {
    ...
    this.state = {
      latitude: null,
      longitude: null,
      error: null,
      routeCoordinates: []
    };
  }

  componentDidMount() {
    this.watchId = navigator.geolocation.watchPosition(
      (position) => {
        ...
        const { routeCoordinates } = this.state
        const positionLatLngs = pick(position.coords, ['latitude', 'longitude'])
        this.setState({ routeCoordinates: routeCoordinates.concat(positionLatLngs) })
        ...
  }

  ...

  render() {
    return (
      <View style={styles.container}>
        <MapView
          ...
          onRegionChange={this.onRegionChange.bind(this)}>
          <MapView.Polyline
            coordinates = {this.state.routeCoordinates}
            strokeColor = '#19B5FE'
            strokeWidth = {5}
          />
          ...
        </MapView>
      </View>
    );
  }