Repository files navigation

react-native-smart-amap

A AMap Library for React Native apps.

npmnpmnpmnpm

react-native 高德地图SDK 插件, 支持ios与android, 关于使用高德地图SDK, 申请应用key等详细信息请点击这里

Mac下Android Studio中获取SHA1和MD5请点击这里

预览

react-native-smart-amap-preview-ios

安装

npm install react-native-smart-amap --save

Notice

这个版本仅支持react-native 0.40及以上, 如果你想使用旧版本,使用npm install react-native-smart-amap@untilRN0.40 --save

安装 (iOS)

  • 将RCTAMap.xcodeproj作为Library拖进你的Xcode里的project中.

  • 将RCTAMap目录里Frameworks目录拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 将RCTAMap目录里Frameworks目录里的AMap.bundle拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 点击你的主project, 选择Build Phases -> Link Binary With Libraries, 将RCTAMap.xcodeproj里Product目录下的libRCTAMap.a拖进去.

  • 同上位置, 选择Add items, 将系统库libstdc++.6.0.9.tbd加入.

  • 同上位置, 选择Add items, 将系统库libc++.tbd加入.

  • 同上位置, 选择Add items, 将系统库libz.tbd加入.

  • 同上位置, 选择Add items, 将系统库Security.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreTelephony.framework加入.

  • 同上位置, 选择Add items, 将系统库SystemConfiguration.framework加入.

  • 同上位置, 选择Add items, 将系统库JavaScriptCore.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreLocation.framework加入.

  • 选择Build Settings, 找到Header Search Paths, 确认其中包含$(SRCROOT)/../../../react-native/React, 模式为recursive.

  • 同上位置, 找到Framework Search Paths, 加入$(PROJECT_DIR)/Frameworks.

  • 点击在Libraries下已拖进来的RCTAMap.xcodeproj, 选择Build Settings, 找到Framework Search Paths, 将$(SRCROOT)/../../../ios/Frameworks替换成$(SRCROOT)/../../../../ios/Frameworks.

  • info.plist中加入Privacy - Location When In Use Usage Description属性(ios 10)

  • info.plist中加入Allow Arbitrary Loads属性, 并设置值为YES(ios 10)

  • AppDelegate.m


...
#import <AMapFoundationKit/AMapFoundationKit.h> //引入高德地图核心包
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[AMapServices sharedServices].apiKey = @"请填写您的key"; //设置高德地图SDK服务key
...
}
...

安装 (Android)

  • android/settings.gradle
...
include ':react-native-smart-amap'
project(':react-native-smart-amap').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-smart-amap/android')
  • android/app/build.gradle
...
dependencies {
...
// From node_modules
compile project(':react-native-smart-amap')
}
  • MainApplication.java
...
import com.reactnativecomponent.amaplocation.RCTAMapPackage; //import package
...
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RCTAMapPackage() //register Module
);
}
...
  • AndroidManifest.xml中, 加入所需权限

...
<!--*************************高德地图-定位所需要权限*************************-->
<!-- Normal Permissions 不需要运行时注册 -->
<!--获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<!-- 请求网络 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 不是SDK需要的权限,是示例中的后台唤醒定位需要的权限 -->
<!--<uses-permission android:name="android.permission.WAKE_LOCK" />-->
<!-- 需要运行时注册的权限 -->
<!--用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--用于访问GPS定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--用于提高GPS定位速度-->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<!--写入扩展存储,向扩展卡写入数据,用于写入缓存定位数据-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--读取缓存数据-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 更改设置 -->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!--*************************高德地图-定位所需要权限*************************-->
...
  • AndroidManifest.xml中, application标签内加入

...
<!--高德地图SDK key设置-->
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="请填写您的key"/>
<!--高德地图APS服务设置-->
<service android:name="com.amap.api.location.APSService" >
</service>
...

完整示例

点击这里 ReactNativeComponentDemos

使用简介

Install the package from npm with npm install react-native-smart-amap --save. Then, require it from your app's JavaScript files with import Barcode from 'react-native-smart-amap'.

importReact,{Component,}from'react'import{StyleSheet,View,Text,Image,NativeAppEventEmitter,TouchableHighlight,ListView,Dimensions,Alert,Platform,}from'react-native'importAMapLocationfrom'react-native-smart-amap-location'importAMapfrom'react-native-smart-amap'importButtonfrom'react-native-smart-button'importAppEventListenerEnhancefrom'react-native-smart-app-event-listener-enhance'importPullToRefreshListViewfrom'react-native-smart-pull-to-refresh-listview'importTimerEnhancefrom'react-native-smart-timer-enhance'importAMapALoneNearByListfrom'./amp-alone-nearby-list'importListViewActivityIndicatorfrom'./ListViewActivityIndicator'const{width: deviceWidth,height: deviceHeight}=Dimensions.get('window')classAMapDemoextendsComponent{constructor(props){super(props);this._amap=nullthis._page=0this._coordinate=this.props.navigator.navigationContext._currentRoute.coordinateconsole.log(`this._coordinate -> `)console.log(this._coordinate)this._keywords='商务住宅|学校'this._onDidMoveByUserTimer=null}componentDidMount(){this.addAppEventListener(NativeAppEventEmitter.addListener('amap.location.onLocationResult',this._onLocationResult),NativeAppEventEmitter.addListener('amap.onPOISearchDone',this._onPOISearchDone)//NativeAppEventEmitter.addListener('amap.onPOISearchFailed', this._onPOISearchFailed))}render(){//console.log(`amap-alone render...`)return(<Viewstyle={{marginTop: (Platform.OS=='ios' ? 20+44 : 56),flex: 1,}}><Viewstyle={{position: 'relative',height: (deviceHeight-(Platform.OS=='ios' ? 64 : 56))-50*5,}}><AMapref={component=>this._amap=component}style={{flex: 1,}}options={{frame: {width: deviceWidth,height: (deviceHeight-64)-50*5},showsUserLocation: false,userTrackingMode: Platform.OS=='ios' ? AMap.constants.userTrackingMode.none : null,centerCoordinate: {latitude: this._coordinate.latitude,longitude: this._coordinate.longitude,},zoomLevel: 18.1,centerMarker: Platform.OS=='ios' ? 'icon_location' : 'poi_marker',}}onLayout={this._onLayout}onDidMoveByUser={this._onDidMoveByUser}/><ButtontouchableType={Button.constants.touchableTypes.highlight}underlayColor={'#ccc'}style={{padding: 5,position: 'absolute',left: 10,bottom: 20,backgroundColor: '#fff',justifyContent: 'center',borderRadius: 3,borderWidth: StyleSheet.hairlineWidth,borderColor: '#ffffff',justifyContent: 'center',}}onPress={()=>{AMapLocation.init(null)AMapLocation.getLocation()//this._activityIndicator.setState({ visible: true,})}}><Imagesource={{uri: Platform.OS=='ios' ? 'gpsStat1' : 'gps_stat1'}}style={{width: 28,height: 28,}}/></Button></View><Viewstyle={{flex: 1,position: 'relative',}}><AMapALoneNearByListref={(component)=>this._amapALoneNearByList=component}onRefresh={this._onRefresh}onLoadMore={this._onLoadMore}/><ListViewActivityIndicatorref={(component)=>this._activityIndicator=component}style={{marginRight: 10,position:'absolute',left: (deviceWidth-20)/2,top: (50*5-20)/2,}}color={'#a9a9a9'}/></View></View>)}_onDidMoveByUser=(e)=>{//console.log(`_onDidMoveByUser....`)if(this._onDidMoveByUserTimer){this.clearTimeout(this._onDidMoveByUserTimer)this._onDidMoveByUserTimer=null}let{ longitude, latitude,}=e.nativeEvent.data.centerCoordinatethis._onDidMoveByUserTimer=this.setTimeout(()=>{let{refresh_none, refresh_idle, load_more_none, load_more_idle, loaded_all,}=PullToRefreshListView.constants.viewStateif((this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_none||this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_idle)&&(this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_none||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_idle||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==loaded_all)){console.log(`beginRefresh(true)....`)this._coordinate={
longitude,
latitude,}this._activityIndicator.setState({visible: true,})this._amapALoneNearByList._pullToRefreshListView._scrollView.scrollTo({y: 0,animated: false,})this._amapALoneNearByList._pullToRefreshListView.beginRefresh(true)//this._amapALoneNearByList._pullToRefreshListView.beginRefresh()this._beginRefresh=true}},300)}_onLocationResult=(result)=>{if(result.error){console.log(`map-错误代码: ${result.error.code}, map-错误信息: ${result.error.localizedDescription}`)}else{if(result.formattedAddress){console.log(`map-格式化地址 = ${result.formattedAddress}`)}else{console.log(`map-纬度 = ${result.coordinate.latitude}, map-经度 = ${result.coordinate.longitude}`)this._coordinate={latitude: result.coordinate.latitude,longitude: result.coordinate.longitude,}this._amap.setOptions({zoomLevel: 18.1,})this._amap.setCenterCoordinate(this._coordinate)}}}//_onPOISearchFailed = (e) => {// //console.log(`_onPOISearchFailed...`)// //console.log(e)// //console.log(e.error)// this._page--;//}_onPOISearchDone=(result)=>{console.log(`_onPOISearchDone...`)if(Platform.OS=='ios'){this._endSearch(result)}else{this.setTimeout(()=>{this._endSearch(result)},255)}}_endSearch=(result)=>{let{ searchResultList, error }=resultconsole.log(result.error)if(error){if(this._page==1){this._page--this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}else{this._amapALoneNearByList._pullToRefreshListView.endLoadMore(false)}return}console.log(`this._page = ${this._page}`)//onRefreshif(this._page==1){this._amapALoneNearByList.setState({dataList: searchResultList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(searchResultList),})this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}//onLoadMoreelse{letnewDataList=this._amapALoneNearByList.state.dataList.concat(searchResultList)this._amapALoneNearByList.setState({dataList: newDataList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(newDataList),})letloadedAllif(searchResultList.length==100){loadedAll=truethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}else{loadedAll=falsethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}}}_searchNearBy=(searchParams)=>{this._amap.searchPoiByCenterCoordinate(searchParams)}_onRefresh=()=>{console.log(`outer _onRefresh...`)this._searchNearBy({page: (this._page=1),coordinate: this._coordinate,keywords: this._keywords,})}_onLoadMore=()=>{console.log(`outer _onLoadMore...`)this._searchNearBy({page: ++this._page,coordinate: this._coordinate,keywords: this._keywords,})}}exportdefaultTimerEnhance(AppEventListenerEnhance(AMapDemo))

属性

PropTypeOptionalDefaultDescription
optionsobjectNo地图参数对象
options.frameobjectNoios设置地图宽(width), 高(height), 类型是number
options.showTrafficboolYesios设置是否显示路况, 默认不显示
options.showsUserLocationboolYesios设置是否显示用户位置,默认显示
options.userTrackingModeboolYesios设置追踪用户位置更新的模式,默认不追踪
options.zoomLevelnumberYes指定缩放级别, 默认为最大级别
options.centerCoordinateobjectYes根据经度(latitude)纬度(longitude)指定地图的中心点, 类型是number
options.centerMarkerstringYes设置中心点自定义图标的项目资源名称, 如为空则不显示中心点图标

方法

  • setOptions

    • 描述: 更改地图参数
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: options 类型: object, 地图参数, 数据结构同上Props中的options
  • setCenterCoordinate

    • 描述: 根据经纬度在地图中心位置显示
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: coordinate 类型: object, 经纬度坐标参数, 数据结构同上Props中的options.centerCoordinate
  • searchPoiByCenterCoordinate

    • 描述: 根据经纬度坐标来搜索周边的POI
    • 参数: params 类型: object, 搜索参数, 数据结构如下: * types 类型: string 表示搜索类型,多个类型用“|”分割 可选值:文本分类、分类代码 * sortrule 类型: number 表示排序规则, 0-距离排序;1-综合排序, 默认1 * offset 类型: number 表示每页记录数, 范围1-50, 默认20 * page 类型: number 表示当前页数, 范围1-100, 默认1 * keywords 类型: string 表示查询关键字,多个关键字用“|”分割 * coordinate 类型: object 表示中心点经纬度, 数据结构同上Props中的options.centerCoordinate * radius 类型: int 表示辐射半径, 默认3000米

事件监听

  • 地图事件: onDidMoveByUser

    • 描述: 监听用户动作, 返回当前地图中心点的经纬度信息
  • 全局事件: amap.onPOISearchDone

    • 描述: 监听POI搜索回调, 返回周边的POI信息

About

react-native 高德地图SDK 插件

Resources

Stars

173 stars

Watchers

8 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

react-native-smart-amap

A AMap Library for React Native apps.

npmnpmnpmnpm

react-native 高德地图SDK 插件, 支持ios与android, 关于使用高德地图SDK, 申请应用key等详细信息请点击这里

Mac下Android Studio中获取SHA1和MD5请点击这里

预览

react-native-smart-amap-preview-ios

安装

npm install react-native-smart-amap --save

Notice

这个版本仅支持react-native 0.40及以上, 如果你想使用旧版本,使用npm install react-native-smart-amap@untilRN0.40 --save

安装 (iOS)

  • 将RCTAMap.xcodeproj作为Library拖进你的Xcode里的project中.

  • 将RCTAMap目录里Frameworks目录拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 将RCTAMap目录里Frameworks目录里的AMap.bundle拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 点击你的主project, 选择Build Phases -> Link Binary With Libraries, 将RCTAMap.xcodeproj里Product目录下的libRCTAMap.a拖进去.

  • 同上位置, 选择Add items, 将系统库libstdc++.6.0.9.tbd加入.

  • 同上位置, 选择Add items, 将系统库libc++.tbd加入.

  • 同上位置, 选择Add items, 将系统库libz.tbd加入.

  • 同上位置, 选择Add items, 将系统库Security.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreTelephony.framework加入.

  • 同上位置, 选择Add items, 将系统库SystemConfiguration.framework加入.

  • 同上位置, 选择Add items, 将系统库JavaScriptCore.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreLocation.framework加入.

  • 选择Build Settings, 找到Header Search Paths, 确认其中包含$(SRCROOT)/../../../react-native/React, 模式为recursive.

  • 同上位置, 找到Framework Search Paths, 加入$(PROJECT_DIR)/Frameworks.

  • 点击在Libraries下已拖进来的RCTAMap.xcodeproj, 选择Build Settings, 找到Framework Search Paths, 将$(SRCROOT)/../../../ios/Frameworks替换成$(SRCROOT)/../../../../ios/Frameworks.

  • info.plist中加入Privacy - Location When In Use Usage Description属性(ios 10)

  • info.plist中加入Allow Arbitrary Loads属性, 并设置值为YES(ios 10)

  • AppDelegate.m


...
#import <AMapFoundationKit/AMapFoundationKit.h> //引入高德地图核心包
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[AMapServices sharedServices].apiKey = @"请填写您的key"; //设置高德地图SDK服务key
...
}
...

安装 (Android)

  • android/settings.gradle
...
include ':react-native-smart-amap'
project(':react-native-smart-amap').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-smart-amap/android')
  • android/app/build.gradle
...
dependencies {
...
// From node_modules
compile project(':react-native-smart-amap')
}
  • MainApplication.java
...
import com.reactnativecomponent.amaplocation.RCTAMapPackage; //import package
...
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RCTAMapPackage() //register Module
);
}
...
  • AndroidManifest.xml中, 加入所需权限

