React Native 集成高德地图

使用高德地图前先要申请一个 Key,具体步骤就不再赘述了

AMapView.h

#import <UIKit/UIKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <React/RCTView.h>

@class RCTEventDispatcher;
@interface AMapView: RCTView;
@end

AMapView.m

#import "AMapView.h"
#import "AMapViewController.h"

@interface AMapView ()
@property (nonatomic, strong) AMapViewController * amapVC;
@end

@implementation AMapView

- (instancetype)init
{
  if ((self = [super init])) {
    [AMapServices sharedServices].apiKey = @"你的高德 Key";
    [AMapServices sharedServices].enableHTTPS = YES;
    
    AMapViewController * amapVC = [[AMapViewController alloc] init];
    self.amapVC = amapVC;
    
    [self addSubview:amapVC.view];
  }
  return self;
}
@end

AMapViewController.h

#import <UIKit/UIKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>

@interface AMapViewController : UIViewController
@end

AMapViewController.m

#import "AMapViewController.h"

@implementation AMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    /// 初始化地图
    MAMapView *_mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];

    /// 把地图添加至view
    [self.view addSubview:_mapView];

    /// 显示定位小蓝点
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;

    /// 显示室内地图
    _mapView.showsIndoorMap = YES;
    
    /// 地图缩放等级
    [_mapView setZoomLevel:18 animated:YES];
    [_mapView setUserTrackingMode:MAUserTrackingModeFollowWithHeading animated:YES];
}
@end

AMapViewManager.h

#import <React/RCTViewManager.h>

@interface AMapViewManager : RCTViewManager
@end

AMapViewManager.m

#import "AMapViewManager.h"
#import "React/RCTBridge.h"
#import "React/RCTEventDispatcher.h"
#import "AMapView.h"

@implementation AMapViewManager

RCT_EXPORT_MODULE()

- (UIView *)view
{
  AMapView *map = [[AMapView alloc] init];

  return map;
}
@end

AMap.js

import { requireNativeComponent } from 'react-native'

export default requireNativeComponent('AMapView', null)

在其他页面里就可以使用这个组件啦

import React from 'react'
import AMap from './AMap'
import { View } from 'react-native'

export default class AMapDemo extends React.Component {
    render() {
        return (
            <View>
                <AMap/>
            </View>
        )
    }
}

效果如下:

这里有个问题,如果我不给 AMap 设置 width: 1,也就是上图中,AMap 的实际宽度其实是两倍于当前屏幕的,通过 inspector 可以看的到。不知道是什么原因,希望有了解的可以在评论中告诉我,感谢。

推荐阅读更多精彩内容