如何在React Native WebView应用中获取用户位置并在谷歌地图展示?
实现步骤与代码示例
1. 安装必要依赖
在项目根目录执行以下命令:
expo install expo-location expo-maps
2. 完整代码实现
替换你现有的App.js内容,以下代码将实现:请求位置权限、获取当前位置、在地图上标记当前位置与目的地,同时保留硬件返回键的基础处理逻辑。
import React, { useState, useEffect, useRef } from 'react'; import { StyleSheet, BackHandler, View, Text } from 'react-native'; import Constants from 'expo-constants'; import * as Location from 'expo-location'; import MapView, { Marker } from 'expo-maps'; export default function App() { const [currentLocation, setCurrentLocation] = useState(null); // 示例目的地坐标,可根据需求修改或通过地址转换获取 const destinationLocation = { latitude: 37.7749, longitude: -122.4194, latitudeDelta: 0.0922, longitudeDelta: 0.0421, }; const mapRef = useRef(null); // 请求权限并获取当前位置 useEffect(() => { const getLocation = async () => { const { status } = await Location.requestForegroundPermissionsAsync(); if (status !== 'granted') { alert('需要开启位置权限才能使用功能'); return; } const location = await Location.getCurrentPositionAsync({}); setCurrentLocation({ latitude: location.coords.latitude, longitude: location.coords.longitude, latitudeDelta: 0.0922, longitudeDelta: 0.0421, }); // 获取位置后自动聚焦到当前位置 if (mapRef.current) { mapRef.current.animateCamera({ center: { latitude: location.coords.latitude, longitude: location.coords.longitude, }, }); } }; getLocation(); }, []); // 硬件返回键处理 const backAction = () => { // 可根据页面路由逻辑调整返回行为,此处默认退出应用 BackHandler.exitApp(); return true; }; useEffect(() => { BackHandler.addEventListener("hardwareBackPress", backAction); return () => BackHandler.removeEventListener("hardwareBackPress", backAction); }, []); // 位置加载中的占位视图 if (!currentLocation) { return ( <View style={styles.loadingContainer}> <Text>正在获取位置...</Text> </View> ); } return ( <View style={styles.container}> <MapView ref={mapRef} style={styles.map} initialRegion={currentLocation} > {/* 当前位置标记 */} <Marker coordinate={{ latitude: currentLocation.latitude, longitude: currentLocation.longitude, }} title="当前位置" description="你的起点" /> {/* 目的地标记(红色) */} <Marker coordinate={{ latitude: destinationLocation.latitude, longitude: destinationLocation.longitude, }} title="目的地" description="你的终点" pinColor="#ff0000" /> </MapView> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, marginTop: Constants.statusBarHeight, }, map: { flex: 1, }, loadingContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', }, });
3. 关键说明
- 权限处理:必须先请求位置权限,否则无法获取用户位置信息
- 地图适配:Android端默认使用谷歌地图,需在项目的
app.json中配置谷歌地图API密钥(添加android.config.googleMaps.apiKey字段);iOS端默认使用苹果地图 - 目的地动态设置:示例中使用固定坐标,你可以通过
Location.geocodeAsync()方法,将用户输入的地址转换为经纬度坐标 - 返回键逻辑:示例中直接退出应用,可根据你的页面路由结构修改为返回上一页的逻辑
内容的提问来源于stack exchange,提问作者Camille Schori
相关产品推荐
相关产品推荐

