React Native地图加载位置

5
我正在尝试使用react-native-maps模块制作一个应用程序。 我可以通过navigator.geolocation.watchPosition获取设备位置,还使用了内置的showUserLocation属性。 如何实现在加载地图时定位到用户位置,而不是看到整个世界或硬编码初始位置。 编辑: 这是我的react-native-map元素。区域被设置为硬编码的初始位置,我想将其更改为始终在用户位置上加载。
    <View style={styles.container}>
                    <MapView
                    style={styles.map}
                    region={this.state.initialPosition}
                    showsMyLocationButton={true}
                    loadingEnabled={true}
                    onRegionChange={(region)=> this.setState({ initialPosition:region })}
                    onLongPress={this.mapOnPress}
                    showsUserLocation={true}
                    > 

我在应用中使用的位置信息来自于这里,但是加载速度非常缓慢,通常需要超过20秒,因此我想跳过这20秒并立即加载用户位置。

this.watchID= navigator.geolocation.watchPosition((position)=>{
    var lastRegion ={
                latitude: lat,
                longitude: lon,
                longitudeDelta: LON_D,
                latitudeDelta: LAT_D
            }
    this.setState({initialPosition:lastRegion})},(error)=>alert(error),{enableHighAccuracy:true,timeout:20,maximumAge:10})

有没有解决方案?谢谢你的帮助 :)

请展示一下你已经尝试过的内容或者你卡住的地方。 - user926721
edited and added more info :) - William
1个回答

5

您可以尝试这个,超时单位为毫秒。在RN:44中进行了测试。

class Map extends Component {

constructor(props) {
    super(props);
    this.state = {
        permissionState: false,
        latitude: null,
        longitude: null,
        error: null,
    };
}

componentDidMount() {
    Platform.OS === 'android' && Platform.Version >= 23 ? this.requestMapPermission() : this.requestMap()
}

async requestMapPermission() {
    try {
        const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION)
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            console.log('Granted');
            this.watchId = navigator.geolocation.getCurrentPosition(
                (position) => {
                    console.log('Position is watched');
                    this.setState({
                        permissionState: true,
                        latitude: position.coords.latitude,
                        longitude: position.coords.longitude,
                        error: null,
                    });
                },
                (error) => this.setState({error: error.message}),
                {enableHighAccuracy: false, timeout: 20000, maximumAge: 1000},
            );

        } else {
            console.log('not Granted');
            this.setState({
                permissionState: false,
            });
        }
    } catch (err) {
        console.warn(err)
    }
}

requestMap() {
    this.watchId = navigator.geolocation.watchPosition(
        (position) => {
            this.setState({
                permissionState: true,
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
                error: null,
            });
        },
        (error) => this.setState({error: error.message, permissionState: false,}),
        {enableHighAccuracy: false, timeout: 20000, maximumAge: 1000},
    );
}


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

render() {
    var {height, width} = Dimensions.get('window');
    return (
        <View style={{height: 150, justifyContent: 'center'}}>
            {
                this.state.permissionState === true ?
                    <MapView
                        minZoomLevel={16}
                        style={{height: 150, marginBottom: 5, marginTop: 5}}
                        region={{
                            latitude: this.state.latitude,
                            longitude: this.state.longitude,
                            latitudeDelta: 0.0922,
                            longitudeDelta: 0.0421
                        }}>
                        <MapView.Marker
                            coordinate={{
                                latitude: (this.state.latitude + 0.00000),
                                longitude: (this.state.longitude + 0.00000),
                            }}>
                            <View>
                                <Icon name="place" size={40} color="#038FC0"/>
                            </View>
                        </MapView.Marker>
                    </MapView> :
                    <View style={{
                        borderWidth: 1,
                        borderColor: '#6f6f6f',
                        height: 150,
                        justifyContent: 'center',
                        alignItems: 'center',
                    }}>
                        <Text>No Permission for location</Text>

                    </View>


            }

        </View>
    );
}
}

const styles = StyleSheet.create({
map: {
    ...StyleSheet.absoluteFillObject,
 }
});

export default Map;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接