...
<!--*************************高德地图-定位所需要权限*************************-->
<!-- Normal Permissions 不需要运行时注册 -->
<!--获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<!-- 请求网络 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 不是SDK需要的权限,是示例中的后台唤醒定位需要的权限 -->
<!--<uses-permission android:name="android.permission.WAKE_LOCK" />-->
<!-- 需要运行时注册的权限 -->
<!--用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--用于访问GPS定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--用于提高GPS定位速度-->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<!--写入扩展存储,向扩展卡写入数据,用于写入缓存定位数据-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--读取缓存数据-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 更改设置 -->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!--*************************高德地图-定位所需要权限*************************-->
...
  • AndroidManifest.xml中, application标签内加入

...
<!--高德地图SDK key设置-->
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="请填写您的key"/>
<!--高德地图APS服务设置-->
<service android:name="com.amap.api.location.APSService" >
</service>
...

完整示例

点击这里 ReactNativeComponentDemos

使用简介

Install the package from npm with npm install react-native-smart-amap --save. Then, require it from your app's JavaScript files with import Barcode from 'react-native-smart-amap'.

importReact,{Component,}from'react'import{StyleSheet,View,Text,Image,NativeAppEventEmitter,TouchableHighlight,ListView,Dimensions,Alert,Platform,}from'react-native'importAMapLocationfrom'react-native-smart-amap-location'importAMapfrom'react-native-smart-amap'importButtonfrom'react-native-smart-button'importAppEventListenerEnhancefrom'react-native-smart-app-event-listener-enhance'importPullToRefreshListViewfrom'react-native-smart-pull-to-refresh-listview'importTimerEnhancefrom'react-native-smart-timer-enhance'importAMapALoneNearByListfrom'./amp-alone-nearby-list'importListViewActivityIndicatorfrom'./ListViewActivityIndicator'const{width: deviceWidth,height: deviceHeight}=Dimensions.get('window')classAMapDemoextendsComponent{constructor(props){super(props);this._amap=nullthis._page=0this._coordinate=this.props.navigator.navigationContext._currentRoute.coordinateconsole.log(`this._coordinate -> `)console.log(this._coordinate)this._keywords='商务住宅|学校'this._onDidMoveByUserTimer=null}componentDidMount(){this.addAppEventListener(NativeAppEventEmitter.addListener('amap.location.onLocationResult',this._onLocationResult),NativeAppEventEmitter.addListener('amap.onPOISearchDone',this._onPOISearchDone)//NativeAppEventEmitter.addListener('amap.onPOISearchFailed', this._onPOISearchFailed))}render(){//console.log(`amap-alone render...`)return(<Viewstyle={{marginTop: (Platform.OS=='ios' ? 20+44 : 56),flex: 1,}}><Viewstyle={{position: 'relative',height: (deviceHeight-(Platform.OS=='ios' ? 64 : 56))-50*5,}}><AMapref={component=>this._amap=component}style={{flex: 1,}}options={{frame: {width: deviceWidth,height: (deviceHeight-64)-50*5},showsUserLocation: false,userTrackingMode: Platform.OS=='ios' ? AMap.constants.userTrackingMode.none : null,centerCoordinate: {latitude: this._coordinate.latitude,longitude: this._coordinate.longitude,},zoomLevel: 18.1,centerMarker: Platform.OS=='ios' ? 'icon_location' : 'poi_marker',}}onLayout={this._onLayout}onDidMoveByUser={this._onDidMoveByUser}/><ButtontouchableType={Button.constants.touchableTypes.highlight}underlayColor={'#ccc'}style={{padding: 5,position: 'absolute',left: 10,bottom: 20,backgroundColor: '#fff',justifyContent: 'center',borderRadius: 3,borderWidth: StyleSheet.hairlineWidth,borderColor: '#ffffff',justifyContent: 'center',}}onPress={()=>{AMapLocation.init(null)AMapLocation.getLocation()//this._activityIndicator.setState({ visible: true,})}}><Imagesource={{uri: Platform.OS=='ios' ? 'gpsStat1' : 'gps_stat1'}}style={{width: 28,height: 28,}}/></Button></View><Viewstyle={{flex: 1,position: 'relative',}}><AMapALoneNearByListref={(component)=>this._amapALoneNearByList=component}onRefresh={this._onRefresh}onLoadMore={this._onLoadMore}/><ListViewActivityIndicatorref={(component)=>this._activityIndicator=component}style={{marginRight: 10,position:'absolute',left: (deviceWidth-20)/2,top: (50*5-20)/2,}}color={'#a9a9a9'}/></View></View>)}_onDidMoveByUser=(e)=>{//console.log(`_onDidMoveByUser....`)if(this._onDidMoveByUserTimer){this.clearTimeout(this._onDidMoveByUserTimer)this._onDidMoveByUserTimer=null}let{ longitude, latitude,}=e.nativeEvent.data.centerCoordinatethis._onDidMoveByUserTimer=this.setTimeout(()=>{let{refresh_none, refresh_idle, load_more_none, load_more_idle, loaded_all,}=PullToRefreshListView.constants.viewStateif((this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_none||this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_idle)&&(this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_none||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_idle||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==loaded_all)){console.log(`beginRefresh(true)....`)this._coordinate={
longitude,
latitude,}this._activityIndicator.setState({visible: true,})this._amapALoneNearByList._pullToRefreshListView._scrollView.scrollTo({y: 0,animated: false,})this._amapALoneNearByList._pullToRefreshListView.beginRefresh(true)//this._amapALoneNearByList._pullToRefreshListView.beginRefresh()this._beginRefresh=true}},300)}_onLocationResult=(result)=>{if(result.error){console.log(`map-错误代码: ${result.error.code}, map-错误信息: ${result.error.localizedDescription}`)}else{if(result.formattedAddress){console.log(`map-格式化地址 = ${result.formattedAddress}`)}else{console.log(`map-纬度 = ${result.coordinate.latitude}, map-经度 = ${result.coordinate.longitude}`)this._coordinate={latitude: result.coordinate.latitude,longitude: result.coordinate.longitude,}this._amap.setOptions({zoomLevel: 18.1,})this._amap.setCenterCoordinate(this._coordinate)}}}//_onPOISearchFailed = (e) => {// //console.log(`_onPOISearchFailed...`)// //console.log(e)// //console.log(e.error)// this._page--;//}_onPOISearchDone=(result)=>{console.log(`_onPOISearchDone...`)if(Platform.OS=='ios'){this._endSearch(result)}else{this.setTimeout(()=>{this._endSearch(result)},255)}}_endSearch=(result)=>{let{ searchResultList, error }=resultconsole.log(result.error)if(error){if(this._page==1){this._page--this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}else{this._amapALoneNearByList._pullToRefreshListView.endLoadMore(false)}return}console.log(`this._page = ${this._page}`)//onRefreshif(this._page==1){this._amapALoneNearByList.setState({dataList: searchResultList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(searchResultList),})this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}//onLoadMoreelse{letnewDataList=this._amapALoneNearByList.state.dataList.concat(searchResultList)this._amapALoneNearByList.setState({dataList: newDataList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(newDataList),})letloadedAllif(searchResultList.length==100){loadedAll=truethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}else{loadedAll=falsethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}}}_searchNearBy=(searchParams)=>{this._amap.searchPoiByCenterCoordinate(searchParams)}_onRefresh=()=>{console.log(`outer _onRefresh...`)this._searchNearBy({page: (this._page=1),coordinate: this._coordinate,keywords: this._keywords,})}_onLoadMore=()=>{console.log(`outer _onLoadMore...`)this._searchNearBy({page: ++this._page,coordinate: this._coordinate,keywords: this._keywords,})}}exportdefaultTimerEnhance(AppEventListenerEnhance(AMapDemo))

属性

PropTypeOptionalDefaultDescription
optionsobjectNo地图参数对象
options.frameobjectNoios设置地图宽(width), 高(height), 类型是number
options.showTrafficboolYesios设置是否显示路况, 默认不显示
options.showsUserLocationboolYesios设置是否显示用户位置,默认显示
options.userTrackingModeboolYesios设置追踪用户位置更新的模式,默认不追踪
options.zoomLevelnumberYes指定缩放级别, 默认为最大级别
options.centerCoordinateobjectYes根据经度(latitude)纬度(longitude)指定地图的中心点, 类型是number
options.centerMarkerstringYes设置中心点自定义图标的项目资源名称, 如为空则不显示中心点图标

方法

  • setOptions

    • 描述: 更改地图参数
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: options 类型: object, 地图参数, 数据结构同上Props中的options
  • setCenterCoordinate

    • 描述: 根据经纬度在地图中心位置显示
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: coordinate 类型: object, 经纬度坐标参数, 数据结构同上Props中的options.centerCoordinate
  • searchPoiByCenterCoordinate

    • 描述: 根据经纬度坐标来搜索周边的POI
    • 参数: params 类型: object, 搜索参数, 数据结构如下: * types 类型: string 表示搜索类型,多个类型用“|”分割 可选值:文本分类、分类代码 * sortrule 类型: number 表示排序规则, 0-距离排序;1-综合排序, 默认1 * offset 类型: number 表示每页记录数, 范围1-50, 默认20 * page 类型: number 表示当前页数, 范围1-100, 默认1 * keywords 类型: string 表示查询关键字,多个关键字用“|”分割 * coordinate 类型: object 表示中心点经纬度, 数据结构同上Props中的options.centerCoordinate * radius 类型: int 表示辐射半径, 默认3000米

事件监听

  • 地图事件: onDidMoveByUser

    • 描述: 监听用户动作, 返回当前地图中心点的经纬度信息
  • 全局事件: amap.onPOISearchDone

    • 描述: 监听POI搜索回调, 返回周边的POI信息

About

react-native 高德地图SDK 插件

Resources

Stars

173 stars

Watchers

8 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

react-native-smart-amap

A AMap Library for React Native apps.

npmnpmnpmnpm

react-native 高德地图SDK 插件, 支持ios与android, 关于使用高德地图SDK, 申请应用key等详细信息请点击这里

Mac下Android Studio中获取SHA1和MD5请点击这里

预览

react-native-smart-amap-preview-ios

安装

npm install react-native-smart-amap --save

Notice

这个版本仅支持react-native 0.40及以上, 如果你想使用旧版本,使用npm install react-native-smart-amap@untilRN0.40 --save

安装 (iOS)

  • 将RCTAMap.xcodeproj作为Library拖进你的Xcode里的project中.

  • 将RCTAMap目录里Frameworks目录拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 将RCTAMap目录里Frameworks目录里的AMap.bundle拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 点击你的主project, 选择Build Phases -> Link Binary With Libraries, 将RCTAMap.xcodeproj里Product目录下的libRCTAMap.a拖进去.

  • 同上位置, 选择Add items, 将系统库libstdc++.6.0.9.tbd加入.

  • 同上位置, 选择Add items, 将系统库libc++.tbd加入.

  • 同上位置, 选择Add items, 将系统库libz.tbd加入.

  • 同上位置, 选择Add items, 将系统库Security.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreTelephony.framework加入.

  • 同上位置, 选择Add items, 将系统库SystemConfiguration.framework加入.

  • 同上位置, 选择Add items, 将系统库JavaScriptCore.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreLocation.framework加入.

  • 选择Build Settings, 找到Header Search Paths, 确认其中包含$(SRCROOT)/../../../react-native/React, 模式为recursive.

  • 同上位置, 找到Framework Search Paths, 加入$(PROJECT_DIR)/Frameworks.

  • 点击在Libraries下已拖进来的RCTAMap.xcodeproj, 选择Build Settings, 找到Framework Search Paths, 将$(SRCROOT)/../../../ios/Frameworks替换成$(SRCROOT)/../../../../ios/Frameworks.

  • info.plist中加入Privacy - Location When In Use Usage Description属性(ios 10)

  • info.plist中加入Allow Arbitrary Loads属性, 并设置值为YES(ios 10)

  • AppDelegate.m


...
#import <AMapFoundationKit/AMapFoundationKit.h> //引入高德地图核心包
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[AMapServices sharedServices].apiKey = @"请填写您的key"; //设置高德地图SDK服务key
...
}
...

安装 (Android)

  • android/settings.gradle
...
include ':react-native-smart-amap'
project(':react-native-smart-amap').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-smart-amap/android')
  • android/app/build.gradle
...
dependencies {
...
// From node_modules
compile project(':react-native-smart-amap')
}
  • MainApplication.java
...
import com.reactnativecomponent.amaplocation.RCTAMapPackage; //import package
...
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RCTAMapPackage() //register Module
);
}
...
  • AndroidManifest.xml中, 加入所需权限

