React Native中正确打开Waze/谷歌地图的方法及react-native-map-link问题排查
React Native 唤起Waze/谷歌地图的正确方式
你的代码存在两个核心问题:
NavigationDialog是组件函数,但你仅在点击时调用它,并未将其渲染到组件的JSX结构中,导致弹窗根本不会显示。- 点击事件未将
isVisible设为true,即便弹窗被渲染,默认也是隐藏状态。
修复 react-native-map-link 的使用方式
把弹窗组件直接放在页面JSX中,点击按钮时只需切换 isVisible 的状态即可:
import { useState } from 'react'; import { TouchableOpacity, Text } from 'react-native'; import { Popup } from 'react-native-map-link'; const Preferences = () => { const [isVisible, setIsVisible] = useState(false); const navigationOptions = { latitude: 38.8976763, longitude: -77.0387185, title: 'The White House', dialogTitle: '选择导航应用', dialogMessage: '请选择导航应用前往目的地', cancelText: '取消', }; return ( <> <TouchableOpacity onPress={() => setIsVisible(true)}> <Text>导航到白宫</Text> </TouchableOpacity> <Popup isVisible={isVisible} onCancelPressed={() => setIsVisible(false)} onAppPressed={() => setIsVisible(false)} onBackButtonPressed={() => setIsVisible(false)} modalProps={{ animationIn: 'slideInUp' }} appsWhiteList={['waze', 'google-maps']} options={navigationOptions} /> </> ); }; export default Preferences;
同时要确保完成库的配置步骤:
- iOS:在
Info.plist中添加对应地图应用的URL Scheme,比如waze、comgooglemaps - Android:在
AndroidManifest.xml中添加查询权限,确保能检测到已安装的地图应用
不依赖第三方库的直接唤起方式
如果不想用第三方库,可直接用React Native自带的 Linking API打开地图:
唤起谷歌地图
import { Linking } from 'react-native'; const openGoogleMaps = async () => { const url = `google.navigation:q=38.8976763,-77.0387185&mode=d`; const supported = await Linking.canOpenURL(url); if (supported) { await Linking.openURL(url); } else { // 未安装谷歌地图时打开网页版 await Linking.openURL(`https://www.google.com/maps/dir/?api=1&destination=38.8976763,-77.0387185`); } };
唤起Waze
const openWaze = async () => { const url = `waze://?ll=38.8976763,-77.0387185&navigate=yes`; const supported = await Linking.canOpenURL(url); if (supported) { await Linking.openURL(url); } else { await Linking.openURL(`https://www.waze.com/ul?ll=38.8976763,-77.0387185&navigate=yes`); } };
使用时直接在TouchableOpacity的onPress中调用这些函数即可。
内容的提问来源于stack exchange,提问作者emma
相关产品推荐
相关产品推荐

