Mapbox使用详解

时间:2022-12-09 22:58:03

一、简介:

Mapbox使用详解
Mapbox致力于打造全球最漂亮的个性化地图。
在一次偶然的地图相关资料搜索过程中发现了一个很神奇又很漂亮的地图,这个地图支持高度自定义各种地图元素,比如,道路,水系,绿地,建筑物,背景色,等等。Mapbox打造的Mapbox studio地图制作虚拟工作室,就是一个很完美的地图元素个性化编辑器。另外,我们也可以把自己项目的地理信息数据上传到Mapbox云端,然后在自己项目的客户端展现出来。
Mapbox地图数据来源于Open Street Map(OSM)等其他地图数据供应商,和Google Map、Apple Map等地图厂商的地图数据来源差不多。

二、使用:

1、注册账号:

在 https://www.mapbox.com 网址找到 sign up 注册一个开发者账号。
Mapbox使用详解
进入个人中心后,我们能看到 Integrate Mapbox 字样,我们点进去,然后根据网页的引导,我们最终会得到一个
和我们的项目相关的 Access tokens ,这个 tokens 就是我们访问SDK的唯一key,
Mapbox使用详解
Mapbox使用详解
选择SDK平台,这里我们选择iOS
Mapbox使用详解
然后选择 Cocoapod 安装方式:
Mapbox使用详解
再接下来我们就能看到 Access tokens 了:
Mapbox使用详解

2、引入工程:

这里我们使用下载好的 Mapbox.framework 做示例,当然使用 cocoa pod 也行。
  • 把Mapbox.frameworks 文件拖拽到 “ 项目 -> TARGETS -> Build Phases -> Embed Frameworks ” 这个路径下;
  • 在路径 “项目 -> TARGETS -> Build Phases ->  +  -> New Run Script phase” 粘贴一串 shel l脚本代码 : 
    bash "${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/Mapbox.framework/strip-frameworks.sh"
Mapbox使用详解
接下来把我们的 Access tokens 填写到项目工程的 Info.plist 文件中:
  • 在Info.plist 文件中添加 key 为 MGLMapboxAccessToken 其值为【Access tokens】 字符串;
  • 在Info.plist 文件中添加 key 为 NSLocationWhenInUseUsageDescription 其值为 bool 类型的 YES;

Mapbox使用详解

3、Mapbox.framework类的使用:

【1】加载地图:

  1. #import "LoadMapboxViewController.h"
  2. #import <Mapbox/Mapbox.h>
  3. @interface LoadMapboxViewController ()<MGLMapViewDelegate>
  4. @property (nonatomic, strong) MGLMapView *mapView;
  5. @end
  6. @implementation LoadMapboxViewController
  7. - (void)viewDidLoad {
  8. [super viewDidLoad];
  9. // Do any additional setup after loading the view.
  10. self.title = @"加载地图";
  11. [self.view addSubview:self.mapView];
  12. }
  13. - (MGLMapView *)mapView {
  14. if (_mapView == nil) {
  15. //设置地图的 frame 和 地图个性化样式
  16. _mapView = [[MGLMapView alloc] initWithFrame:self.view.bounds styleURL:[NSURL URLWithString:@"mapbox://styles/mapbox/streets-v10"]];
  17. _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  18. //设置地图默认显示的地点和缩放等级
  19. [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(39.980528, 116.306745) zoomLevel:15 animated:YES];
  20. //显示用户位置
  21. _mapView.showsUserLocation = YES;
  22. //定位模式
  23. _mapView.userTrackingMode = MGLUserTrackingModeFollow;
  24. //是否倾斜地图
  25. _mapView.pitchEnabled = YES;
  26. //是否旋转地图
  27. _mapView.rotateEnabled = NO;
  28. //代理
  29. _mapView.delegate = self;
  30. }
  31. return _mapView;
  32. }
  33. @end

Mapbox使用详解

【2】加载各种样式的地图:

我们可以通过如下代码修改地图样式:
[self.mapView setStyleURL:[NSURL URLWithString:@"mapbox://styles/mapbox/streets-v10"]];

这是所有地图已经做好的模板样式参数:

  • mapbox://styles/mapbox/streets-v10
  • mapbox://styles/mapbox/outdoors-v10
  • mapbox://styles/mapbox/light-v9
  • mapbox://styles/mapbox/dark-v9
  • mapbox://styles/mapbox/satellite-v9
  • mapbox://styles/mapbox/satellite-streets-v10
  • mapbox://styles/mapbox/navigation-preview-day-v2
  • mapbox://styles/mapbox/navigation-preview-night-v2
  • mapbox://styles/mapbox/navigation-guidance-day-v2
  • mapbox://styles/mapbox/navigation-guidance-night-v2

使用不同的参数呈现出来的地图风格变不一样。

Mapbox使用详解