...
<!--*************************高德地图-定位所需要权限*************************-->
<!-- Normal Permissions 不需要运行时注册 -->
<!--获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<!-- 请求网络 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 不是SDK需要的权限,是示例中的后台唤醒定位需要的权限 -->
<!--<uses-permission android:name="android.permission.WAKE_LOCK" />-->
<!-- 需要运行时注册的权限 -->
<!--用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--用于访问GPS定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--用于提高GPS定位速度-->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<!--写入扩展存储,向扩展卡写入数据,用于写入缓存定位数据-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--读取缓存数据-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 更改设置 -->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!--*************************高德地图-定位所需要权限*************************-->
...
  • AndroidManifest.xml中, application标签内加入

...
<!--高德地图SDK key设置-->
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="请填写您的key"/>
<!--高德地图APS服务设置-->
<service android:name="com.amap.api.location.APSService" >
</service>
...

完整示例

点击这里 ReactNativeComponentDemos

使用简介

Install the package from npm with npm install react-native-smart-amap --save. Then, require it from your app's JavaScript files with import Barcode from 'react-native-smart-amap'.

importReact,{Component,}from'react'import{StyleSheet,View,Text,Image,NativeAppEventEmitter,TouchableHighlight,ListView,Dimensions,Alert,Platform,}from'react-native'importAMapLocationfrom'react-native-smart-amap-location'importAMapfrom'react-native-smart-amap'importButtonfrom'react-native-smart-button'importAppEventListenerEnhancefrom'react-native-smart-app-event-listener-enhance'importPullToRefreshListViewfrom'react-native-smart-pull-to-refresh-listview'importTimerEnhancefrom'react-native-smart-timer-enhance'importAMapALoneNearByListfrom'./amp-alone-nearby-list'importListViewActivityIndicatorfrom'./ListViewActivityIndicator'const{width: deviceWidth,height: deviceHeight}=Dimensions.get('window')classAMapDemoextendsComponent{constructor(props){super(props);this._amap=nullthis._page=0this._coordinate=this.props.navigator.navigationContext._currentRoute.coordinateconsole.log(`this._coordinate -> `)console.log(this._coordinate)this._keywords='商务住宅|学校'this._onDidMoveByUserTimer=null}componentDidMount(){this.addAppEventListener(NativeAppEventEmitter.addListener('amap.location.onLocationResult',this._onLocationResult),NativeAppEventEmitter.addListener('amap.onPOISearchDone',this._onPOISearchDone)//NativeAppEventEmitter.addListener('amap.onPOISearchFailed', this._onPOISearchFailed))}render(){//console.log(`amap-alone render...`)return(<Viewstyle={{marginTop: (Platform.OS=='ios' ? 20+44 : 56),flex: 1,}}><Viewstyle={{position: 'relative',height: (deviceHeight-(Platform.OS=='ios' ? 64 : 56))-50*5,}}><AMapref={component=>this._amap=component}style={{flex: 1,}}options={{frame: {width: deviceWidth,height: (deviceHeight-64)-50*5},showsUserLocation: false,userTrackingMode: Platform.OS=='ios' ? AMap.constants.userTrackingMode.none : null,centerCoordinate: {latitude: this._coordinate.latitude,longitude: this._coordinate.longitude,},zoomLevel: 18.1,centerMarker: Platform.OS=='ios' ? 'icon_location' : 'poi_marker',}}onLayout={this._onLayout}onDidMoveByUser={this._onDidMoveByUser}/><ButtontouchableType={Button.constants.touchableTypes.highlight}underlayColor={'#ccc'}style={{padding: 5,position: 'absolute',left: 10,bottom: 20,backgroundColor: '#fff',justifyContent: 'center',borderRadius: 3,borderWidth: StyleSheet.hairlineWidth,borderColor: '#ffffff',justifyContent: 'center',}}onPress={()=>{AMapLocation.init(null)AMapLocation.getLocation()//this._activityIndicator.setState({ visible: true,})}}><Imagesource={{uri: Platform.OS=='ios' ? 'gpsStat1' : 'gps_stat1'}}style={{width: 28,height: 28,}}/></Button></View><Viewstyle={{flex: 1,position: 'relative',}}><AMapALoneNearByListref={(component)=>this._amapALoneNearByList=component}onRefresh={this._onRefresh}onLoadMore={this._onLoadMore}/><ListViewActivityIndicatorref={(component)=>this._activityIndicator=component}style={{marginRight: 10,position:'absolute',left: (deviceWidth-20)/2,top: (50*5-20)/2,}}color={'#a9a9a9'}/></View></View>)}_onDidMoveByUser=(e)=>{//console.log(`_onDidMoveByUser....`)if(this._onDidMoveByUserTimer){this.clearTimeout(this._onDidMoveByUserTimer)this._onDidMoveByUserTimer=null}let{ longitude, latitude,}=e.nativeEvent.data.centerCoordinatethis._onDidMoveByUserTimer=this.setTimeout(()=>{let{refresh_none, refresh_idle, load_more_none, load_more_idle, loaded_all,}=PullToRefreshListView.constants.viewStateif((this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_none||this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_idle)&&(this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_none||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_idle||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==loaded_all)){console.log(`beginRefresh(true)....`)this._coordinate={
longitude,
latitude,}this._activityIndicator.setState({visible: true,})this._amapALoneNearByList._pullToRefreshListView._scrollView.scrollTo({y: 0,animated: false,})this._amapALoneNearByList._pullToRefreshListView.beginRefresh(true)//this._amapALoneNearByList._pullToRefreshListView.beginRefresh()this._beginRefresh=true}},300)}_onLocationResult=(result)=>{if(result.error){console.log(`map-错误代码: ${result.error.code}, map-错误信息: ${result.error.localizedDescription}`)}else{if(result.formattedAddress){console.log(`map-格式化地址 = ${result.formattedAddress}`)}else{console.log(`map-纬度 = ${result.coordinate.latitude}, map-经度 = ${result.coordinate.longitude}`)this._coordinate={latitude: result.coordinate.latitude,longitude: result.coordinate.longitude,}this._amap.setOptions({zoomLevel: 18.1,})this._amap.setCenterCoordinate(this._coordinate)}}}//_onPOISearchFailed = (e) => {// //console.log(`_onPOISearchFailed...`)// //console.log(e)// //console.log(e.error)// this._page--;//}_onPOISearchDone=(result)=>{console.log(`_onPOISearchDone...`)if(Platform.OS=='ios'){this._endSearch(result)}else{this.setTimeout(()=>{this._endSearch(result)},255)}}_endSearch=(result)=>{let{ searchResultList, error }=resultconsole.log(result.error)if(error){if(this._page==1){this._page--this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}else{this._amapALoneNearByList._pullToRefreshListView.endLoadMore(false)}return}console.log(`this._page = ${this._page}`)//onRefreshif(this._page==1){this._amapALoneNearByList.setState({dataList: searchResultList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(searchResultList),})this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}//onLoadMoreelse{letnewDataList=this._amapALoneNearByList.state.dataList.concat(searchResultList)this._amapALoneNearByList.setState({dataList: newDataList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(newDataList),})letloadedAllif(searchResultList.length==100){loadedAll=truethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}else{loadedAll=falsethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}}}_searchNearBy=(searchParams)=>{this._amap.searchPoiByCenterCoordinate(searchParams)}_onRefresh=()=>{console.log(`outer _onRefresh...`)this._searchNearBy({page: (this._page=1),coordinate: this._coordinate,keywords: this._keywords,})}_onLoadMore=()=>{console.log(`outer _onLoadMore...`)this._searchNearBy({page: ++this._page,coordinate: this._coordinate,keywords: this._keywords,})}}exportdefaultTimerEnhance(AppEventListenerEnhance(AMapDemo))

属性

PropTypeOptionalDefaultDescription
optionsobjectNo地图参数对象
options.frameobjectNoios设置地图宽(width), 高(height), 类型是number
options.showTrafficboolYesios设置是否显示路况, 默认不显示
options.showsUserLocationboolYesios设置是否显示用户位置,默认显示
options.userTrackingModeboolYesios设置追踪用户位置更新的模式,默认不追踪
options.zoomLevelnumberYes指定缩放级别, 默认为最大级别
options.centerCoordinateobjectYes根据经度(latitude)纬度(longitude)指定地图的中心点, 类型是number
options.centerMarkerstringYes设置中心点自定义图标的项目资源名称, 如为空则不显示中心点图标

方法

  • setOptions

    • 描述: 更改地图参数
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: options 类型: object, 地图参数, 数据结构同上Props中的options
  • setCenterCoordinate

    • 描述: 根据经纬度在地图中心位置显示
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: coordinate 类型: object, 经纬度坐标参数, 数据结构同上Props中的options.centerCoordinate
  • searchPoiByCenterCoordinate

    • 描述: 根据经纬度坐标来搜索周边的POI
    • 参数: params 类型: object, 搜索参数, 数据结构如下: * types 类型: string 表示搜索类型,多个类型用“|”分割 可选值:文本分类、分类代码 * sortrule 类型: number 表示排序规则, 0-距离排序;1-综合排序, 默认1 * offset 类型: number 表示每页记录数, 范围1-50, 默认20 * page 类型: number 表示当前页数, 范围1-100, 默认1 * keywords 类型: string 表示查询关键字,多个关键字用“|”分割 * coordinate 类型: object 表示中心点经纬度, 数据结构同上Props中的options.centerCoordinate * radius 类型: int 表示辐射半径, 默认3000米

事件监听

  • 地图事件: onDidMoveByUser

    • 描述: 监听用户动作, 返回当前地图中心点的经纬度信息
  • 全局事件: amap.onPOISearchDone

    • 描述: 监听POI搜索回调, 返回周边的POI信息

About

react-native 高德地图SDK 插件

Resources

Stars

173 stars

Watchers

8 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

react-native-smart-amap

A AMap Library for React Native apps.

npmnpmnpmnpm

react-native 高德地图SDK 插件, 支持ios与android, 关于使用高德地图SDK, 申请应用key等详细信息请点击这里

Mac下Android Studio中获取SHA1和MD5请点击这里

预览

react-native-smart-amap-preview-ios

安装

npm install react-native-smart-amap --save

Notice

这个版本仅支持react-native 0.40及以上, 如果你想使用旧版本,使用npm install react-native-smart-amap@untilRN0.40 --save

安装 (iOS)

  • 将RCTAMap.xcodeproj作为Library拖进你的Xcode里的project中.

  • 将RCTAMap目录里Frameworks目录拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 将RCTAMap目录里Frameworks目录里的AMap.bundle拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 点击你的主project, 选择Build Phases -> Link Binary With Libraries, 将RCTAMap.xcodeproj里Product目录下的libRCTAMap.a拖进去.

  • 同上位置, 选择Add items, 将系统库libstdc++.6.0.9.tbd加入.

  • 同上位置, 选择Add items, 将系统库libc++.tbd加入.

  • 同上位置, 选择Add items, 将系统库libz.tbd加入.

  • 同上位置, 选择Add items, 将系统库Security.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreTelephony.framework加入.

  • 同上位置, 选择Add items, 将系统库SystemConfiguration.framework加入.

  • 同上位置, 选择Add items, 将系统库JavaScriptCore.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreLocation.framework加入.

  • 选择Build Settings, 找到Header Search Paths, 确认其中包含$(SRCROOT)/../../../react-native/React, 模式为recursive.

  • 同上位置, 找到Framework Search Paths, 加入$(PROJECT_DIR)/Frameworks.

  • 点击在Libraries下已拖进来的RCTAMap.xcodeproj, 选择Build Settings, 找到Framework Search Paths, 将$(SRCROOT)/../../../ios/Frameworks替换成$(SRCROOT)/../../../../ios/Frameworks.

  • info.plist中加入Privacy - Location When In Use Usage Description属性(ios 10)

  • info.plist中加入Allow Arbitrary Loads属性, 并设置值为YES(ios 10)

  • AppDelegate.m


...
#import <AMapFoundationKit/AMapFoundationKit.h> //引入高德地图核心包
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[AMapServices sharedServices].apiKey = @"请填写您的key"; //设置高德地图SDK服务key
...
}
...

安装 (Android)

  • android/settings.gradle
...
include ':react-native-smart-amap'
project(':react-native-smart-amap').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-smart-amap/android')
  • android/app/build.gradle
...
dependencies {
...
// From node_modules
compile project(':react-native-smart-amap')
}
  • MainApplication.java
...
import com.reactnativecomponent.amaplocation.RCTAMapPackage; //import package
...
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RCTAMapPackage() //register Module
);
}
...
  • AndroidManifest.xml中, 加入所需权限

