打开地图屏幕时,如何将 MapView 置于用户当前位置的中心? React Native 世博会

How to centre a MapView on a user's current location when the Map Screen is opened? React Native Expo

打开地图屏幕时,如何使地图居中以显示用户的当前位置?按照 expo 文档,应该可以通过 Expo Location API 来实现?但是,文档不清楚。我从 expo Location 文档中提取了部分代码,并在我的地图屏幕中实现了它。那么,应该如何集成到MapView中,在打开地图画面时执行getCurrentPositionAsync方法,使地图居中呢?

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>
    </>
  );};

您必须将世博会位置 api 提供的用户坐标传递到您的地图组件中,以便显示您当前的位置,您还需要使用 (lat,lng) 为您的位置设置一个初始状态,如下所示 ,如果您寻求更高的准确性,我会向您推荐这些选项 getCurrentPositionAsync

        export const MapScreen = ({navigation}) => {
        
          const [location, setLocation] = useState({
          latitude: 37.78825,
          longitude: -122.4324,
    });
          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({
                accuracy: Location.Accuracy.Balanced,
                enableHighAccuracy: true,
                timeInterval: 5
});
              setLocation(location);
            })();
          }, []);
        
          return (
            <> 
            <SearchBarContainer>
              <Searchbar placeholder="location"/>
            </SearchBarContainer>
            <Map region={location} showsUserLocation={true}/>
            </>
          );};

我也为这个问题苦苦挣扎了几天,我觉得很奇怪,即使 expo MapView 可以在地图上显示你自己的位置,它不能 return 你自己的坐标.

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

  1. 安装 Expo-location

expo install expo-location

  1. 导入它
import * as Location from 'expo-location'
  1. 创建状态
const [location, setLocation] = useState({});
  1. 创建一个异步检索您的坐标的 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);
        })();
    }, []);
  1. 您的 Mapview 需要有一个引用才能与 MapView 对话并设置它的坐标。
<MapView ref={mapRef}>.... </MapView>
const mapRef = React.createRef();
  1. 最后创建一个可以由自定义按钮触发的功能,以用户位置为中心。
const goToMyLocation = async () => {
        mapRef.current.animateCamera({center: {"latitude":location.coords.latitude, "longitude": location.coords.longitude}});
}