【3】加载大头针和默认气泡:

  1. //
  2. // DefaultAnnotationCalloutViewController.m
  3. // MapboxExample
  4. //
  5. // Created by iron on 2018/1/30.
  6. // Copyright © 2018年 wangzhengang. All rights reserved.
  7. //
  8. #import "DefaultAnnotationCalloutViewController.h"
  9. #import <Mapbox/Mapbox.h>
  10. @interface DefaultAnnotationCalloutViewController ()<MGLMapViewDelegate>
  11. @property (nonatomic, strong) MGLMapView *mapView;
  12. @property (nonatomic, copy) NSArray *annotationsArray;
  13. @end
  14. @implementation DefaultAnnotationCalloutViewController
  15. - (void)dealloc {
  16. [_mapView removeFromSuperview];
  17. _mapView.delegate = nil;
  18. _mapView = nil;
  19. }
  20. - (void)viewDidLoad {
  21. [super viewDidLoad];
  22. [self.view addSubview:self.mapView];
  23. }
  24. - (void)didReceiveMemoryWarning {
  25. [super didReceiveMemoryWarning];
  26. // Dispose of any resources that can be recreated.
  27. }
  28. - (MGLMapView *)mapView {
  29. if (_mapView == nil) {
  30. //设置地图的 frame 和 地图个性化样式
  31. _mapView = [[MGLMapView alloc] initWithFrame:self.view.bounds styleURL:[NSURL URLWithString:@"mapbox://styles/mapbox/streets-v10"]];
  32. _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  33. //设置地图默认显示的地点和缩放等级
  34. [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(39.980528, 116.306745) zoomLevel:15 animated:NO];
  35. //显示用户位置
  36. _mapView.showsUserLocation = YES;
  37. //定位模式
  38. _mapView.userTrackingMode = MGLUserTrackingModeNone;
  39. //是否倾斜地图
  40. _mapView.pitchEnabled = YES;
  41. //是否旋转地图
  42. _mapView.rotateEnabled = NO;
  43. //代理
  44. _mapView.delegate = self;
  45. }
  46. return _mapView;
  47. }
  48. - (NSArray *)annotationsArray {
  49. if (_annotationsArray == nil) {
  50. CLLocationCoordinate2D coords[2];
  51. coords[0] = CLLocationCoordinate2DMake(39.980528, 116.306745);
  52. coords[1] = CLLocationCoordinate2DMake(40.000, 116.306745);
  53. NSMutableArray *pointsArray = [NSMutableArray array];
  54. for (NSInteger i = 0; i < 2; ++i) {
  55. MGLPointAnnotation *pointAnnotation = [[MGLPointAnnotation alloc] init];
  56. pointAnnotation.coordinate = coords[i];
  57. pointAnnotation.title = [NSString stringWithFormat:@"title:%ld", (long)i];
  58. pointAnnotation.subtitle = [NSString stringWithFormat:@"subtitle: %ld%ld%ld", (long)i,(long)i,(long)i];
  59. [pointsArray addObject:pointAnnotation];
  60. }
  61. _annotationsArray = [pointsArray copy];
  62. }
  63. return _annotationsArray;
  64. }
  65. #pragma mark MGLMapViewDelegate
  66. - (void)mapViewDidFinishLoadingMap:(MGLMapView *)mapView {
  67. ///地图加载完成时加载大头针
  68. [mapView addAnnotations:self.annotationsArray];
  69. }
  70. - (MGLAnnotationView *)mapView:(MGLMapView *)mapView viewForAnnotation:(id<MGLAnnotation>)annotation {
  71. if (![annotation isKindOfClass:[MGLPointAnnotation class]]) {
  72. return nil;
  73. }
  74. MGLAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"MGLAnnotationView"];
  75. if (annotationView == nil) {
  76. annotationView = [[MGLAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MGLAnnotationView"];
  77. [annotationView setFrame:CGRectMake(0, 0, 40, 40)];
  78. [annotationView setBackgroundColor:[UIColor redColor]];
  79. annotationView.layer.cornerRadius = 20.f;
  80. annotationView.layer.masksToBounds= YES;
  81. annotationView.layer.borderColor = [UIColor whiteColor].CGColor;
  82. annotationView.layer.borderWidth = 5.f;
  83. }
  84. return annotationView;
  85. }
  86. ///是否显示气泡
  87. -(BOOL)mapView:(MGLMapView *)mapView annotationCanShowCallout:(id<MGLAnnotation>)annotation {
  88. return YES;
  89. }
  90. ///完成加载大头针
  91. - (void)mapView:(MGLMapView *)mapView didAddAnnotationViews:(NSArray<MGLAnnotationView *> *)annotationViews {
  92. [mapView showAnnotations:self.annotationsArray edgePadding:UIEdgeInsetsMake(100, 50, 100, 50) animated:YES];
  93. }
  94. ///气泡左侧视图
  95. - (UIView *)mapView:(MGLMapView *)mapView leftCalloutAccessoryViewForAnnotation:(id<MGLAnnotation>)annotation {
  96. UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
  97. view.backgroundColor= [UIColor blueColor];
  98. UILabel *lab = [[UILabel alloc] initWithFrame:view.bounds];
  99. lab.text = @"左侧视图";
  100. lab.textColor = [UIColor whiteColor];
  101. lab.font = [UIFont systemFontOfSize:10];
  102. lab.textAlignment = NSTextAlignmentCenter;
  103. [view addSubview:lab];
  104. return view;
  105. }
  106. ///气泡右侧视图,
  107. - (UIView *)mapView:(MGLMapView *)mapView rightCalloutAccessoryViewForAnnotation:(id<MGLAnnotation>)annotation {
  108. UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
  109. view.backgroundColor= [UIColor greenColor];
  110. UILabel *lab = [[UILabel alloc] initWithFrame:view.bounds];
  111. lab.text = @"右侧视图";
  112. lab.textColor = [UIColor blackColor];
  113. lab.font = [UIFont systemFontOfSize:10];
  114. [view addSubview:lab];
  115. return view;
  116. }
  117. @end

Mapbox使用详解

【4】加载图片大头针和自定义气泡:

  • 创建一个继承 UIview 的类 CustomeMapViewCalloutView  并遵守 < MGLCalloutView > 这个协议;
  • 在 CustomeMapViewCalloutView 中实现各种需求;
实现自定义callout view:
  1. //
  2. // CustomeMapViewCalloutView.h
  3. // Etoury
  4. //
  5. // Created by iron on 2017/5/21.
  6. // Copyright © 2017年 iron. All rights reserved.
  7. //
  8. #import <UIKit/UIKit.h>
  9. #import <Mapbox/Mapbox.h>
  10. @interface CustomeMapViewCalloutView : UIView<MGLCalloutView>
  11. @end
  1. //
  2. // CustomeMapViewCalloutView.m
  3. // Etoury
  4. //
  5. // Created by iron on 2017/5/21.
  6. // Copyright © 2017年 iron. All rights reserved.
  7. //
  8. #import "CustomeMapViewCalloutView.h"
  9. // Set defaults for custom tip drawing
  10. static CGFloat const tipHeight = 10.0;
  11. static CGFloat const tipWidth = 20.0;
  12. @interface CustomeMapViewCalloutView ()
  13. @property (strong, nonatomic) UIButton *mainBody;
  14. @end
  15. @implementation CustomeMapViewCalloutView {
  16. id <MGLAnnotation> _representedObject;
  17. __unused UIView *_leftAccessoryView;/* unused */
  18. __unused UIView *_rightAccessoryView;/* unused */
  19. __weak id <MGLCalloutViewDelegate> _delegate;
  20. BOOL _dismissesAutomatically;
  21. BOOL _anchoredToAnnotation;
  22. }
  23. @synthesize representedObject = _representedObject;
  24. @synthesize leftAccessoryView = _leftAccessoryView;/* unused */
  25. @synthesize rightAccessoryView = _rightAccessoryView;/* unused */
  26. @synthesize delegate = _delegate;
  27. @synthesize anchoredToAnnotation = _anchoredToAnnotation;
  28. @synthesize dismissesAutomatically = _dismissesAutomatically;
  29. - (instancetype)initWithFrame:(CGRect)frame
  30. {
  31. self = [super initWithFrame:frame];
  32. if (self)
  33. {
  34. self.backgroundColor = [UIColor clearColor];
  35. // Create and add a subview to hold the callout’s text
  36. UIButton *mainBody = [UIButton buttonWithType:UIButtonTypeSystem];
  37. mainBody.backgroundColor = [self backgroundColorForCallout];
  38. mainBody.tintColor = [UIColor whiteColor];
  39. mainBody.contentEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0);
  40. mainBody.layer.cornerRadius = 4.0;
  41. self.mainBody = mainBody;
  42. [self addSubview:self.mainBody];
  43. }
  44. return self;
  45. }
  46. #pragma mark - MGLCalloutView API
  47. - (void)presentCalloutFromRect:(CGRect)rect inView:(UIView *)view constrainedToView:(UIView *)constrainedView animated:(BOOL)animated
  48. {
  49. // Do not show a callout if there is no title set for the annotation
  50. if (![self.representedObject respondsToSelector:@selector(title)])
  51. {
  52. return;
  53. }
  54. [view addSubview:self];
  55. // Prepare title label
  56. [self.mainBody setTitle:self.representedObject.title forState:UIControlStateNormal];
  57. [self.mainBody sizeToFit];
  58. if ([self isCalloutTappable])
  59. {
  60. // Handle taps and eventually try to send them to the delegate (usually the map view)
  61. [self.mainBody addTarget:self action:@selector(calloutTapped) forControlEvents:UIControlEventTouchUpInside];
  62. }
  63. else
  64. {
  65. // Disable tapping and highlighting
  66. self.mainBody.userInteractionEnabled = NO;
  67. }
  68. // Prepare our frame, adding extra space at the bottom for the tip
  69. CGFloat frameWidth = self.mainBody.bounds.size.width;
  70. CGFloat frameHeight = self.mainBody.bounds.size.height + tipHeight;
  71. CGFloat frameOriginX = rect.origin.x + (rect.size.width/2.0) - (frameWidth/2.0);
  72. CGFloat frameOriginY = rect.origin.y - frameHeight;
  73. self.frame = CGRectMake(frameOriginX, frameOriginY,
  74. frameWidth, frameHeight);
  75. if (animated)
  76. {
  77. self.alpha = 0.0;
  78. [UIView animateWithDuration:0.2 animations:^{
  79. self.alpha = 1.0;
  80. }];
  81. }
  82. }
  83. - (void)dismissCalloutAnimated:(BOOL)animated
  84. {
  85. if (self.superview)
  86. {
  87. if (animated)
  88. {
  89. [UIView animateWithDuration:0.2 animations:^{
  90. self.alpha = 0.0;
  91. } completion:^(BOOL finished) {
  92. [self removeFromSuperview];
  93. }];
  94. }
  95. else
  96. {
  97. [self removeFromSuperview];
  98. }
  99. }
  100. }
  101. // Allow the callout to remain open during panning.
  102. - (BOOL)dismissesAutomatically {
  103. return NO;
  104. }
  105. - (BOOL)isAnchoredToAnnotation {
  106. return YES;
  107. }
  108. // https://github.com/mapbox/mapbox-gl-native/issues/9228
  109. - (void)setCenter:(CGPoint)center {
  110. center.y = center.y - CGRectGetMidY(self.bounds);
  111. [super setCenter:center];
  112. }
  113. #pragma mark - Callout interaction handlers
  114. - (BOOL)isCalloutTappable
  115. {
  116. if ([self.delegate respondsToSelector:@selector(calloutViewShouldHighlight:)]) {
  117. return [self.delegate performSelector:@selector(calloutViewShouldHighlight:) withObject:self];
  118. }
  119. return NO;
  120. }
  121. - (void)calloutTapped
  122. {
  123. if ([self isCalloutTappable] && [self.delegate respondsToSelector:@selector(calloutViewTapped:)])
  124. {
  125. [self.delegate performSelector:@selector(calloutViewTapped:) withObject:self];
  126. }
  127. }
  128. #pragma mark - Custom view styling
  129. - (UIColor *)backgroundColorForCallout
  130. {
  131. return [UIColor darkGrayColor];
  132. }
  133. - (void)drawRect:(CGRect)rect
  134. {
  135. // Draw the pointed tip at the bottom
  136. UIColor *fillColor = [self backgroundColorForCallout];
  137. CGFloat tipLeft = rect.origin.x + (rect.size.width / 2.0) - (tipWidth / 2.0);
  138. CGPoint tipBottom = CGPointMake(rect.origin.x + (rect.size.width / 2.0), rect.origin.y + rect.size.height);
  139. CGFloat heightWithoutTip = rect.size.height - tipHeight - 1;
  140. CGContextRef currentContext = UIGraphicsGetCurrentContext();
  141. CGMutablePathRef tipPath = CGPathCreateMutable();
  142. CGPathMoveToPoint(tipPath, NULL, tipLeft, heightWithoutTip);
  143. CGPathAddLineToPoint(tipPath, NULL, tipBottom.x, tipBottom.y);
  144. CGPathAddLineToPoint(tipPath, NULL, tipLeft + tipWidth, heightWithoutTip);
  145. CGPathCloseSubpath(tipPath);
  146. [fillColor setFill];
  147. CGContextAddPath(currentContext, tipPath);
  148. CGContextFillPath(currentContext);
  149. CGPathRelease(tipPath);
  150. }
  151. @end

