如何在不使用API Key与Google provider的情况下使用react-native-maps
解决react-native-maps非Google Provider下的API Key报错问题
问题说明
我需要使用带自定义切片(custom tiles)的react-native-maps,且不想依赖Google provider。执行安装命令:
npm install react-native-maps --save
运行项目时触发错误:
API Key not found. Check that
is in the element of AndroidManifest.xml
我的组件代码如下:
import React from 'react'; import { Dimensions, StyleSheet, View } from 'react-native'; import MapView, { Marker } from 'react-native-maps'; const App = () => { return ( <View style={{ flex: 1 }}> <MapView style={{ ...StyleSheet.absoluteFillObject, }} provider={undefined} initialRegion={{ latitude: 37.78825, longitude: -122.4324, latitudeDelta: 0.0922, longitudeDelta: 0.0421, }} > <UrlTile urlTemplate="http://c.tile.openstreetmap.org/{z}/{x}/{y}.png" zIndex={1} /> <Marker coordinate={{ latitude: 37.78825, longitude: -122.4324, }} pinColor="red" /> </MapView> </View> ) }
解决方案
1. 显式指定非Google Provider
设置provider={undefined}时,Android端默认仍会尝试加载Google Maps Provider,这是报错的核心原因。需显式指定使用OpenStreetMap Provider:
// 先导入PROVIDER_OSM import MapView, { Marker, UrlTile, PROVIDER_OSM } from 'react-native-maps'; // 修改MapView的provider属性 <MapView style={{ ...StyleSheet.absoluteFillObject, }} provider={PROVIDER_OSM} initialRegion={{ latitude: 37.78825, longitude: -122.4324, latitudeDelta: 0.0922, longitudeDelta: 0.0421, }} >
2. 补充Android端依赖
使用PROVIDER_OSM需要在android/app/build.gradle中添加对应依赖:
dependencies { // 其他已有依赖... implementation 'org.osmdroid:osmdroid-android:6.1.18' implementation 'org.osmdroid:osmdroid-mapsforge:6.1.18' }
3. 修复代码导入遗漏
代码中使用了UrlTile但未导入,需补上:
import MapView, { Marker, UrlTile } from 'react-native-maps';
4. 清理Google Maps相关配置(可选)
如果确认不需要Google Maps,可以删除AndroidManifest.xml中所有和Google Maps API Key相关的配置项,避免冗余提示。
验证
完成上述修改后重新运行项目,API Key报错会消失,自定义切片与Marker均可正常显示。
内容的提问来源于stack exchange,提问作者Ghasem Khalili
相关产品推荐
相关产品推荐

