平滑的位置跟踪反应原生地图

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了平滑的位置跟踪反应原生地图相关的知识,希望对你有一定的参考价值。

我建立了一个应用程序,我需要一个位置跟踪(行人)。我顺利地搜索了这个方法。我使用watchPositionAsync,每次用户的位置改变,调用一个函数,在这个函数上,我使用animateToRegion和参数中的新区域和时间。这对于该地区很有效,相机可以顺利地跟踪用户,但是当我到达新区域时地图不会加载,除非我用手指移动拖动地图。

还有更好的方法吗?或者解决问题的方法?

            <MapView
                initialRegion={this.state.currentRegion}
                ref={ref => { this.map = ref; }}
                showsUserLocation={true}
                style={{ flex: 1 }}
                customMapStyle={MAP_STYLE_SAM}
                mapType={(this.state.switchValue) ? 'hybrid':'standard'}
                provider='google'
                onRegionChangeComplete={this.onMapMove}
                loadingEnable={true}
                moveOnMarkerPress={false}
                onPress={this.pressOnMap}
            >

followUser = async () => {
    try {
        await Location.watchPositionAsync(GEOLOCATION_OPTIONS, this.locationChanged);
    }
    catch (error) {
        let status = Location.getProviderStatusAsync();
        if (!status.locationServicesEnabled) {
            alert('Veuillez activer la géolocalisation de votre appareil.');
        }
    }
};

locationChanged = (location) => {
    const region = {
        longitude: location.coords.longitude,
        latitude: location.coords.latitude,
        latitudeDelta: BASIC_LATITUDE_DELTA,
        longitudeDelta: BASIC_LONGITUDE_DELTA
    };
    this.goToRegion(region);
    this.setState({ currentRegion: region });
};

goToRegion = (region) => {
    this.map.animateToRegion(region,1000*2);
};
答案

我希望你使用最新版本的地图,因此不推荐使用animateToRegion。让状态更新驱动动画。不要为每个位置更改调用goToRegion。以下是您可能想要做的事情:

componentDidUpdate(prevProps, prevState) {
  const { latitude: newLat, longitude: newLon } = this.state.currentRegion;
  const { latitude: oldLat, longitude: oldLon } = prevState.currentRegion;
  if (oldLat !== newLat || oldLon !== newLon) {
    this._animateCamera();
  }
}

_animateCamera = () => {
  this.map.animateCamera(
    {
      center: this.state.currentRegion, // should be { latitude, longitude }
      pitch: 10,
    },
    { duration: 750 }
  );
};

componentWillUnmount() {
  this.map = null;
}
另一答案

以下是整个组件@Ziyo的建议:

import React, { Component } from 'react';
import {View, Platform, WebView, TouchableOpacity, Dimensions, Switch, Text} from 'react-native';
import {Constants, Location, Permissions } from 'expo';
import MapView from 'react-native-maps';

import Image from 'react-native-scalable-image';
import {
BASIC_LATITUDE_DELTA,
BASIC_LONGITUDE_DELTA,
MAP_STYLE_SAM,
MARKERS_MONS,
POLYLINE_MONS_COORD,
SARAH_YELLOW, START_REGION,
START_REGION_MONS
} from "../../const/Const";
import {MARKERS_MAIN_ROUTE, MARKERS_OUT_ROUTE, POLYLINE_MAROLLE} from "../../const/MarollesMarker";

const GEOLOCATION_OPTIONS = { accuracy: 6, distanceInterval: 1};