在view controller中使用自定义的callout view:

  1. //
  2. // CustomeAnnotationCalloutViewController.m
  3. // MapboxExample
  4. //
  5. // Created by iron on 2018/1/30.
  6. // Copyright © 2018年 wangzhengang. All rights reserved.
  7. //
  8. #import "CustomeAnnotationCalloutViewController.h"
  9. #import <Mapbox/Mapbox.h>
  10. #import "CustomeMapViewCalloutView.h"
  11. @interface CustomeAnnotationCalloutViewController ()<MGLMapViewDelegate>
  12. @property (nonatomic, strong) MGLMapView *mapView;
  13. @property (nonatomic, copy) NSArray *annotationsArray;
  14. @end
  15. @implementation CustomeAnnotationCalloutViewController
  16. - (void)dealloc {
  17. [_mapView removeFromSuperview];
  18. _mapView.delegate = nil;
  19. _mapView = nil;
  20. }
  21. - (void)viewDidLoad {
  22. [super viewDidLoad];
  23. [self.view addSubview:self.mapView];
  24. }
  25. - (MGLMapView *)mapView {
  26. if (_mapView == nil) {
  27. //设置地图的 frame 和 地图个性化样式
  28. _mapView = [[MGLMapView alloc] initWithFrame:self.view.bounds styleURL:[NSURL URLWithString:@"mapbox://styles/mapbox/streets-v10"]];
  29. _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  30. //设置地图默认显示的地点和缩放等级
  31. [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(39.980528, 116.306745) zoomLevel:15 animated:NO];
  32. //显示用户位置
  33. _mapView.showsUserLocation = YES;
  34. //定位模式
  35. _mapView.userTrackingMode = MGLUserTrackingModeNone;
  36. //是否倾斜地图
  37. _mapView.pitchEnabled = YES;
  38. //是否旋转地图
  39. _mapView.rotateEnabled = NO;
  40. //代理
  41. _mapView.delegate = self;
  42. }
  43. return _mapView;
  44. }
  45. - (NSArray *)annotationsArray {
  46. if (_annotationsArray == nil) {
  47. CLLocationCoordinate2D coords[2];
  48. coords[0] = CLLocationCoordinate2DMake(39.980528, 116.306745);
  49. coords[1] = CLLocationCoordinate2DMake(40.000, 116.306745);
  50. NSMutableArray *pointsArray = [NSMutableArray array];
  51. for (NSInteger i = 0; i < 2; ++i) {
  52. MGLPointAnnotation *pointAnnotation = [[MGLPointAnnotation alloc] init];
  53. pointAnnotation.coordinate = coords[i];
  54. pointAnnotation.title = [NSString stringWithFormat:@"title:%ld", (long)i];
  55. pointAnnotation.subtitle = [NSString stringWithFormat:@"subtitle: %ld%ld%ld", (long)i,(long)i,(long)i];
  56. [pointsArray addObject:pointAnnotation];
  57. }
  58. _annotationsArray = [pointsArray copy];
  59. }
  60. return _annotationsArray;
  61. }
  62. #pragma mark MGLMapViewDelegate
  63. - (void)mapViewDidFinishLoadingMap:(MGLMapView *)mapView {
  64. ///地图加载完成时加载大头针
  65. [mapView addAnnotations:self.annotationsArray];
  66. }
  67. - (MGLAnnotationView *)mapView:(MGLMapView *)mapView viewForAnnotation:(id<MGLAnnotation>)annotation {
  68. if (![annotation isKindOfClass:[MGLPointAnnotation class]]) {
  69. return nil;
  70. }
  71. MGLAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"MGLAnnotationView"];
  72. if (annotationView == nil) {
  73. annotationView = [[MGLAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MGLAnnotationView"];
  74. [annotationView setFrame:CGRectMake(0, 0, 40, 40)];
  75. [annotationView setBackgroundColor:[UIColor redColor]];
  76. annotationView.layer.cornerRadius = 20.f;
  77. annotationView.layer.masksToBounds= YES;
  78. annotationView.layer.borderColor = [UIColor whiteColor].CGColor;
  79. annotationView.layer.borderWidth = 5.f;
  80. }
  81. return annotationView;
  82. }
  83. ///是否显示气泡
  84. -(BOOL)mapView:(MGLMapView *)mapView annotationCanShowCallout:(id<MGLAnnotation>)annotation {
  85. return YES;
  86. }
  87. ///完成加载大头针
  88. - (void)mapView:(MGLMapView *)mapView didAddAnnotationViews:(NSArray<MGLAnnotationView *> *)annotationViews {
  89. [mapView showAnnotations:self.annotationsArray edgePadding:UIEdgeInsetsMake(100, 50, 100, 50) animated:YES];
  90. }
  91. ///加载定义callout view
  92. - (id<MGLCalloutView>)mapView:(MGLMapView *)mapView calloutViewForAnnotation:(id<MGLAnnotation>)annotation {
  93. CustomeMapViewCalloutView *calloutView = [[CustomeMapViewCalloutView alloc] init];
  94. calloutView.representedObject = annotation;
  95. return calloutView;
  96. }
  97. ///气泡点击事件
  98. - (void)mapView:(MGLMapView *)mapView tapOnCalloutForAnnotation:(id<MGLAnnotation>)annotation {
  99. NSLog(@"点击了气泡: %@", annotation);
  100. [mapView deselectAnnotation:annotation animated:YES];
  101. [self showAlertControllerWithViewContorller:self title:@"点击了气泡" message:nil leftButtonTitle:nil rightButtonTitle:@"确定"];
  102. }
  103. #pragma mark - 警告框
  104. - (void)showAlertControllerWithViewContorller:(UIViewController *)viewController title:(NSString *)title message:(NSString *)message leftButtonTitle:(NSString *)leftBtnTitle rightButtonTitle:(NSString *)rightBtnTitle {
  105. UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
  106. if (leftBtnTitle) {
  107. [alert addAction:[UIAlertAction actionWithTitle:leftBtnTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  108. }]];
  109. }
  110. if (rightBtnTitle) {
  111. [alert addAction:[UIAlertAction actionWithTitle:rightBtnTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  112. }]];
  113. }
  114. [viewController presentViewController:alert animated:YES completion:nil];
  115. }
  116. @end

