React Native Expo MapView 如何居中显示用户当前位置并添加标记
你只需要做以下几处调整即可完成定位后自动调整地图中心的需求:
- 给MapView添加ref引用,方便调用地图内置的定位动画方法,同时新增region状态存储地图的中心点、缩放级参数
- 在
getCurrentPositionAsync获取到位置结果后,构造符合MapView要求的region对象,更新状态或者直接调用动画方法跳转 - 将region参数绑定到MapView组件对应的属性上
完整修改后代码如下:
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, Text } 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 mapRef = useRef(null); const [location, setLocation] = useState(null); const [errorMsg, setErrorMsg] = useState(null); // 初始默认位置,未拿到定位权限/定位结果时先显示该区域,可自行修改 const [region, setRegion] = useState({ latitude: 39.9042, longitude: 116.4074, latitudeDelta: 0.0922, longitudeDelta: 0.0421, }); useEffect(() => { (async () => { let { status } = await Location.requestForegroundPermissionsAsync(); if (status !== 'granted') { setErrorMsg('位置权限被拒绝,无法获取当前定位'); return; } let location = await Location.getCurrentPositionAsync({}); setLocation(location); // 构造新的地图区域参数 const newRegion = { latitude: location.coords.latitude, longitude: location.coords.longitude, latitudeDelta: 0.0922, longitudeDelta: 0.0421, }; // 两种定位跳转方式二选一即可 // 方式1:直接更新region状态,绑定到MapView的region属性 setRegion(newRegion); // 方式2:调用地图动画方法平滑跳转,过渡效果更自然,不需要绑定region时可使用 // mapRef.current?.animateToRegion(newRegion, 1000); })(); }, []); return ( <> <SearchBarContainer> <Searchbar placeholder="location"/> </SearchBarContainer> {/* 权限拒绝时显示提示 */} {errorMsg && <Text style={{position: 'absolute', top: 80, left: 20, zIndex: 999, color: 'red'}}>{errorMsg}</Text>} <Map ref={mapRef} showsUserLocation={true} region={region} // 若使用方式2的动画跳转,可把region换成initialRegion // initialRegion={region} // 如果需要监听用户拖动地图更新region状态可添加以下回调 // onRegionChangeComplete={setRegion} /> </> ); };
参数说明
latitudeDelta和longitudeDelta控制地图的缩放级别,数值越小放大比例越高,可根据实际需求调整animateToRegion的第二个参数为动画时长,单位为毫秒,示例中1000即1秒完成定位跳转
内容的提问来源于stack exchange,提问作者Patrick89
相关产品推荐
相关产品推荐

