【问题标题】:How to centre a MapView on a user's current location when the Map Screen is opened? React Native Expo打开地图屏幕时,如何将 MapView 以用户当前位置为中心?反应原生博览会
【发布时间】:2022-01-02 07:36:05
【问题描述】:

如何在地图屏幕打开时使地图居中以显示用户的当前位置?按照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>
    </>
  );};

【问题讨论】:

    标签: javascript reactjs react-native expo react-native-maps


    【解决方案1】:

    您必须将 Expo location 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}/>
                </>
              );};
    

    【讨论】:

    • 您好,感谢您的回答。我实现了你的代码。但是,我收到警告:道具类型失败:道具 region.latitudeDelta 在 mapView 中被标记为必需,但其值未定义。而且地图还没有以当前位置为中心?
    【解决方案2】:

    这几天我也一直在努力解决这个问题,我觉得很奇怪,即使 expo MapView 可以在地图上显示您自己的位置,它也无法返回您自己的坐标。

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

    1. 安装 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}});
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-18
      • 2022-09-29
      • 1970-01-01
      • 2023-03-11
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多