效果如下:

Mapbox使用详解Mapbox使用详解

【5】绘制线段和多边形:

老实说 Mapbox 的 绘制线段和多边形的相关类,相比高德地图和百度地图写的并不好,用起来很不方便,比如:
  • MGLPolygon 有 strokeColor 这个参数,却没有设置 描边线宽度和样式的参数;
  • MGLPolyline 没有 strokeColor 和 fillColor 之分,而且画虚线的代码写起来很麻烦;

总体来讲,MGLPolygon 和 MGLPolyline 这两个类没有高德地图和百度地图那样使用起来方便,另外,MGLPolyline 这个类中的 MGLShapeSource 、MGLStyleLayer 虽然使用起来很麻烦,但是相对来说倒是保持了灵活性。

为了提高 MGLPolygon 和 MGLPolyline 的使用便利性,我对 MGLPolygon 、MGLPolyline 的基类 MGLShape 扩展了几个属性:

  • @property (nonatomic, strong) UIColor *fillColor;//填充颜色
  • @property (nonatomic, assign) CGFloat fillOpacity;//填充透明度
  • @property (nonatomic, strong) UIColor *strokeColor;//描边颜色
  • @property (nonatomic, assign) BOOL isDash;//YES = 虚线/NO = 实线
  • @property (nonatomic, assign) NSInteger strokeWeight;//描边宽度