...
<!--*************************高德地图-定位所需要权限*************************-->
<!-- Normal Permissions 不需要运行时注册 -->
<!--获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<!-- 请求网络 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 不是SDK需要的权限,是示例中的后台唤醒定位需要的权限 -->
<!--<uses-permission android:name="android.permission.WAKE_LOCK" />-->
<!-- 需要运行时注册的权限 -->
<!--用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--用于访问GPS定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--用于提高GPS定位速度-->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<!--写入扩展存储,向扩展卡写入数据,用于写入缓存定位数据-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--读取缓存数据-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 更改设置 -->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!--*************************高德地图-定位所需要权限*************************-->
...
  • AndroidManifest.xml中, application标签内加入

...
<!--高德地图SDK key设置-->
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="请填写您的key"/>
<!--高德地图APS服务设置-->
<service android:name="com.amap.api.location.APSService" >
</service>
...

完整示例

点击这里 ReactNativeComponentDemos

使用简介

Install the package from npm with npm install react-native-smart-amap --save. Then, require it from your app's JavaScript files with import Barcode from 'react-native-smart-amap'.

importReact,{Component,}from'react'import{StyleSheet,View,Text,Image,NativeAppEventEmitter,TouchableHighlight,ListView,Dimensions,Alert,Platform,}from'react-native'importAMapLocationfrom'react-native-smart-amap-location'importAMapfrom'react-native-smart-amap'importButtonfrom'react-native-smart-button'importAppEventListenerEnhancefrom'react-native-smart-app-event-listener-enhance'importPullToRefreshListViewfrom'react-native-smart-pull-to-refresh-listview'importTimerEnhancefrom'react-native-smart-timer-enhance'importAMapALoneNearByListfrom'./amp-alone-nearby-list'importListViewActivityIndicatorfrom'./ListViewActivityIndicator'const{width: deviceWidth,height: deviceHeight}=Dimensions.get('window')classAMapDemoextendsComponent{constructor(props){super(props);this._amap=nullthis._page=0this._coordinate=this.props.navigator.navigationContext._currentRoute.coordinateconsole.log(`this._coordinate -> `)console.log(this._coordinate)this._keywords='商务住宅|学校'this._onDidMoveByUserTimer=null}componentDidMount(){this.addAppEventListener(NativeAppEventEmitter.addListener('amap.location.onLocationResult',this._onLocationResult),NativeAppEventEmitter.addListener('amap.onPOISearchDone',this._onPOISearchDone)//NativeAppEventEmitter.addListener('amap.onPOISearchFailed', this._onPOISearchFailed))}render(){//console.log(`amap-alone render...`)return(<Viewstyle={{marginTop: (Platform.OS=='ios' ? 20+44 : 56),flex: 1,}}><Viewstyle={{position: 'relative',height: (deviceHeight-(Platform.OS=='ios' ? 64 : 56))-50*5,}}><AMapref={component=>this._amap=component}style={{flex: 1,}}options={{frame: {width: deviceWidth,height: (deviceHeight-64)-50*5},showsUserLocation: false,userTrackingMode: Platform.OS=='ios' ? AMap.constants.userTrackingMode.none : null,centerCoordinate: {latitude: this._coordinate.latitude,longitude: this._coordinate.longitude,},zoomLevel: 18.1,centerMarker: Platform.OS=='ios' ? 'icon_location' : 'poi_marker',}}onLayout={this._onLayout}onDidMoveByUser={this._onDidMoveByUser}/><ButtontouchableType={Button.constants.touchableTypes.highlight}underlayColor={'#ccc'}style={{padding: 5,position: 'absolute',left: 10,bottom: 20,backgroundColor: '#fff',justifyContent: 'center',borderRadius: 3,borderWidth: StyleSheet.hairlineWidth,borderColor: '#ffffff',justifyContent: 'center',}}onPress={()=>{AMapLocation.init(null)AMapLocation.getLocation()//this._activityIndicator.setState({ visible: true,})}}><Imagesource={{uri: Platform.OS=='ios' ? 'gpsStat1' : 'gps_stat1'}}style={{width: 28,height: 28,}}/></Button></View><Viewstyle={{flex: 1,position: 'relative',}}><AMapALoneNearByListref={(component)=>this._amapALoneNearByList=component}onRefresh={this._onRefresh}onLoadMore={this._onLoadMore}/><ListViewActivityIndicatorref={(component)=>this._activityIndicator=component}style={{marginRight: 10,position:'absolute',left: (deviceWidth-20)/2,top: (50*5-20)/2,}}color={'#a9a9a9'}/></View></View>)}_onDidMoveByUser=(e)=>{//console.log(`_onDidMoveByUser....`)if(this._onDidMoveByUserTimer){this.clearTimeout(this._onDidMoveByUserTimer)this._onDidMoveByUserTimer=null}let{ longitude, latitude,}=e.nativeEvent.data.centerCoordinatethis._onDidMoveByUserTimer=this.setTimeout(()=>{let{refresh_none, refresh_idle, load_more_none, load_more_idle, loaded_all,}=PullToRefreshListView.constants.viewStateif((this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_none||this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_idle)&&(this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_none||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_idle||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==loaded_all)){console.log(`beginRefresh(true)....`)this._coordinate={
longitude,
latitude,}this._activityIndicator.setState({visible: true,})this._amapALoneNearByList._pullToRefreshListView._scrollView.scrollTo({y: 0,animated: false,})this._amapALoneNearByList._pullToRefreshListView.beginRefresh(true)//this._amapALoneNearByList._pullToRefreshListView.beginRefresh()this._beginRefresh=true}},300)}_onLocationResult=(result)=>{if(result.error){console.log(`map-错误代码: ${result.error.code}, map-错误信息: ${result.error.localizedDescription}`)}else{if(result.formattedAddress){console.log(`map-格式化地址 = ${result.formattedAddress}`)}else{console.log(`map-纬度 = ${result.coordinate.latitude}, map-经度 = ${result.coordinate.longitude}`)this._coordinate={latitude: result.coordinate.latitude,longitude: result.coordinate.longitude,}this._amap.setOptions({zoomLevel: 18.1,})this._amap.setCenterCoordinate(this._coordinate)}}}//_onPOISearchFailed = (e) => {// //console.log(`_onPOISearchFailed...`)// //console.log(e)// //console.log(e.error)// this._page--;//}_onPOISearchDone=(result)=>{console.log(`_onPOISearchDone...`)if(Platform.OS=='ios'){this._endSearch(result)}else{this.setTimeout(()=>{this._endSearch(result)},255)}}_endSearch=(result)=>{let{ searchResultList, error }=resultconsole.log(result.error)if(error){if(this._page==1){this._page--this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}else{this._amapALoneNearByList._pullToRefreshListView.endLoadMore(false)}return}console.log(`this._page = ${this._page}`)//onRefreshif(this._page==1){this._amapALoneNearByList.setState({dataList: searchResultList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(searchResultList),})this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}//onLoadMoreelse{letnewDataList=this._amapALoneNearByList.state.dataList.concat(searchResultList)this._amapALoneNearByList.setState({dataList: newDataList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(newDataList),})letloadedAllif(searchResultList.length==100){loadedAll=truethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}else{loadedAll=falsethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}}}_searchNearBy=(searchParams)=>{this._amap.searchPoiByCenterCoordinate(searchParams)}_onRefresh=()=>{console.log(`outer _onRefresh...`)this._searchNearBy({page: (this._page=1),coordinate: this._coordinate,keywords: this._keywords,})}_onLoadMore=()=>{console.log(`outer _onLoadMore...`)this._searchNearBy({page: ++this._page,coordinate: this._coordinate,keywords: this._keywords,})}}exportdefaultTimerEnhance(AppEventListenerEnhance(AMapDemo))

属性

PropTypeOptionalDefaultDescription
optionsobjectNo地图参数对象
options.frameobjectNoios设置地图宽(width), 高(height), 类型是number
options.showTrafficboolYesios设置是否显示路况, 默认不显示
options.showsUserLocationboolYesios设置是否显示用户位置,默认显示
options.userTrackingModeboolYesios设置追踪用户位置更新的模式,默认不追踪
options.zoomLevelnumberYes指定缩放级别, 默认为最大级别
options.centerCoordinateobjectYes根据经度(latitude)纬度(longitude)指定地图的中心点, 类型是number
options.centerMarkerstringYes设置中心点自定义图标的项目资源名称, 如为空则不显示中心点图标

方法

  • setOptions

    • 描述: 更改地图参数
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: options 类型: object, 地图参数, 数据结构同上Props中的options
  • setCenterCoordinate

    • 描述: 根据经纬度在地图中心位置显示
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: coordinate 类型: object, 经纬度坐标参数, 数据结构同上Props中的options.centerCoordinate
  • searchPoiByCenterCoordinate

    • 描述: 根据经纬度坐标来搜索周边的POI
    • 参数: params 类型: object, 搜索参数, 数据结构如下: * types 类型: string 表示搜索类型,多个类型用“|”分割 可选值:文本分类、分类代码 * sortrule 类型: number 表示排序规则, 0-距离排序;1-综合排序, 默认1 * offset 类型: number 表示每页记录数, 范围1-50, 默认20 * page 类型: number 表示当前页数, 范围1-100, 默认1 * keywords 类型: string 表示查询关键字,多个关键字用“|”分割 * coordinate 类型: object 表示中心点经纬度, 数据结构同上Props中的options.centerCoordinate * radius 类型: int 表示辐射半径, 默认3000米

事件监听

  • 地图事件: onDidMoveByUser

    • 描述: 监听用户动作, 返回当前地图中心点的经纬度信息
  • 全局事件: amap.onPOISearchDone

    • 描述: 监听POI搜索回调, 返回周边的POI信息

About

react-native 高德地图SDK 插件

Resources

Stars

173 stars

Watchers

8 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

react-native-smart-amap

A AMap Library for React Native apps.

npmnpmnpmnpm

react-native 高德地图SDK 插件, 支持ios与android, 关于使用高德地图SDK, 申请应用key等详细信息请点击这里

Mac下Android Studio中获取SHA1和MD5请点击这里

预览

react-native-smart-amap-preview-ios

安装

npm install react-native-smart-amap --save

Notice

这个版本仅支持react-native 0.40及以上, 如果你想使用旧版本,使用npm install react-native-smart-amap@untilRN0.40 --save

安装 (iOS)

  • 将RCTAMap.xcodeproj作为Library拖进你的Xcode里的project中.

  • 将RCTAMap目录里Frameworks目录拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 将RCTAMap目录里Frameworks目录里的AMap.bundle拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 点击你的主project, 选择Build Phases -> Link Binary With Libraries, 将RCTAMap.xcodeproj里Product目录下的libRCTAMap.a拖进去.

  • 同上位置, 选择Add items, 将系统库libstdc++.6.0.9.tbd加入.

  • 同上位置, 选择Add items, 将系统库libc++.tbd加入.

  • 同上位置, 选择Add items, 将系统库libz.tbd加入.

  • 同上位置, 选择Add items, 将系统库Security.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreTelephony.framework加入.

  • 同上位置, 选择Add items, 将系统库SystemConfiguration.framework加入.

  • 同上位置, 选择Add items, 将系统库JavaScriptCore.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreLocation.framework加入.

  • 选择Build Settings, 找到Header Search Paths, 确认其中包含$(SRCROOT)/../../../react-native/React, 模式为recursive.

  • 同上位置, 找到Framework Search Paths, 加入$(PROJECT_DIR)/Frameworks.

  • 点击在Libraries下已拖进来的RCTAMap.xcodeproj, 选择Build Settings, 找到Framework Search Paths, 将$(SRCROOT)/../../../ios/Frameworks替换成$(SRCROOT)/../../../../ios/Frameworks.

  • info.plist中加入Privacy - Location When In Use Usage Description属性(ios 10)

  • info.plist中加入Allow Arbitrary Loads属性, 并设置值为YES(ios 10)

  • AppDelegate.m


...
#import <AMapFoundationKit/AMapFoundationKit.h> //引入高德地图核心包
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[AMapServices sharedServices].apiKey = @"请填写您的key"; //设置高德地图SDK服务key
...
}
...

安装 (Android)

  • android/settings.gradle
...
include ':react-native-smart-amap'
project(':react-native-smart-amap').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-smart-amap/android')
  • android/app/build.gradle
...
dependencies {
...
// From node_modules
compile project(':react-native-smart-amap')
}
  • MainApplication.java
...
import com.reactnativecomponent.amaplocation.RCTAMapPackage; //import package
...
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RCTAMapPackage() //register Module
);
}
...
  • AndroidManifest.xml中, 加入所需权限

