React Native Expo打开地图页时如何让MapView居中显示用户当前位置
实现步骤
你只需要对现有代码做3处修改即可实现需求:
- 引入
useRef创建MapView实例引用,用于调用地图内置的跳转方法 - 成功获取用户位置后,调用
animateToRegion方法把地图视图居中到用户坐标 - 给Map组件绑定对应的ref属性
完整修改后的代码如下:
import React, { useContext, useState, useEffect, useRef } from "react"; import MapView from "react-native-maps"; import styled from "styled-components"; import { Searchbar } from "react-native-paper"; import { View, Alert } 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}) => { // 新增map引用 const mapRef = useRef(null); 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'); Alert.alert('权限提示','获取定位权限失败,无法为您展示当前位置'); // 可选:权限被拒时默认居中到指定城市,示例为北京 mapRef.current?.animateToRegion({ latitude: 39.9042, longitude: 116.4074, latitudeDelta: 0.0922, longitudeDelta: 0.0421, }) return; } let location = await Location.getCurrentPositionAsync({}); setLocation(location); // 获取位置后居中地图 mapRef.current?.animateToRegion({ latitude: location.coords.latitude, longitude: location.coords.longitude, latitudeDelta: 0.0922, longitudeDelta: 0.0421, }) })(); }, []); return ( <> <SearchBarContainer> <Searchbar placeholder="location"/> </SearchBarContainer> {/* 给Map绑定ref */} <Map ref={mapRef} showsUserLocation={true}> </Map> </> );};
补充说明:参数
latitudeDelta和longitudeDelta控制地图缩放等级,数值越小缩放程度越高,你可以根据业务需求自行调整。如果不需要动画过渡效果,可将animateToRegion替换为setRegion方法。
内容的提问来源于stack exchange,提问作者Patrick89
相关产品推荐
相关产品推荐

