react native实现地图
React Native 地图实现方法
安装依赖库
使用 react-native-maps 库实现地图功能,需要安装核心库和平台特定配置:
npm install react-native-maps
# 或
yarn add react-native-maps
对于 iOS 平台,需在项目目录下执行:
cd ios && pod install
基础地图组件
在组件中引入 MapView 并设置初始区域坐标:
import MapView from 'react-native-maps';
<MapView
style={{ flex: 1 }}
initialRegion={{
latitude: 39.9042,
longitude: 116.4074,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
/>
添加标记点
使用 Marker 组件在地图上标注特定位置:
import { Marker } from 'react-native-maps';
<Marker
coordinate={{ latitude: 39.9042, longitude: 116.4074 }}
title="北京市"
description="中国首都"
/>
自定义地图样式
通过 providers 属性指定地图提供商(如 Google 或 Apple):
<MapView
provider="google"
customMapStyle={mapStyle} // 自定义样式数组
/>
用户定位功能
启用用户位置显示并获取当前位置:
<MapView
showsUserLocation={true}
followsUserLocation={true}
/>
// 获取位置权限需添加相关配置:
// iOS: 在Info.plist添加NSLocationWhenInUseUsageDescription
// Android: 在AndroidManifest.xml添加权限声明
绘制路线
使用 Polyline 组件绘制两点间路线:
import { Polyline } from 'react-native-maps';
<Polyline
coordinates={[
{ latitude: 37.78825, longitude: -122.4324 },
{ latitude: 37.75825, longitude: -122.4624 }
]}
strokeColor="#000"
strokeWidth={3}
/>
注意事项
Android 平台需在 AndroidManifest.xml 中添加 API Key:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_GOOGLE_MAPS_API_KEY"/>
iOS 平台需在 AppDelegate.m 中配置 API Key:
[GMSServices provideAPIKey:@"YOUR_GOOGLE_MAPS_API_KEY"];