...
<!--*************************高德地图-定位所需要权限*************************-->
<!-- Normal Permissions 不需要运行时注册 -->
<!--获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<!-- 请求网络 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 不是SDK需要的权限,是示例中的后台唤醒定位需要的权限 -->
<!--<uses-permission android:name="android.permission.WAKE_LOCK" />-->
<!-- 需要运行时注册的权限 -->
<!--用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--用于访问GPS定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--用于提高GPS定位速度-->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<!--写入扩展存储,向扩展卡写入数据,用于写入缓存定位数据-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--读取缓存数据-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 更改设置 -->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!--*************************高德地图-定位所需要权限*************************-->
...
  • AndroidManifest.xml中, application标签内加入

...
<!--高德地图SDK key设置-->
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="请填写您的key"/>
<!--高德地图APS服务设置-->
<service android:name="com.amap.api.location.APSService" >
</service>
...

完整示例

点击这里 ReactNativeComponentDemos

使用简介

Install the package from npm with npm install react-native-smart-amap --save. Then, require it from your app's JavaScript files with import Barcode from 'react-native-smart-amap'.

importReact,{Component,}from'react'import{StyleSheet,View,Text,Image,NativeAppEventEmitter,TouchableHighlight,ListView,Dimensions,Alert,Platform,}from'react-native'importAMapLocationfrom'react-native-smart-amap-location'importAMapfrom'react-native-smart-amap'importButtonfrom'react-native-smart-button'importAppEventListenerEnhancefrom'react-native-smart-app-event-listener-enhance'importPullToRefreshListViewfrom'react-native-smart-pull-to-refresh-listview'importTimerEnhancefrom'react-native-smart-timer-enhance'importAMapALoneNearByListfrom'./amp-alone-nearby-list'importListViewActivityIndicatorfrom'./ListViewActivityIndicator'const{width: deviceWidth,height: deviceHeight}=Dimensions.get('window')classAMapDemoextendsComponent{constructor(props){super(props);this._amap=nullthis._page=0this._coordinate=this.props.navigator.navigationContext._currentRoute.coordinateconsole.log(`this._coordinate -> `)console.log(this._coordinate)this._keywords='商务住宅|学校'this._onDidMoveByUserTimer=null}componentDidMount(){this.addAppEventListener(NativeAppEventEmitter.addListener('amap.location.onLocationResult',this._onLocationResult),NativeAppEventEmitter.addListener('amap.onPOISearchDone',this._onPOISearchDone)//NativeAppEventEmitter.addListener('amap.onPOISearchFailed', this._onPOISearchFailed))}render(){//console.log(`amap-alone render...`)return(<Viewstyle={{marginTop: (Platform.OS=='ios' ? 20+44 : 56),flex: 1,}}><Viewstyle={{position: 'relative',height: (deviceHeight-(Platform.OS=='ios' ? 64 : 56))-50*5,}}><AMapref={component=>this._amap=component}style={{flex: 1,}}options={{frame: {width: deviceWidth,height: (deviceHeight-64)-50*5},showsUserLocation: false,userTrackingMode: Platform.OS=='ios' ? AMap.constants.userTrackingMode.none : null,centerCoordinate: {latitude: this._coordinate.latitude,longitude: this._coordinate.longitude,},zoomLevel: 18.1,centerMarker: Platform.OS=='ios' ? 'icon_location' : 'poi_marker',}}onLayout={this._onLayout}onDidMoveByUser={this._onDidMoveByUser}/><ButtontouchableType={Button.constants.touchableTypes.highlight}underlayColor={'#ccc'}style={{padding: 5,position: 'absolute',left: 10,bottom: 20,backgroundColor: '#fff',justifyContent: 'center',borderRadius: 3,borderWidth: StyleSheet.hairlineWidth,borderColor: '#ffffff',justifyContent: 'center',}}onPress={()=>{AMapLocation.init(null)AMapLocation.getLocation()//this._activityIndicator.setState({ visible: true,})}}><Imagesource={{uri: Platform.OS=='ios' ? 'gpsStat1' : 'gps_stat1'}}style={{width: 28,height: 28,}}/></Button></View><Viewstyle={{flex: 1,position: 'relative',}}><AMapALoneNearByListref={(component)=>this._amapALoneNearByList=component}onRefresh={this._onRefresh}onLoadMore={this._onLoadMore}/><ListViewActivityIndicatorref={(component)=>this._activityIndicator=component}style={{marginRight: 10,position:'absolute',left: (deviceWidth-20)/2,top: (50*5-20)/2,}}color={'#a9a9a9'}/></View></View>)}_onDidMoveByUser=(e)=>{//console.log(`_onDidMoveByUser....`)if(this._onDidMoveByUserTimer){this.clearTimeout(this._onDidMoveByUserTimer)this._onDidMoveByUserTimer=null}let{ longitude, latitude,}=e.nativeEvent.data.centerCoordinatethis._onDidMoveByUserTimer=this.setTimeout(()=>{let{refresh_none, refresh_idle, load_more_none, load_more_idle, loaded_all,}=PullToRefreshListView.constants.viewStateif((this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_none||this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_idle)&&(this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_none||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_idle||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==loaded_all)){console.log(`beginRefresh(true)....`)this._coordinate={
longitude,
latitude,}this._activityIndicator.setState({visible: true,})this._amapALoneNearByList._pullToRefreshListView._scrollView.scrollTo({y: 0,animated: false,})this._amapALoneNearByList._pullToRefreshListView.beginRefresh(true)//this._amapALoneNearByList._pullToRefreshListView.beginRefresh()this._beginRefresh=true}},300)}_onLocationResult=(result)=>{if(result.error){console.log(`map-错误代码: ${result.error.code}, map-错误信息: ${result.error.localizedDescription}`)}else{if(result.formattedAddress){console.log(`map-格式化地址 = ${result.formattedAddress}`)}else{console.log(`map-纬度 = ${result.coordinate.latitude}, map-经度 = ${result.coordinate.longitude}`)this._coordinate={latitude: result.coordinate.latitude,longitude: result.coordinate.longitude,}this._amap.setOptions({zoomLevel: 18.1,})this._amap.setCenterCoordinate(this._coordinate)}}}//_onPOISearchFailed = (e) => {// //console.log(`_onPOISearchFailed...`)// //console.log(e)// //console.log(e.error)// this._page--;//}_onPOISearchDone=(result)=>{console.log(`_onPOISearchDone...`)if(Platform.OS=='ios'){this._endSearch(result)}else{this.setTimeout(()=>{this._endSearch(result)},255)}}_endSearch=(result)=>{let{ searchResultList, error }=resultconsole.log(result.error)if(error){if(this._page==1){this._page--this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}else{this._amapALoneNearByList._pullToRefreshListView.endLoadMore(false)}return}console.log(`this._page = ${this._page}`)//onRefreshif(this._page==1){this._amapALoneNearByList.setState({dataList: searchResultList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(searchResultList),})this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}//onLoadMoreelse{letnewDataList=this._amapALoneNearByList.state.dataList.concat(searchResultList)this._amapALoneNearByList.setState({dataList: newDataList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(newDataList),})letloadedAllif(searchResultList.length==100){loadedAll=truethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}else{loadedAll=falsethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}}}_searchNearBy=(searchParams)=>{this._amap.searchPoiByCenterCoordinate(searchParams)}_onRefresh=()=>{console.log(`outer _onRefresh...`)this._searchNearBy({page: (this._page=1),coordinate: this._coordinate,keywords: this._keywords,})}_onLoadMore=()=>{console.log(`outer _onLoadMore...`)this._searchNearBy({page: ++this._page,coordinate: this._coordinate,keywords: this._keywords,})}}exportdefaultTimerEnhance(AppEventListenerEnhance(AMapDemo))

属性

PropTypeOptionalDefaultDescription
optionsobjectNo地图参数对象
options.frameobjectNoios设置地图宽(width), 高(height), 类型是number
options.showTrafficboolYesios设置是否显示路况, 默认不显示
options.showsUserLocationboolYesios设置是否显示用户位置,默认显示
options.userTrackingModeboolYesios设置追踪用户位置更新的模式,默认不追踪
options.zoomLevelnumberYes指定缩放级别, 默认为最大级别
options.centerCoordinateobjectYes根据经度(latitude)纬度(longitude)指定地图的中心点, 类型是number
options.centerMarkerstringYes设置中心点自定义图标的项目资源名称, 如为空则不显示中心点图标

方法

  • setOptions

    • 描述: 更改地图参数
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: options 类型: object, 地图参数, 数据结构同上Props中的options
  • setCenterCoordinate

    • 描述: 根据经纬度在地图中心位置显示
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: coordinate 类型: object, 经纬度坐标参数, 数据结构同上Props中的options.centerCoordinate
  • searchPoiByCenterCoordinate

    • 描述: 根据经纬度坐标来搜索周边的POI
    • 参数: params 类型: object, 搜索参数, 数据结构如下: * types 类型: string 表示搜索类型,多个类型用“|”分割 可选值:文本分类、分类代码 * sortrule 类型: number 表示排序规则, 0-距离排序;1-综合排序, 默认1 * offset 类型: number 表示每页记录数, 范围1-50, 默认20 * page 类型: number 表示当前页数, 范围1-100, 默认1 * keywords 类型: string 表示查询关键字,多个关键字用“|”分割 * coordinate 类型: object 表示中心点经纬度, 数据结构同上Props中的options.centerCoordinate * radius 类型: int 表示辐射半径, 默认3000米

事件监听

  • 地图事件: onDidMoveByUser

    • 描述: 监听用户动作, 返回当前地图中心点的经纬度信息
  • 全局事件: amap.onPOISearchDone

    • 描述: 监听POI搜索回调, 返回周边的POI信息

About

react-native 高德地图SDK 插件

Resources

Stars

173 stars

Watchers

8 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

react-native-smart-amap

A AMap Library for React Native apps.

npmnpmnpmnpm

react-native 高德地图SDK 插件, 支持ios与android, 关于使用高德地图SDK, 申请应用key等详细信息请点击这里

Mac下Android Studio中获取SHA1和MD5请点击这里

预览

react-native-smart-amap-preview-ios

安装

npm install react-native-smart-amap --save

Notice

这个版本仅支持react-native 0.40及以上, 如果你想使用旧版本,使用npm install react-native-smart-amap@untilRN0.40 --save

安装 (iOS)

  • 将RCTAMap.xcodeproj作为Library拖进你的Xcode里的project中.

  • 将RCTAMap目录里Frameworks目录拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 将RCTAMap目录里Frameworks目录里的AMap.bundle拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 点击你的主project, 选择Build Phases -> Link Binary With Libraries, 将RCTAMap.xcodeproj里Product目录下的libRCTAMap.a拖进去.

  • 同上位置, 选择Add items, 将系统库libstdc++.6.0.9.tbd加入.

  • 同上位置, 选择Add items, 将系统库libc++.tbd加入.

  • 同上位置, 选择Add items, 将系统库libz.tbd加入.

  • 同上位置, 选择Add items, 将系统库Security.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreTelephony.framework加入.

  • 同上位置, 选择Add items, 将系统库SystemConfiguration.framework加入.

  • 同上位置, 选择Add items, 将系统库JavaScriptCore.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreLocation.framework加入.

  • 选择Build Settings, 找到Header Search Paths, 确认其中包含$(SRCROOT)/../../../react-native/React, 模式为recursive.

  • 同上位置, 找到Framework Search Paths, 加入$(PROJECT_DIR)/Frameworks.

  • 点击在Libraries下已拖进来的RCTAMap.xcodeproj, 选择Build Settings, 找到Framework Search Paths, 将$(SRCROOT)/../../../ios/Frameworks替换成$(SRCROOT)/../../../../ios/Frameworks.

  • info.plist中加入Privacy - Location When In Use Usage Description属性(ios 10)

  • info.plist中加入Allow Arbitrary Loads属性, 并设置值为YES(ios 10)

  • AppDelegate.m


...
#import <AMapFoundationKit/AMapFoundationKit.h> //引入高德地图核心包
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[AMapServices sharedServices].apiKey = @"请填写您的key"; //设置高德地图SDK服务key
...
}
...

安装 (Android)

  • android/settings.gradle
...
include ':react-native-smart-amap'
project(':react-native-smart-amap').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-smart-amap/android')
  • android/app/build.gradle
...
dependencies {
...
// From node_modules
compile project(':react-native-smart-amap')
}
  • MainApplication.java
...
import com.reactnativecomponent.amaplocation.RCTAMapPackage; //import package
...
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RCTAMapPackage() //register Module
);
}
...
  • AndroidManifest.xml中, 加入所需权限

