[ iOS ] 使用 google Map 產生縮圖 ? 再用Apple Map導航

在LBS Application 發達的時代常常會發現app 不可或缺的就是小小的地圖加上兩點做Tag 那怎麼樣能輕鬆的產生map縮圖?在開啟Apple Map 導航呢?只要簡單幾個步驟就可以完成!!讓我們慢慢看下去

第一步 取得座標

要先讓我們的App有取得使用者座標的功能,所以我們要先在專案 > Target > Info 加上 下面3個Key

  • NSLocationWhenInUseUsageDescription
  • NSLocationAlwaysUsageDescription
  • Privacy - Location Usage Description

並在 AppDelegate.h import CoreLocation 並加上 CLLocationManagerDelegate

#import <CoreLocation/CoreLocation.h>
.
.
.
@interface AppDelegate : UIResponder <UIApplicationDelegate,CLLocationManagerDelegate>

之後在 AppDelegate.m didFinishLaunchingWithOptions 初始化locationManager以及加上Delegate

if ([CLLocationManager locationServicesEnabled]) {

        NSLog(@"有開啟GPS");
        locationManager = [[CLLocationManager alloc] init];
        [locationManager setDelegate:(id)self];
        [locationManager requestWhenInUseAuthorization];
        [locationManager startMonitoringSignificantLocationChanges];
        [locationManager startUpdatingLocation];

    } else  {
        NSLog(@"請開啟GPS");
    }

第二步 設定Storyboard

這個範例內我們需要一個UIImageView以及一個UIButton,並設定Property和IBAction

第三步 編寫程式碼

  • 產生小Map的方法
-(void)setMapImage{
     NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];

    NSLog(@"latitude %f",[[defaults stringForKey:@"latitude"] floatValue]);
    NSLog(@"latitude %f",[[defaults stringForKey:@"latitude"] floatValue]);

    NSString *url=[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/staticmap?zoom=15&size=640x400&maptype=roadmap&markers=color:blue|label:U|%f,%f&markers=color:red|label:D|%f,%f",[[defaults stringForKey:@"latitude"] floatValue],[[defaults stringForKey:@"longitude"] floatValue],25.033190,121.564842];

    NSString* webStringURL = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    _image_Map.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:webStringURL]]];
}
  • 開啟Apple Map 導航的方法
- (IBAction)openAppleMap:(id)sender {
    //帶上目的地的座標
    NSString *stringURL = [NSString stringWithFormat:@"http://maps.apple.com/?z=1&q=%f,%f",25.033190,121.564842];
    NSURL *url = [NSURL URLWithString:stringURL];
    [[UIApplication sharedApplication] openURL:url];
}
  • 最後記得在viewDidLoad 加上我們剛剛寫的方法
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setMapImage];
}

GitHub clone URL:https://github.com/SuperPolowu/GoGoMap.git

Polo

Having being a full stack engineer. His interests in Node.js, ARM mbed, IoT solutions, iOS Contact us : [email protected]

ALL RIGHTS RESERVED. COPYRIGHT © 2016. Designed and Coded by Makee.io