class MarrolleMap extends Component {
state = {
    screenWidth: Dimensions.get('window').width,
    location: null,
    errorMessage: null,
    switchValue: false,
    markerSelected : false,
    markerIsMainRoute: false,
    markerID: '',
    currentRegion: START_REGION,
    markerLoc: undefined,
    prevPos: null,
    curPos: { latitude: 37.420814, longitude: -122.081949 },
    curAng: 45,
    latitudeDelta: 0.0922,
    longitudeDelta: 0.0421,
};

//----------------location authorisations-------------
getPermissionLocation = async () => {
    try {
        let { status } = await Permissions.askAsync(Permissions.LOCATION);
        if (status !== 'granted') {
            this.setState({
                errorMessage: 'Permission to access location was denied',
            });
        }
    }
    catch (error) {
        console.log(error);
    }
    if (Platform.OS === 'android' && !Constants.isDevice) {
        console.log('try it on device');
        this.setState({
            errorMessage: 'Oops, this will not work on Sketch in an Android emulator. Try it on your device!',
        });
    } else {
        this._getLocationAsync();
        //ne se lance pas car il y a un return dans le
    }
};

_getLocationAsync = async () => {
    // a executer dans didmount apres 1s (timer)
    if (Platform.OS === 'android' && !Constants.isDevice) {
        console.log('try it on device');
        this.setState({
            errorMessage: 'Oops, this will not work on Sketch in an Android emulator. Try it on your device!',
        });
    } else {
        try {
            let location = await Location.getCurrentPositionAsync({});
            this.setState({
                currentRegion : {
                    longitude: location.coords.longitude,
                    latitude: location.coords.latitude,
                    longitudeDelta: BASIC_LONGITUDE_DELTA,
                    latitudeDelta: BASIC_LATITUDE_DELTA
                }
            });
            //this.setState({ location });
        }
        catch (error) {
            let status = Location.getProviderStatusAsync();
            if (!status.locationServicesEnabled) {
                alert('Veuillez activer la géolocalisation de votre appareil.');
            }
        }
    }
};

//------------------localisations-------------------

followUser = async () => {
    try {
        await Location.watchPositionAsync(GEOLOCATION_OPTIONS, this.locationChanged);
    }
    catch (error) {
        let status = Location.getProviderStatusAsync();
        if (!status.locationServicesEnabled) {
            alert('Veuillez activer la géolocalisation de votre appareil.');
        }
    }
};

locationChanged = (location) => {
    const region = {
        longitude: location.coords.longitude,
        latitude: location.coords.latitude,
        latitudeDelta: BASIC_LATITUDE_DELTA,
        longitudeDelta: BASIC_LONGITUDE_DELTA
    };
    this.setState({ currentRegion: region });
};

componentDidUpdate = async (prevProps, prevState) => {
    console.log("didUpdate");
    const {latitude: newLat, longitude: newLong} = this.state.currentRegion;
    const { latitude: oldLat, longitude: oldLong } = prevState.currentRegion;


    if ( (oldLat !== newLat) || (oldLong !== newLong) ) {
        this._animateCamera();
    }
};

componentWillUnmount() {
    this.map = null;
}

_animateCamera = () => {
    this.map.animateCamera(
        {
           center : { latitude: 50.8435, longitude: 4.3488 },
           pitch: 10,
        },
        { duration: 750 }
    );
};

followHeading = async () => {
    try {
        await Location.watchHeadingAsync(this.headingChanged);
    }
    catch (error) {
        console.log(error)
    }
};

headingChanged = (heading) => {
    console.log(heading)
};

//-------------------------map-------------------------

onMapReady = () => {
    console.log('map ready')
};

onMapMove = (region) => {
    //code exeuted each time the map move, we get this region values on states
    //console.log('move');
};

pressMainMarker = (coordinate, position) => {
    /*faudra faire en sorte de savoir avant de taper sur le marker, vers quel idmarker on
    s'approche et seter, pour afficher la winodows info en question*/
    const coord = coordinate.nativeEvent.coordinate;
    const id = coordinate.nativeEvent.id;

    this.setState({
        markerID: id,
        markerSelected: true,
        markerIsMainRoute: true,
        markerLoc: coord
    });
    console.log(this.state.markerID);
};

pressOutRouteMarker = (coordinate, position) => {
    const coord = coordinate.nativeEvent.coordinate;
    const id = coordinate.nativeEvent.id;

    this.setState({
        markerID: id,
        markerSelected: true,
        markerIsMainRoute: false,
        markerLoc: coord
    });
    console.log(this.state.markerID);
};

resetCurrentMarkerState = () => {
    this.setState({
        markerSelected: false,
        markerIsMainRoute: false,
    });
};

pressOnMap = (event) => {

    const lat = event.nativeEvent.coordinate.latitude;
    const long = event.nativeEvent.coordinate.longitude;
    //console.log(`{ latitude: ${lat}, longitude: ${long}},`)*/
    this.setState({
        currentRegion: {
            longitude: long,
            latitude: lat,
            longitudeDelta: BASIC_LONGITUDE_DELTA,
            latitudeDelta: BASIC_LATITUDE_DELTA
        }
    });
    console.log(this.state.currentRegion);
    this.resetCurrentMarkerState();
};

pressOnSwitch = (value) => {
    this.setState({switchValue: value});
};

componentWillMount() {
    this.getPermissionLocation();
}

render() {

    return (
        <View style={{ flex: 1 , backgroundColor: '#fff'}}>
            <View style={{top: 0}}>
            </View>
            <MapView
                initialRegion={{...this.state.curPos,
                    latitudeDelta: this.state.latitudeDelta,
                    longitudeDelta: this.state.longitudeDelta}}
                ref={ref => { this.map = ref; }}
                showsUserLocation={true}
                style={{ flex: 1 }}
                customMapStyle={MAP_STYLE_SAM}
                mapType={(this.state.switchValue) ? 'hybrid':'standard'}
                provider='google'
                onReg

以上是关于平滑的位置跟踪反应原生地图的主要内容,如果未能解决你的问题,请参考以下文章

如何在点击时重新加载反应原生地图

打开地图屏幕时,如何将 MapView 以用户当前位置为中心?反应原生博览会

在反应原生中链接谷歌地图应用程序时如何呈现方向?

如何在地图视图中显示不同的位置取决于所选的选取器? (反应原生)

Android 实时谷歌地图位置跟踪

反应原生地图:如何通过用户界面向地图添加带有属性和标记的点