...
<!--*************************高德地图-定位所需要权限*************************-->
<!-- Normal Permissions 不需要运行时注册 -->
<!--获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<!-- 请求网络 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 不是SDK需要的权限,是示例中的后台唤醒定位需要的权限 -->
<!--<uses-permission android:name="android.permission.WAKE_LOCK" />-->
<!-- 需要运行时注册的权限 -->
<!--用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--用于访问GPS定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--用于提高GPS定位速度-->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<!--写入扩展存储,向扩展卡写入数据,用于写入缓存定位数据-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--读取缓存数据-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 更改设置 -->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!--*************************高德地图-定位所需要权限*************************-->
...
  • AndroidManifest.xml中, application标签内加入

...
<!--高德地图SDK key设置-->
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="请填写您的key"/>
<!--高德地图APS服务设置-->
<service android:name="com.amap.api.location.APSService" >
</service>
...

完整示例

点击这里 ReactNativeComponentDemos

使用简介

Install the package from npm with npm install react-native-smart-amap --save. Then, require it from your app's JavaScript files with import Barcode from 'react-native-smart-amap'.

importReact,{Component,}from'react'import{StyleSheet,View,Text,Image,NativeAppEventEmitter,TouchableHighlight,ListView,Dimensions,Alert,Platform,}from'react-native'importAMapLocationfrom'react-native-smart-amap-location'importAMapfrom'react-native-smart-amap'importButtonfrom'react-native-smart-button'importAppEventListenerEnhancefrom'react-native-smart-app-event-listener-enhance'importPullToRefreshListViewfrom'react-native-smart-pull-to-refresh-listview'importTimerEnhancefrom'react-native-smart-timer-enhance'importAMapALoneNearByListfrom'./amp-alone-nearby-list'importListViewActivityIndicatorfrom'./ListViewActivityIndicator'const{width: deviceWidth,height: deviceHeight}=Dimensions.get('window')classAMapDemoextendsComponent{constructor(props){super(props);this._amap=nullthis._page=0this._coordinate=this.props.navigator.navigationContext._currentRoute.coordinateconsole.log(`this._coordinate -> `)console.log(this._coordinate)this._keywords='商务住宅|学校'this._onDidMoveByUserTimer=null}componentDidMount(){this.addAppEventListener(NativeAppEventEmitter.addListener('amap.location.onLocationResult',this._onLocationResult),NativeAppEventEmitter.addListener('amap.onPOISearchDone',this._onPOISearchDone)//NativeAppEventEmitter.addListener('amap.onPOISearchFailed', this._onPOISearchFailed))}render(){//console.log(`amap-alone render...`)return(<Viewstyle={{marginTop: (Platform.OS=='ios' ? 20+44 : 56),flex: 1,}}><Viewstyle={{position: 'relative',height: (deviceHeight-(Platform.OS=='ios' ? 64 : 56))-50*5,}}><AMapref={component=>this._amap=component}style={{flex: 1,}}options={{frame: {width: deviceWidth,height: (deviceHeight-64)-50*5},showsUserLocation: false,userTrackingMode: Platform.OS=='ios' ? AMap.constants.userTrackingMode.none : null,centerCoordinate: {latitude: this._coordinate.latitude,longitude: this._coordinate.longitude,},zoomLevel: 18.1,centerMarker: Platform.OS=='ios' ? 'icon_location' : 'poi_marker',}}onLayout={this._onLayout}onDidMoveByUser={this._onDidMoveByUser}/><ButtontouchableType={Button.constants.touchableTypes.highlight}underlayColor={'#ccc'}style={{padding: 5,position: 'absolute',left: 10,bottom: 20,backgroundColor: '#fff',justifyContent: 'center',borderRadius: 3,borderWidth: StyleSheet.hairlineWidth,borderColor: '#ffffff',justifyContent: 'center',}}onPress={()=>{AMapLocation.init(null)AMapLocation.getLocation()//this._activityIndicator.setState({ visible: true,})}}><Imagesource={{uri: Platform.OS=='ios' ? 'gpsStat1' : 'gps_stat1'}}style={{width: 28,height: 28,}}/></Button></View><Viewstyle={{flex: 1,position: 'relative',}}><AMapALoneNearByListref={(component)=>this._amapALoneNearByList=component}onRefresh={this._onRefresh}onLoadMore={this._onLoadMore}/><ListViewActivityIndicatorref={(component)=>this._activityIndicator=component}style={{marginRight: 10,position:'absolute',left: (deviceWidth-20)/2,top: (50*5-20)/2,}}color={'#a9a9a9'}/></View></View>)}_onDidMoveByUser=(e)=>{//console.log(`_onDidMoveByUser....`)if(this._onDidMoveByUserTimer){this.clearTimeout(this._onDidMoveByUserTimer)this._onDidMoveByUserTimer=null}let{ longitude, latitude,}=e.nativeEvent.data.centerCoordinatethis._onDidMoveByUserTimer=this.setTimeout(()=>{let{refresh_none, refresh_idle, load_more_none, load_more_idle, loaded_all,}=PullToRefreshListView.constants.viewStateif((this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_none||this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_idle)&&(this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_none||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_idle||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==loaded_all)){console.log(`beginRefresh(true)....`)this._coordinate={
longitude,
latitude,}this._activityIndicator.setState({visible: true,})this._amapALoneNearByList._pullToRefreshListView._scrollView.scrollTo({y: 0,animated: false,})this._amapALoneNearByList._pullToRefreshListView.beginRefresh(true)//this._amapALoneNearByList._pullToRefreshListView.beginRefresh()this._beginRefresh=true}},300)}_onLocationResult=(result)=>{if(result.error){console.log(`map-错误代码: ${result.error.code}, map-错误信息: ${result.error.localizedDescription}`)}else{if(result.formattedAddress){console.log(`map-格式化地址 = ${result.formattedAddress}`)}else{console.log(`map-纬度 = ${result.coordinate.latitude}, map-经度 = ${result.coordinate.longitude}`)this._coordinate={latitude: result.coordinate.latitude,longitude: result.coordinate.longitude,}this._amap.setOptions({zoomLevel: 18.1,})this._amap.setCenterCoordinate(this._coordinate)}}}//_onPOISearchFailed = (e) => {// //console.log(`_onPOISearchFailed...`)// //console.log(e)// //console.log(e.error)// this._page--;//}_onPOISearchDone=(result)=>{console.log(`_onPOISearchDone...`)if(Platform.OS=='ios'){this._endSearch(result)}else{this.setTimeout(()=>{this._endSearch(result)},255)}}_endSearch=(result)=>{let{ searchResultList, error }=resultconsole.log(result.error)if(error){if(this._page==1){this._page--this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}else{this._amapALoneNearByList._pullToRefreshListView.endLoadMore(false)}return}console.log(`this._page = ${this._page}`)//onRefreshif(this._page==1){this._amapALoneNearByList.setState({dataList: searchResultList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(searchResultList),})this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}//onLoadMoreelse{letnewDataList=this._amapALoneNearByList.state.dataList.concat(searchResultList)this._amapALoneNearByList.setState({dataList: newDataList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(newDataList),})letloadedAllif(searchResultList.length==100){loadedAll=truethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}else{loadedAll=falsethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}}}_searchNearBy=(searchParams)=>{this._amap.searchPoiByCenterCoordinate(searchParams)}_onRefresh=()=>{console.log(`outer _onRefresh...`)this._searchNearBy({page: (this._page=1),coordinate: this._coordinate,keywords: this._keywords,})}_onLoadMore=()=>{console.log(`outer _onLoadMore...`)this._searchNearBy({page: ++this._page,coordinate: this._coordinate,keywords: this._keywords,})}}exportdefaultTimerEnhance(AppEventListenerEnhance(AMapDemo))

属性

PropTypeOptionalDefaultDescription
optionsobjectNo地图参数对象
options.frameobjectNoios设置地图宽(width), 高(height), 类型是number
options.showTrafficboolYesios设置是否显示路况, 默认不显示
options.showsUserLocationboolYesios设置是否显示用户位置,默认显示
options.userTrackingModeboolYesios设置追踪用户位置更新的模式,默认不追踪
options.zoomLevelnumberYes指定缩放级别, 默认为最大级别
options.centerCoordinateobjectYes根据经度(latitude)纬度(longitude)指定地图的中心点, 类型是number
options.centerMarkerstringYes设置中心点自定义图标的项目资源名称, 如为空则不显示中心点图标

方法

  • setOptions

    • 描述: 更改地图参数
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: options 类型: object, 地图参数, 数据结构同上Props中的options
  • setCenterCoordinate

    • 描述: 根据经纬度在地图中心位置显示
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: coordinate 类型: object, 经纬度坐标参数, 数据结构同上Props中的options.centerCoordinate
  • searchPoiByCenterCoordinate

    • 描述: 根据经纬度坐标来搜索周边的POI
    • 参数: params 类型: object, 搜索参数, 数据结构如下: * types 类型: string 表示搜索类型,多个类型用“|”分割 可选值:文本分类、分类代码 * sortrule 类型: number 表示排序规则, 0-距离排序;1-综合排序, 默认1 * offset 类型: number 表示每页记录数, 范围1-50, 默认20 * page 类型: number 表示当前页数, 范围1-100, 默认1 * keywords 类型: string 表示查询关键字,多个关键字用“|”分割 * coordinate 类型: object 表示中心点经纬度, 数据结构同上Props中的options.centerCoordinate * radius 类型: int 表示辐射半径, 默认3000米

事件监听

  • 地图事件: onDidMoveByUser

    • 描述: 监听用户动作, 返回当前地图中心点的经纬度信息
  • 全局事件: amap.onPOISearchDone

    • 描述: 监听POI搜索回调, 返回周边的POI信息

About

react-native 高德地图SDK 插件

Resources

Stars

173 stars

Watchers

8 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

react-native-smart-amap

A AMap Library for React Native apps.

npmnpmnpmnpm

react-native 高德地图SDK 插件, 支持ios与android, 关于使用高德地图SDK, 申请应用key等详细信息请点击这里

Mac下Android Studio中获取SHA1和MD5请点击这里

预览

react-native-smart-amap-preview-ios

安装

npm install react-native-smart-amap --save

Notice

这个版本仅支持react-native 0.40及以上, 如果你想使用旧版本,使用npm install react-native-smart-amap@untilRN0.40 --save

安装 (iOS)

  • 将RCTAMap.xcodeproj作为Library拖进你的Xcode里的project中.

  • 将RCTAMap目录里Frameworks目录拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 将RCTAMap目录里Frameworks目录里的AMap.bundle拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 点击你的主project, 选择Build Phases -> Link Binary With Libraries, 将RCTAMap.xcodeproj里Product目录下的libRCTAMap.a拖进去.

  • 同上位置, 选择Add items, 将系统库libstdc++.6.0.9.tbd加入.

  • 同上位置, 选择Add items, 将系统库libc++.tbd加入.

  • 同上位置, 选择Add items, 将系统库libz.tbd加入.

  • 同上位置, 选择Add items, 将系统库Security.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreTelephony.framework加入.

  • 同上位置, 选择Add items, 将系统库SystemConfiguration.framework加入.

  • 同上位置, 选择Add items, 将系统库JavaScriptCore.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreLocation.framework加入.

  • 选择Build Settings, 找到Header Search Paths, 确认其中包含$(SRCROOT)/../../../react-native/React, 模式为recursive.

  • 同上位置, 找到Framework Search Paths, 加入$(PROJECT_DIR)/Frameworks.

  • 点击在Libraries下已拖进来的RCTAMap.xcodeproj, 选择Build Settings, 找到Framework Search Paths, 将$(SRCROOT)/../../../ios/Frameworks替换成$(SRCROOT)/../../../../ios/Frameworks.

  • info.plist中加入Privacy - Location When In Use Usage Description属性(ios 10)

  • info.plist中加入Allow Arbitrary Loads属性, 并设置值为YES(ios 10)

  • AppDelegate.m


...
#import <AMapFoundationKit/AMapFoundationKit.h> //引入高德地图核心包
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[AMapServices sharedServices].apiKey = @"请填写您的key"; //设置高德地图SDK服务key
...
}
...

安装 (Android)

  • android/settings.gradle
...
include ':react-native-smart-amap'
project(':react-native-smart-amap').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-smart-amap/android')
  • android/app/build.gradle
...
dependencies {
...
// From node_modules
compile project(':react-native-smart-amap')
}
  • MainApplication.java
...
import com.reactnativecomponent.amaplocation.RCTAMapPackage; //import package
...
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RCTAMapPackage() //register Module
);
}
...
  • AndroidManifest.xml中, 加入所需权限

