gpt4 book ai didi

javascript - 本地图屏幕打开时,如何使 map View 以用户当前位置为中心? React Native 博览会

转载 作者:行者123 更新时间:2023-12-03 08:13:32 24 4
gpt4 key购买 nike

打开 map 屏幕时如何使 map 居中以显示用户当前位置?按照expo文档,应该是用Expo Location API来实现吧?然而,文档并不清楚。我从世博会位置文档中获取了部分代码,并在我的 map 屏幕中实现了它。那么,我应该如何将其集成到MapView中以执行getCurrentPositionAsync方法并在 map 屏幕打开时相应地将 map 居中?

import React, { useContext, useState, useEffect } from "react";
import MapView from "react-native-maps";
import styled from "styled-components";
import { Searchbar } from "react-native-paper";
import { View } from "react-native";

import * as Location from 'expo-location';

const Map = styled(MapView)`
height: 100%;
width: 100%;
`;

const SearchBarContainer= styled(View)`
padding: ${(props) => props.theme.space[3]};
position: absolute;
z-index: 999;
top: 20px;
width: 100%;
`;

export const MapScreen = ({navigation}) => {

const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);

useEffect(() => {
(async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
return;
}

let location = await Location.getCurrentPositionAsync({});
setLocation(location);
})();
}, []);

return (
<>
<SearchBarContainer>
<Searchbar placeholder="location"/>
</SearchBarContainer>
<Map showsUserLocation={true}>

</Map>
</>
);};

最佳答案

我也为这个问题苦苦挣扎了几天,我发现很奇怪,即使 expo MapView 可以在 map 上显示您自己的位置,但它无法返回您自己的坐标。

尽管如此,问题可以通过以下解决方案解决。

  1. 安装 Expo-location

expo install expo-location

  • 导入
  • import * as Location from 'expo-location'
  • 创建一个状态
  • const [location, setLocation] = useState({});
  • 创建一个 useEffect 函数,用于异步检索坐标(检索按下按钮时的位置可能需要长达 5-10 秒的时间,这对于用户体验来说太晚了)
  • useEffect(() => {
    (async () => {
    let { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== 'granted') {
    return;
    }

    let location = await Location.getCurrentPositionAsync({
    accuracy: Location.Accuracy.Balanced,
    enableHighAccuracy: true,
    timeInterval: 5
    });
    setLocation(location);
    })();
    }, []);
  • 您的 Mapview 需要有一个引用来与 MapView 对话并设置它的坐标。
  • <MapView ref={mapRef}>.... </MapView>
    const mapRef = React.createRef();
  • 最后创建一个可以通过自定义按钮触发的函数,以用户位置为中心。
  • const goToMyLocation = async () => {
    mapRef.current.animateCamera({center: {"latitude":location.coords.latitude, "longitude": location.coords.longitude}});
    }

    关于javascript - 本地图屏幕打开时,如何使 map View 以用户当前位置为中心? React Native 博览会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70087168/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com