上一節(jié)描述了基本的mapkit加載,其眾多委托方法與功能后面介紹,本節(jié)介紹離線谷歌衛(wèi)星瓦片的加載與保存。
本篇內(nèi)容:瓦片地圖加載 瓦片下載與保存
先看實(shí)際效果:

局部離線瓦片

全局在線瓦片
方法如下:
一、全局瓦片的加載
1、獲取全局瓦片
MKTileOverlay * tile = [[MKTileOverlay alloc] initWithURLTemplate:@"http://mt1.google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}"];
tile.minimumZ = 3;
tile.maximumZ = 30;
tile.canReplaceMapContent = YES;
//tile.boundingMapRect = MAMapRectWorld;
2、全局瓦片加載與更替
if (_mapView.mapType == MKMapTypeStandard) {
//change to google setilite
MKTileOverlay *tile = [self mapTileOverlay];
[_mapView insertOverlay:tile atIndex:0 level:MKOverlayLevelAboveRoads];
NSLog(@"google setellite");
[_mapView setMapType:MKMapTypeSatellite];
}else{
//把google瓦片刪除
NSArray* annos = [NSArray arrayWithArray:_mapView.overlays];
for (int i = 0; i < annos.count; i++) {
id<MKOverlay> ann = [annos objectAtIndex:i];
if ([ann isKindOfClass:[MKTileOverlay class]]) {
[_mapView removeOverlay:ann];
}
}
[_mapView setMapType:MKMapTypeStandard];
NSLog(@"mapkit standard");
二、離線瓦片的加載與保存
1、 瓦片的行列號(hào)計(jì)算
//get x from lon 根據(jù)縮放級(jí)別zoom和經(jīng)度獲取對(duì)應(yīng)瓦片的x(行號(hào))
- (int) getOSMTileXFromLongitude:(double) lon zoom:(int) zoom {
return (int) (floor((lon + 180) / 360 * pow(2, zoom)));
}
//get y from lat 根據(jù)縮放級(jí)別zoom和緯度獲取對(duì)應(yīng)瓦片的y(列號(hào))
- (int) getOSMTileYFromLatitude:(double) lat zoom:(int) zoom
{
return (int) (floor((1 - log(tan(lat * M_PI / 180) + 1 / cos(lat * M_PI / 180)) /M_PI) / 2 * pow(2, zoom)));
}
關(guān)于瓦片的工作原理參考:瓦片原理。
2、生成瓦片下載URL
NSString * urlstr = [NSString stringWithFormat:@"http://mt0.google.cn/maps/vt?lyrs=s@773&gl=cn&x=%d&y=%d&z=%d",x,y,zoomLevel];
3、根據(jù)瓦片urls下載瓦片到本地
/******************************
AFN Download methods
******************************/
- (void) AFNdownloadWapian:(NSMutableArray * ) urls localUrls:(NSMutableArray *)localUrls map:(LocalMap *) map{
/* 創(chuàng)建網(wǎng)絡(luò)下載對(duì)象 */
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
if (urls.count == 0) {
//所有瓦片都下載完成了
map.statuscode = 1;
map.url = [self array2str:localUrls];
//[self updateLocalMap:map];
[self updateLocalMap:map];
return;
}
//每次取urls數(shù)組的第一個(gè) 下完就刪掉
NSString * urlStr = [urls objectAtIndex:0];
//把下載的瓦片的x y z 信息保存到本地 后面離線加載尋址
NSArray * arry = [urlStr componentsSeparatedByString:@"x"];
NSString * urlStrHeli = [arry objectAtIndex:1];
urlStrHeli = [NSString stringWithFormat:@"x%@",urlStrHeli];
/* 下載地址 */
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
/* 保存路徑 */
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/"];
NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",urlStrHeli]];
////把下載的瓦片的x y z 信息保存到本地 后面離線加載尋址
NSString * zzcPath = [NSString stringWithFormat:@"%@.png",urlStrHeli];
NSLog(@"zzcPath:%@",zzcPath);
[localUrls addObject:zzcPath];
/* 開(kāi)始請(qǐng)求下載 */
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"下載進(jìn)度:%.0f%", downloadProgress.fractionCompleted * 100);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
dispatch_async(dispatch_get_main_queue(), ^{
//如果需要進(jìn)行UI操作,需要獲取主線程進(jìn)行操作
});
/* 設(shè)定下載到的位置 */
return [NSURL fileURLWithPath:filePath];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
[urls removeObjectAtIndex:0];
NSLog(@"下載完成,剩余:%lu",(unsigned long)urls.count);
NSLog(@"ZZCfilePath:%@",filePath);
[self AFNdownloadWapian:urls localUrls:localUrls map:map];
}];
[downloadTask resume];
}
4、自定義瓦片類用于加載本地瓦片
原理:規(guī)定URLForTilePath的指定檢索 本地有對(duì)應(yīng)瓦片的xyz的路徑就加載否則不管
//
// ZKTileOverlay.h
// RTectGo
//
// Created by Apple on 2019/2/21.
// Copyright ? 2019年 zzcBjergsen. All rights reserved.
//
#import <MapKit/MapKit.h>
@interface ZKTileOverlay : MKTileOverlay
@property (nonatomic, strong) NSMutableArray * urls;
-(id) initWithArray:(NSMutableArray *)urls;
- (NSURL *)URLForTilePath:(MKTileOverlayPath)path; // default implementation fills out the URLTemplate
@end
//
// ZKTileOverlay.m
// RTectGo
//
// Created by Apple on 2019/2/21.
// Copyright ? 2019年 zzcBjergsen. All rights reserved.
//
#import "ZKTileOverlay.h"
@implementation ZKTileOverlay
-(id) initWithArray:(NSMutableArray *)urls
{
self = [super init];
if (self) {
_urls = urls;
}
return self;
}
- (NSURL *)URLForTilePath:(MKTileOverlayPath)path{
NSString * str = [NSString stringWithFormat:@"x=%ld&y=%ld&z=%ld.png",(long)path.x,(long)path.y,(long)path.z];
NSString *Hpath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/"];
NSString *filePath = [Hpath stringByAppendingPathComponent:str];
NSURL * url;
if ([self contains:_urls str:str]) {
url = [NSURL fileURLWithPath:filePath];
}else{
}
return url;
}
- (BOOL) contains:(NSMutableArray *)urls str:(NSString *)str{
for (int i = 0; i < urls.count; i++) {
NSString * temp = [urls objectAtIndex:i];
if ([str isEqualToString:temp]) {
return YES;
}
}
return NO;
}
@end
5、自定義瓦片的加載
//已下載 進(jìn)行地圖顯示
ZKTileOverlay * tile = [[ZKTileOverlay alloc] initWithArray:[self str2array:map.url]];
[_mapView addOverlay:tile];
//設(shè)置顯示的縮放級(jí)別
MKCoordinateRegion region = {0};
if (CLLocationCoordinate2DIsValid(map.coor)) {
region.center = map.coor;
region.span.latitudeDelta = 0.001;
region.span.longitudeDelta = 0.001;
[_mapView setRegion:region animated:YES];