...
<!--*************************高德地图-定位所需要权限*************************-->
<!-- Normal Permissions 不需要运行时注册 -->
<!--获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<!-- 请求网络 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 不是SDK需要的权限,是示例中的后台唤醒定位需要的权限 -->
<!--<uses-permission android:name="android.permission.WAKE_LOCK" />-->
<!-- 需要运行时注册的权限 -->
<!--用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--用于访问GPS定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--用于提高GPS定位速度-->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<!--写入扩展存储,向扩展卡写入数据,用于写入缓存定位数据-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--读取缓存数据-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 更改设置 -->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!--*************************高德地图-定位所需要权限*************************-->
...
  • AndroidManifest.xml中, application标签内加入

...
<!--高德地图SDK key设置-->
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="请填写您的key"/>
<!--高德地图APS服务设置-->
<service android:name="com.amap.api.location.APSService" >
</service>
...

完整示例

点击这里 ReactNativeComponentDemos

使用简介

Install the package from npm with npm install react-native-smart-amap --save. Then, require it from your app's JavaScript files with import Barcode from 'react-native-smart-amap'.

importReact,{Component,}from'react'import{StyleSheet,View,Text,Image,NativeAppEventEmitter,TouchableHighlight,ListView,Dimensions,Alert,Platform,}from'react-native'importAMapLocationfrom'react-native-smart-amap-location'importAMapfrom'react-native-smart-amap'importButtonfrom'react-native-smart-button'importAppEventListenerEnhancefrom'react-native-smart-app-event-listener-enhance'importPullToRefreshListViewfrom'react-native-smart-pull-to-refresh-listview'importTimerEnhancefrom'react-native-smart-timer-enhance'importAMapALoneNearByListfrom'./amp-alone-nearby-list'importListViewActivityIndicatorfrom'./ListViewActivityIndicator'const{width: deviceWidth,height: deviceHeight}=Dimensions.get('window')classAMapDemoextendsComponent{constructor(props){super(props);this._amap=nullthis._page=0this._coordinate=this.props.navigator.navigationContext._currentRoute.coordinateconsole.log(`this._coordinate -> `)console.log(this._coordinate)this._keywords='商务住宅|学校'this._onDidMoveByUserTimer=null}componentDidMount(){this.addAppEventListener(NativeAppEventEmitter.addListener('amap.location.onLocationResult',this._onLocationResult),NativeAppEventEmitter.addListener('amap.onPOISearchDone',this._onPOISearchDone)//NativeAppEventEmitter.addListener('amap.onPOISearchFailed', this._onPOISearchFailed))}render(){//console.log(`amap-alone render...`)return(<Viewstyle={{marginTop: (Platform.OS=='ios' ? 20+44 : 56),flex: 1,}}><Viewstyle={{position: 'relative',height: (deviceHeight-(Platform.OS=='ios' ? 64 : 56))-50*5,}}><AMapref={component=>this._amap=component}style={{flex: 1,}}options={{frame: {width: deviceWidth,height: (deviceHeight-64)-50*5},showsUserLocation: false,userTrackingMode: Platform.OS=='ios' ? AMap.constants.userTrackingMode.none : null,centerCoordinate: {latitude: this._coordinate.latitude,longitude: this._coordinate.longitude,},zoomLevel: 18.1,centerMarker: Platform.OS=='ios' ? 'icon_location' : 'poi_marker',}}onLayout={this._onLayout}onDidMoveByUser={this._onDidMoveByUser}/><ButtontouchableType={Button.constants.touchableTypes.highlight}underlayColor={'#ccc'}style={{padding: 5,position: 'absolute',left: 10,bottom: 20,backgroundColor: '#fff',justifyContent: 'center',borderRadius: 3,borderWidth: StyleSheet.hairlineWidth,borderColor: '#ffffff',justifyContent: 'center',}}onPress={()=>{AMapLocation.init(null)AMapLocation.getLocation()//this._activityIndicator.setState({ visible: true,})}}><Imagesource={{uri: Platform.OS=='ios' ? 'gpsStat1' : 'gps_stat1'}}style={{width: 28,height: 28,}}/></Button></View><Viewstyle={{flex: 1,position: 'relative',}}><AMapALoneNearByListref={(component)=>this._amapALoneNearByList=component}onRefresh={this._onRefresh}onLoadMore={this._onLoadMore}/><ListViewActivityIndicatorref={(component)=>this._activityIndicator=component}style={{marginRight: 10,position:'absolute',left: (deviceWidth-20)/2,top: (50*5-20)/2,}}color={'#a9a9a9'}/></View></View>)}_onDidMoveByUser=(e)=>{//console.log(`_onDidMoveByUser....`)if(this._onDidMoveByUserTimer){this.clearTimeout(this._onDidMoveByUserTimer)this._onDidMoveByUserTimer=null}let{ longitude, latitude,}=e.nativeEvent.data.centerCoordinatethis._onDidMoveByUserTimer=this.setTimeout(()=>{let{refresh_none, refresh_idle, load_more_none, load_more_idle, loaded_all,}=PullToRefreshListView.constants.viewStateif((this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_none||this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_idle)&&(this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_none||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_idle||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==loaded_all)){console.log(`beginRefresh(true)....`)this._coordinate={
longitude,
latitude,}this._activityIndicator.setState({visible: true,})this._amapALoneNearByList._pullToRefreshListView._scrollView.scrollTo({y: 0,animated: false,})this._amapALoneNearByList._pullToRefreshListView.beginRefresh(true)//this._amapALoneNearByList._pullToRefreshListView.beginRefresh()this._beginRefresh=true}},300)}_onLocationResult=(result)=>{if(result.error){console.log(`map-错误代码: ${result.error.code}, map-错误信息: ${result.error.localizedDescription}`)}else{if(result.formattedAddress){console.log(`map-格式化地址 = ${result.formattedAddress}`)}else{console.log(`map-纬度 = ${result.coordinate.latitude}, map-经度 = ${result.coordinate.longitude}`)this._coordinate={latitude: result.coordinate.latitude,longitude: result.coordinate.longitude,}this._amap.setOptions({zoomLevel: 18.1,})this._amap.setCenterCoordinate(this._coordinate)}}}//_onPOISearchFailed = (e) => {// //console.log(`_onPOISearchFailed...`)// //console.log(e)// //console.log(e.error)// this._page--;//}_onPOISearchDone=(result)=>{console.log(`_onPOISearchDone...`)if(Platform.OS=='ios'){this._endSearch(result)}else{this.setTimeout(()=>{this._endSearch(result)},255)}}_endSearch=(result)=>{let{ searchResultList, error }=resultconsole.log(result.error)if(error){if(this._page==1){this._page--this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}else{this._amapALoneNearByList._pullToRefreshListView.endLoadMore(false)}return}console.log(`this._page = ${this._page}`)//onRefreshif(this._page==1){this._amapALoneNearByList.setState({dataList: searchResultList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(searchResultList),})this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}//onLoadMoreelse{letnewDataList=this._amapALoneNearByList.state.dataList.concat(searchResultList)this._amapALoneNearByList.setState({dataList: newDataList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(newDataList),})letloadedAllif(searchResultList.length==100){loadedAll=truethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}else{loadedAll=falsethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}}}_searchNearBy=(searchParams)=>{this._amap.searchPoiByCenterCoordinate(searchParams)}_onRefresh=()=>{console.log(`outer _onRefresh...`)this._searchNearBy({page: (this._page=1),coordinate: this._coordinate,keywords: this._keywords,})}_onLoadMore=()=>{console.log(`outer _onLoadMore...`)this._searchNearBy({page: ++this._page,coordinate: this._coordinate,keywords: this._keywords,})}}exportdefaultTimerEnhance(AppEventListenerEnhance(AMapDemo))

属性

PropTypeOptionalDefaultDescription
optionsobjectNo地图参数对象
options.frameobjectNoios设置地图宽(width), 高(height), 类型是number
options.showTrafficboolYesios设置是否显示路况, 默认不显示
options.showsUserLocationboolYesios设置是否显示用户位置,默认显示
options.userTrackingModeboolYesios设置追踪用户位置更新的模式,默认不追踪
options.zoomLevelnumberYes指定缩放级别, 默认为最大级别
options.centerCoordinateobjectYes根据经度(latitude)纬度(longitude)指定地图的中心点, 类型是number
options.centerMarkerstringYes设置中心点自定义图标的项目资源名称, 如为空则不显示中心点图标

方法

  • setOptions

    • 描述: 更改地图参数
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: options 类型: object, 地图参数, 数据结构同上Props中的options
  • setCenterCoordinate

    • 描述: 根据经纬度在地图中心位置显示
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: coordinate 类型: object, 经纬度坐标参数, 数据结构同上Props中的options.centerCoordinate
  • searchPoiByCenterCoordinate

    • 描述: 根据经纬度坐标来搜索周边的POI
    • 参数: params 类型: object, 搜索参数, 数据结构如下: * types 类型: string 表示搜索类型,多个类型用“|”分割 可选值:文本分类、分类代码 * sortrule 类型: number 表示排序规则, 0-距离排序;1-综合排序, 默认1 * offset 类型: number 表示每页记录数, 范围1-50, 默认20 * page 类型: number 表示当前页数, 范围1-100, 默认1 * keywords 类型: string 表示查询关键字,多个关键字用“|”分割 * coordinate 类型: object 表示中心点经纬度, 数据结构同上Props中的options.centerCoordinate * radius 类型: int 表示辐射半径, 默认3000米

事件监听

  • 地图事件: onDidMoveByUser

    • 描述: 监听用户动作, 返回当前地图中心点的经纬度信息
  • 全局事件: amap.onPOISearchDone

    • 描述: 监听POI搜索回调, 返回周边的POI信息

About

react-native 高德地图SDK 插件

Resources

Stars

173 stars

Watchers

8 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

react-native-smart-amap

A AMap Library for React Native apps.

npmnpmnpmnpm

react-native 高德地图SDK 插件, 支持ios与android, 关于使用高德地图SDK, 申请应用key等详细信息请点击这里

Mac下Android Studio中获取SHA1和MD5请点击这里

预览

react-native-smart-amap-preview-ios

安装

npm install react-native-smart-amap --save

Notice

这个版本仅支持react-native 0.40及以上, 如果你想使用旧版本,使用npm install react-native-smart-amap@untilRN0.40 --save

安装 (iOS)

  • 将RCTAMap.xcodeproj作为Library拖进你的Xcode里的project中.

  • 将RCTAMap目录里Frameworks目录拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 将RCTAMap目录里Frameworks目录里的AMap.bundle拖进主project目录下, 选择copy items if needed, create groups, 另外add to target不要忘记选择主project.

  • 点击你的主project, 选择Build Phases -> Link Binary With Libraries, 将RCTAMap.xcodeproj里Product目录下的libRCTAMap.a拖进去.

  • 同上位置, 选择Add items, 将系统库libstdc++.6.0.9.tbd加入.

  • 同上位置, 选择Add items, 将系统库libc++.tbd加入.

  • 同上位置, 选择Add items, 将系统库libz.tbd加入.

  • 同上位置, 选择Add items, 将系统库Security.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreTelephony.framework加入.

  • 同上位置, 选择Add items, 将系统库SystemConfiguration.framework加入.

  • 同上位置, 选择Add items, 将系统库JavaScriptCore.framework加入.

  • 同上位置, 选择Add items, 将系统库CoreLocation.framework加入.

  • 选择Build Settings, 找到Header Search Paths, 确认其中包含$(SRCROOT)/../../../react-native/React, 模式为recursive.

  • 同上位置, 找到Framework Search Paths, 加入$(PROJECT_DIR)/Frameworks.

  • 点击在Libraries下已拖进来的RCTAMap.xcodeproj, 选择Build Settings, 找到Framework Search Paths, 将$(SRCROOT)/../../../ios/Frameworks替换成$(SRCROOT)/../../../../ios/Frameworks.

  • info.plist中加入Privacy - Location When In Use Usage Description属性(ios 10)

  • info.plist中加入Allow Arbitrary Loads属性, 并设置值为YES(ios 10)

  • AppDelegate.m


...
#import <AMapFoundationKit/AMapFoundationKit.h> //引入高德地图核心包
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[AMapServices sharedServices].apiKey = @"请填写您的key"; //设置高德地图SDK服务key
...
}
...

安装 (Android)

  • android/settings.gradle
...
include ':react-native-smart-amap'
project(':react-native-smart-amap').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-smart-amap/android')
  • android/app/build.gradle
...
dependencies {
...
// From node_modules
compile project(':react-native-smart-amap')
}
  • MainApplication.java
...
import com.reactnativecomponent.amaplocation.RCTAMapPackage; //import package
...
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RCTAMapPackage() //register Module
);
}
...
  • AndroidManifest.xml中, 加入所需权限