接下来让我们看看整体代码是如何实现的,以及最后的效果是怎样的:

MGLShape+PolygonParamer.h

  1. //
  2. // MGLShape+PolygonParamer.h
  3. // Etoury
  4. //
  5. // Created by dev on 2018/1/3.
  6. // Copyright © 2018年 iron. All rights reserved.
  7. //
  8. #import <Mapbox/Mapbox.h>
  9. @interface MGLShape (PolygonParamer)
  10. @property (nonatomic, strong) UIColor *fillColor;//填充颜色
  11. @property (nonatomic, assign) CGFloat fillOpacity;//填充透明度
  12. @property (nonatomic, strong) UIColor *strokeColor;//描边颜色
  13. @property (nonatomic, assign) BOOL isDash;//YES = 虚线/NO = 实线
  14. @property (nonatomic, assign) NSInteger strokeWeight;//描边宽度
  15. @end

MGLShape+PolygonParamer.h

  1. //
  2. // MGLShape+PolygonParamer.m
  3. // Etoury
  4. //
  5. // Created by dev on 2018/1/3.
  6. // Copyright © 2018年 iron. All rights reserved.
  7. //
  8. #import "MGLShape+PolygonParamer.h"
  9. #import <objc/runtime.h>
  10. static UIColor *_fillColor;//填充颜色
  11. static NSInteger _fillOpacity;//填充透明度
  12. static UIColor *_strokeColor;//描边颜色
  13. static BOOL _isDash;//YES = 虚线/NO = 实线
  14. static NSInteger _strokeWeight;//描边宽度
  15. @implementation MGLShape (PolygonParamer)
  16. - (void)setFillColor:(UIColor *)fillColor {
  17. objc_setAssociatedObject(self, &_fillColor, fillColor, OBJC_ASSOCIATION_COPY);
  18. }
  19. - (UIColor *)fillColor {
  20. return objc_getAssociatedObject(self, &_fillColor);
  21. }
  22. - (void)setFillOpacity:(CGFloat)fillOpacity {
  23. NSNumber *fillOpacityNumber = @(fillOpacity);
  24. objc_setAssociatedObject(self, &_fillOpacity, fillOpacityNumber, OBJC_ASSOCIATION_COPY);
  25. }
  26. - (CGFloat)fillOpacity {
  27. NSNumber *fillOpacityNumber = objc_getAssociatedObject(self, &_fillOpacity);
  28. return [fillOpacityNumber floatValue];
  29. }
  30. - (void)setStrokeColor:(UIColor *)strokeColor {
  31. objc_setAssociatedObject(self, &_strokeColor, strokeColor, OBJC_ASSOCIATION_COPY);
  32. }
  33. - (UIColor *)strokeColor {
  34. return objc_getAssociatedObject(self, &_strokeColor);
  35. }
  36. - (void)setIsDash:(BOOL)isDash {
  37. NSNumber *isDashNumber = [NSNumber numberWithBool:isDash];
  38. objc_setAssociatedObject(self, &_isDash, isDashNumber, OBJC_ASSOCIATION_COPY);
  39. }
  40. - (BOOL)isDash {
  41. NSNumber *isDashNumber = objc_getAssociatedObject(self, &_isDash);
  42. return [isDashNumber boolValue];
  43. }
  44. - (void)setStrokeWeight:(NSInteger)strokeWeight {
  45. NSNumber *strokeWeightNumber = @(strokeWeight);
  46. objc_setAssociatedObject(self, &_strokeWeight, strokeWeightNumber, OBJC_ASSOCIATION_COPY);
  47. }
  48. - (NSInteger)strokeWeight {
  49. NSNumber *strokeWeightNumber = objc_getAssociatedObject(self, &_strokeWeight);
  50. return [strokeWeightNumber integerValue];
  51. }
  52. @end

