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];

    /// 顯示定位小藍(lán)點
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;

    /// 顯示室內(nèi)地圖
    _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 設(shè)置 width: 1,也就是上圖中,AMap 的實際寬度其實是兩倍于當(dāng)前屏幕的,通過 inspector 可以看的到。不知道是什么原因,希望有了解的可以在評論中告訴我,感謝。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容