...
<!--*************************高德地图-定位所需要权限*************************-->
<!-- Normal Permissions 不需要运行时注册 -->
<!--获取运营商信息,用于支持提供运营商信息相关的接口-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--用于访问wifi网络信息,wifi信息会用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<!-- 请求网络 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 不是SDK需要的权限,是示例中的后台唤醒定位需要的权限 -->
<!--<uses-permission android:name="android.permission.WAKE_LOCK" />-->
<!-- 需要运行时注册的权限 -->
<!--用于进行网络定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--用于访问GPS定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--用于提高GPS定位速度-->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<!--写入扩展存储,向扩展卡写入数据,用于写入缓存定位数据-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--读取缓存数据-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!--用于读取手机当前的状态-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 更改设置 -->
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<!--*************************高德地图-定位所需要权限*************************-->
...
  • AndroidManifest.xml中, application标签内加入

...
<!--高德地图SDK key设置-->
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="请填写您的key"/>
<!--高德地图APS服务设置-->
<service android:name="com.amap.api.location.APSService" >
</service>
...

完整示例

点击这里 ReactNativeComponentDemos

使用简介

Install the package from npm with npm install react-native-smart-amap --save. Then, require it from your app's JavaScript files with import Barcode from 'react-native-smart-amap'.

importReact,{Component,}from'react'import{StyleSheet,View,Text,Image,NativeAppEventEmitter,TouchableHighlight,ListView,Dimensions,Alert,Platform,}from'react-native'importAMapLocationfrom'react-native-smart-amap-location'importAMapfrom'react-native-smart-amap'importButtonfrom'react-native-smart-button'importAppEventListenerEnhancefrom'react-native-smart-app-event-listener-enhance'importPullToRefreshListViewfrom'react-native-smart-pull-to-refresh-listview'importTimerEnhancefrom'react-native-smart-timer-enhance'importAMapALoneNearByListfrom'./amp-alone-nearby-list'importListViewActivityIndicatorfrom'./ListViewActivityIndicator'const{width: deviceWidth,height: deviceHeight}=Dimensions.get('window')classAMapDemoextendsComponent{constructor(props){super(props);this._amap=nullthis._page=0this._coordinate=this.props.navigator.navigationContext._currentRoute.coordinateconsole.log(`this._coordinate -> `)console.log(this._coordinate)this._keywords='商务住宅|学校'this._onDidMoveByUserTimer=null}componentDidMount(){this.addAppEventListener(NativeAppEventEmitter.addListener('amap.location.onLocationResult',this._onLocationResult),NativeAppEventEmitter.addListener('amap.onPOISearchDone',this._onPOISearchDone)//NativeAppEventEmitter.addListener('amap.onPOISearchFailed', this._onPOISearchFailed))}render(){//console.log(`amap-alone render...`)return(<Viewstyle={{marginTop: (Platform.OS=='ios' ? 20+44 : 56),flex: 1,}}><Viewstyle={{position: 'relative',height: (deviceHeight-(Platform.OS=='ios' ? 64 : 56))-50*5,}}><AMapref={component=>this._amap=component}style={{flex: 1,}}options={{frame: {width: deviceWidth,height: (deviceHeight-64)-50*5},showsUserLocation: false,userTrackingMode: Platform.OS=='ios' ? AMap.constants.userTrackingMode.none : null,centerCoordinate: {latitude: this._coordinate.latitude,longitude: this._coordinate.longitude,},zoomLevel: 18.1,centerMarker: Platform.OS=='ios' ? 'icon_location' : 'poi_marker',}}onLayout={this._onLayout}onDidMoveByUser={this._onDidMoveByUser}/><ButtontouchableType={Button.constants.touchableTypes.highlight}underlayColor={'#ccc'}style={{padding: 5,position: 'absolute',left: 10,bottom: 20,backgroundColor: '#fff',justifyContent: 'center',borderRadius: 3,borderWidth: StyleSheet.hairlineWidth,borderColor: '#ffffff',justifyContent: 'center',}}onPress={()=>{AMapLocation.init(null)AMapLocation.getLocation()//this._activityIndicator.setState({ visible: true,})}}><Imagesource={{uri: Platform.OS=='ios' ? 'gpsStat1' : 'gps_stat1'}}style={{width: 28,height: 28,}}/></Button></View><Viewstyle={{flex: 1,position: 'relative',}}><AMapALoneNearByListref={(component)=>this._amapALoneNearByList=component}onRefresh={this._onRefresh}onLoadMore={this._onLoadMore}/><ListViewActivityIndicatorref={(component)=>this._activityIndicator=component}style={{marginRight: 10,position:'absolute',left: (deviceWidth-20)/2,top: (50*5-20)/2,}}color={'#a9a9a9'}/></View></View>)}_onDidMoveByUser=(e)=>{//console.log(`_onDidMoveByUser....`)if(this._onDidMoveByUserTimer){this.clearTimeout(this._onDidMoveByUserTimer)this._onDidMoveByUserTimer=null}let{ longitude, latitude,}=e.nativeEvent.data.centerCoordinatethis._onDidMoveByUserTimer=this.setTimeout(()=>{let{refresh_none, refresh_idle, load_more_none, load_more_idle, loaded_all,}=PullToRefreshListView.constants.viewStateif((this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_none||this._amapALoneNearByList._pullToRefreshListView._refreshState==refresh_idle)&&(this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_none||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==load_more_idle||this._amapALoneNearByList._pullToRefreshListView._loadMoreState==loaded_all)){console.log(`beginRefresh(true)....`)this._coordinate={
longitude,
latitude,}this._activityIndicator.setState({visible: true,})this._amapALoneNearByList._pullToRefreshListView._scrollView.scrollTo({y: 0,animated: false,})this._amapALoneNearByList._pullToRefreshListView.beginRefresh(true)//this._amapALoneNearByList._pullToRefreshListView.beginRefresh()this._beginRefresh=true}},300)}_onLocationResult=(result)=>{if(result.error){console.log(`map-错误代码: ${result.error.code}, map-错误信息: ${result.error.localizedDescription}`)}else{if(result.formattedAddress){console.log(`map-格式化地址 = ${result.formattedAddress}`)}else{console.log(`map-纬度 = ${result.coordinate.latitude}, map-经度 = ${result.coordinate.longitude}`)this._coordinate={latitude: result.coordinate.latitude,longitude: result.coordinate.longitude,}this._amap.setOptions({zoomLevel: 18.1,})this._amap.setCenterCoordinate(this._coordinate)}}}//_onPOISearchFailed = (e) => {// //console.log(`_onPOISearchFailed...`)// //console.log(e)// //console.log(e.error)// this._page--;//}_onPOISearchDone=(result)=>{console.log(`_onPOISearchDone...`)if(Platform.OS=='ios'){this._endSearch(result)}else{this.setTimeout(()=>{this._endSearch(result)},255)}}_endSearch=(result)=>{let{ searchResultList, error }=resultconsole.log(result.error)if(error){if(this._page==1){this._page--this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}else{this._amapALoneNearByList._pullToRefreshListView.endLoadMore(false)}return}console.log(`this._page = ${this._page}`)//onRefreshif(this._page==1){this._amapALoneNearByList.setState({dataList: searchResultList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(searchResultList),})this._amapALoneNearByList._pullToRefreshListView.endRefresh(this._beginRefresh)//this._amapALoneNearByList._pullToRefreshListView.endRefresh()this._beginRefresh=falsethis._activityIndicator.setState({visible: false,})}//onLoadMoreelse{letnewDataList=this._amapALoneNearByList.state.dataList.concat(searchResultList)this._amapALoneNearByList.setState({dataList: newDataList,dataSource: this._amapALoneNearByList._dataSource.cloneWithRows(newDataList),})letloadedAllif(searchResultList.length==100){loadedAll=truethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}else{loadedAll=falsethis._amapALoneNearByList._pullToRefreshListView.endLoadMore(loadedAll)}}}_searchNearBy=(searchParams)=>{this._amap.searchPoiByCenterCoordinate(searchParams)}_onRefresh=()=>{console.log(`outer _onRefresh...`)this._searchNearBy({page: (this._page=1),coordinate: this._coordinate,keywords: this._keywords,})}_onLoadMore=()=>{console.log(`outer _onLoadMore...`)this._searchNearBy({page: ++this._page,coordinate: this._coordinate,keywords: this._keywords,})}}exportdefaultTimerEnhance(AppEventListenerEnhance(AMapDemo))

属性

PropTypeOptionalDefaultDescription
optionsobjectNo地图参数对象
options.frameobjectNoios设置地图宽(width), 高(height), 类型是number
options.showTrafficboolYesios设置是否显示路况, 默认不显示
options.showsUserLocationboolYesios设置是否显示用户位置,默认显示
options.userTrackingModeboolYesios设置追踪用户位置更新的模式,默认不追踪
options.zoomLevelnumberYes指定缩放级别, 默认为最大级别
options.centerCoordinateobjectYes根据经度(latitude)纬度(longitude)指定地图的中心点, 类型是number
options.centerMarkerstringYes设置中心点自定义图标的项目资源名称, 如为空则不显示中心点图标

方法

  • setOptions

    • 描述: 更改地图参数
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: options 类型: object, 地图参数, 数据结构同上Props中的options
  • setCenterCoordinate

    • 描述: 根据经纬度在地图中心位置显示
    • 参数: reactTag 类型: number, 地图的native view id, 根据这个id可以获取到地图的实例
    • 参数: coordinate 类型: object, 经纬度坐标参数, 数据结构同上Props中的options.centerCoordinate
  • searchPoiByCenterCoordinate

    • 描述: 根据经纬度坐标来搜索周边的POI
    • 参数: params 类型: object, 搜索参数, 数据结构如下: * types 类型: string 表示搜索类型,多个类型用“|”分割 可选值:文本分类、分类代码 * sortrule 类型: number 表示排序规则, 0-距离排序;1-综合排序, 默认1 * offset 类型: number 表示每页记录数, 范围1-50, 默认20 * page 类型: number 表示当前页数, 范围1-100, 默认1 * keywords 类型: string 表示查询关键字,多个关键字用“|”分割 * coordinate 类型: object 表示中心点经纬度, 数据结构同上Props中的options.centerCoordinate * radius 类型: int 表示辐射半径, 默认3000米

事件监听

  • 地图事件: onDidMoveByUser

    • 描述: 监听用户动作, 返回当前地图中心点的经纬度信息
  • 全局事件: amap.onPOISearchDone

    • 描述: 监听POI搜索回调, 返回周边的POI信息

About

react-native 高德地图SDK 插件

Resources

Stars

173 stars

Watchers

8 watching

Forks

Releases

Packages

Used by

Contributors

Languages