把 MGLShape+PolygonParamer引入到 view controller 中:

  1. //
  2. // LinePolygonMapboxViewController.m
  3. // MapboxExample
  4. //
  5. // Created by iron on 2018/1/30.
  6. // Copyright © 2018年 wangzhengang. All rights reserved.
  7. //
  8. #import "LinePolygonMapboxViewController.h"
  9. #import <Mapbox/Mapbox.h>
  10. #import "MGLShape+PolygonParamer.h"
  11. @interface LinePolygonMapboxViewController ()<MGLMapViewDelegate>
  12. @property (nonatomic, strong) MGLMapView *mapView;
  13. @property (nonatomic, strong) MGLPolyline *blueLine;//蓝色线段
  14. @property (nonatomic, strong) MGLPolyline *strokeLine;//多边形边线
  15. @property (nonatomic, strong) MGLPolygon *polygon;//多边形
  16. @end
  17. @implementation LinePolygonMapboxViewController
  18. - (void)dealloc {
  19. [_mapView removeFromSuperview];
  20. _mapView.delegate = nil;
  21. _mapView = nil;
  22. }
  23. - (void)viewDidLoad {
  24. [super viewDidLoad];
  25. self.title = @"线段和多边形";
  26. [self.view addSubview:self.mapView];
  27. }
  28. - (void)didReceiveMemoryWarning {
  29. [super didReceiveMemoryWarning];
  30. // Dispose of any resources that can be recreated.
  31. }
  32. - (MGLMapView *)mapView {
  33. if (_mapView == nil) {
  34. //设置地图的 frame 和 地图个性化样式
  35. _mapView = [[MGLMapView alloc] initWithFrame:self.view.bounds styleURL:[NSURL URLWithString:@"mapbox://styles/mapbox/streets-v10"]];
  36. _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  37. //设置地图默认显示的地点和缩放等级
  38. [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(39.980528, 116.306745) zoomLevel:8 animated:YES];
  39. //显示用户位置
  40. _mapView.showsUserLocation = YES;
  41. //定位模式
  42. _mapView.userTrackingMode = MGLUserTrackingModeNone;
  43. //是否倾斜地图
  44. _mapView.pitchEnabled = YES;
  45. //是否旋转地图
  46. _mapView.rotateEnabled = NO;
  47. //代理
  48. _mapView.delegate = self;
  49. }
  50. return _mapView;
  51. }
  52. - (MGLPolyline *)blueLine {
  53. if (_blueLine == nil) {
  54. CLLocationCoordinate2D coords[3];
  55. coords[0] = CLLocationCoordinate2DMake(27.000, 95.356745);
  56. coords[1] = CLLocationCoordinate2DMake(20.000, 105.356745);
  57. coords[2] = CLLocationCoordinate2DMake(27.000, 115.356745);
  58. _blueLine = [MGLPolyline polylineWithCoordinates:coords count:3];
  59. _blueLine.strokeColor = [UIColor blueColor];
  60. _blueLine.strokeWeight = 3.f;
  61. _blueLine.fillOpacity = 0.75f;
  62. _blueLine.isDash = NO;
  63. }
  64. return _blueLine;
  65. }
  66. - (MGLPolyline *)strokeLine {
  67. if (_strokeLine == nil) {
  68. CLLocationCoordinate2D coords[6];
  69. coords[0] = CLLocationCoordinate2DMake(30.980528, 110.306745);
  70. coords[2] = CLLocationCoordinate2DMake(30.000, 120.306745);
  71. coords[1] = CLLocationCoordinate2DMake(40.000, 120.306745);
  72. coords[3] = CLLocationCoordinate2DMake(40.000, 110.306745);
  73. coords[4] = CLLocationCoordinate2DMake(35.000, 95.356745);
  74. coords[5] = CLLocationCoordinate2DMake(30.980528, 110.306745);;
  75. _strokeLine = [MGLPolyline polylineWithCoordinates:coords count:6];
  76. _strokeLine.strokeColor = [UIColor blackColor];
  77. _strokeLine.strokeWeight = 2.f;
  78. _strokeLine.fillOpacity = 0.75f;
  79. _strokeLine.isDash = YES;
  80. }
  81. return _strokeLine;
  82. }
  83. - (MGLPolygon *)polygon {
  84. if (_polygon == nil) {
  85. CLLocationCoordinate2D coords[6];
  86. coords[0] = CLLocationCoordinate2DMake(30.980528, 110.306745);
  87. coords[2] = CLLocationCoordinate2DMake(30.000, 120.306745);
  88. coords[1] = CLLocationCoordinate2DMake(40.000, 120.306745);
  89. coords[3] = CLLocationCoordinate2DMake(40.000, 110.306745);
  90. coords[4] = CLLocationCoordinate2DMake(35.000, 95.356745);
  91. _polygon = [MGLPolygon polygonWithCoordinates:coords count:5];
  92. _polygon.fillColor = [UIColor redColor];
  93. _polygon.strokeColor = [UIColor blueColor];
  94. _polygon.strokeWeight= 2.f;
  95. _polygon.fillOpacity = 0.5f;
  96. }
  97. return _polygon;
  98. }
  99. #pragma mark MGLMapViewDelegate
  100. - (void)mapViewDidFinishLoadingMap:(MGLMapView *)mapView {
  101. ///地图加载完成后绘制 线段 和 多边形
  102. [mapView addOverlays:@[self.blueLine, self.strokeLine, self.polygon]];
  103. ///把窗口显示到合适的范围
  104. [mapView setVisibleCoordinateBounds:self.polygon.overlayBounds edgePadding:UIEdgeInsetsMake(0, 10, 200, 10) animated:YES];
  105. // [mapView setVisibleCoordinateBounds:self.line.overlayBounds edgePadding:UIEdgeInsetsMake(300, 10, 0, 10) animated:YES];
  106. }
  107. - (CGFloat)mapView:(MGLMapView *)mapView alphaForShapeAnnotation:(MGLShape *)annotation {
  108. ///MGLPolyline 和 MGLPolygon 都执行这个方法
  109. return annotation.fillOpacity;
  110. }
  111. - (UIColor *)mapView:(MGLMapView *)mapView strokeColorForShapeAnnotation:(MGLShape *)annotation {
  112. ///MGLPolyline 和 MGLPolygon 都执行这个方法
  113. if ([@"MGLPolyline" isEqualToString:NSStringFromClass([annotation class])]) {
  114. if (annotation.isDash) {
  115. MGLShapeSource *shapeSource = [self addSourceWithShape:annotation];
  116. [self.mapView.style addSource:shapeSource];
  117. MGLStyleLayer *styleLayer = [self dashedLineWithStyle:shapeSource shape:annotation lineDashPattern:@[@2.f, @1.f] lineCap:MGLLineCapButt lineColor:[UIColor blackColor] lineWidth:@2];
  118. [self.mapView.style addLayer:styleLayer];
  119. return [UIColor clearColor];
  120. } else {
  121. return annotation.strokeColor;
  122. }
  123. } else if ([@"MGLPolygon" isEqualToString:NSStringFromClass([annotation class])]) {
  124. return annotation.strokeColor;
  125. }
  126. return annotation.strokeColor;
  127. }
  128. - (UIColor *)mapView:(MGLMapView *)mapView fillColorForPolygonAnnotation:(MGLPolygon *)annotation {
  129. /// MGLPolygon 执行这个方法, MGLPolyline 不执行这个方法
  130. return annotation.fillColor;
  131. }
  132. - (CGFloat)mapView:(MGLMapView *)mapView lineWidthForPolylineAnnotation:(MGLPolyline *)annotation {
  133. ///MGLPolyline 执行这个方法, MGLPolygon 不执行
  134. return annotation.strokeWeight;
  135. }
  136. #pragma mark 画虚线
  137. - (MGLShapeSource *)addSourceWithShape:(MGLShape *)shape {
  138. return [[MGLShapeSource alloc] initWithIdentifier:@"DashLines" shape:shape options:nil];
  139. }
  140. - (MGLStyleLayer *)dashedLineWithStyle:(MGLShapeSource *)shapeSource shape:(MGLShape *)shape lineDashPattern:(NSArray<NSNumber *> *)lineDashPattern lineCap:(MGLLineCap)cap lineColor:(UIColor *)lineColor lineWidth:(NSNumber *)lineWidth {
  141. MGLLineStyleLayer *lineStyleLayer = [[MGLLineStyleLayer alloc] initWithIdentifier:@"DashLines" source:shapeSource];
  142. //线段模型
  143. lineStyleLayer.lineDashPattern = [MGLStyleValue valueWithRawValue:lineDashPattern];
  144. //线段头部
  145. lineStyleLayer.lineCap = [MGLStyleValue valueWithRawValue:[NSNumber numberWithInteger:cap]];
  146. //线段颜色
  147. lineStyleLayer.lineColor = [MGLStyleValue valueWithRawValue:lineColor];
  148. //线段宽度
  149. lineStyleLayer.lineWidth = [MGLStyleValue valueWithRawValue:lineWidth];
  150. return lineStyleLayer;
  151. }
  152. @end

整个代码的是用步骤是这样的:

  • 实现 MGLShape (PolygonParamer) 扩展类 MGLShape+PolygonParamer ;
  • 把 MGLShape+PolygonParamer.h 引入到  LinePolygonMapboxViewController.h 这个 view controller 中;
  • 运行看效果;
Mapbox使用详解

三、后续更新:

现在文章到这里只是讲述了 Mapbox 的常规使用,后续我会更新关于 多点聚合、位置方向等的使用。。。

四、和其他地图的对比:

Mapbox使用详解

五、项目代码地址:

项目示例代码在GitHub上的地址:https://github.com/wangzhengang/MapboxExample/  
如果您觉得对您有用,请在GitHub上给个星星。