上一节描述了基本的mapkit加载,其众多委托方法与功能后面介绍,本节介绍离线谷歌卫星瓦片的加载与保存。
本篇内容:瓦片地图加载 瓦片下载与保存
先看实际效果:
方法如下:
一、全局瓦片的加载
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、 瓦片的行列号计算
//get x from lon 根据缩放级别zoom和经度获取对应瓦片的x(行号)
- (int) getOSMTileXFromLongitude:(double) lon zoom:(int) zoom {
return (int) (floor((lon + 180) / 360 * pow(2, zoom)));
}
//get y from lat 根据缩放级别zoom和纬度获取对应瓦片的y(列号)
- (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)));
}
关于瓦片的工作原理参考:瓦片原理。
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、根据瓦片urls下载瓦片到本地
/******************************
AFN Download methods
******************************/
- (void) AFNdownloadWapian:(NSMutableArray * ) urls localUrls:(NSMutableArray *)localUrls map:(LocalMap *) map{
/* 创建网络下载对象 */
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数组的第一个 下完就删掉
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];
/* 开始请求下载 */
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"下载进度:%.0f%", downloadProgress.fractionCompleted * 100);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
dispatch_async(dispatch_get_main_queue(), ^{
//如果需要进行UI操作,需要获取主线程进行操作
});
/* 设定下载到的位置 */
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、自定义瓦片类用于加载本地瓦片
原理:规定URLForTilePath的指定检索 本地有对应瓦片的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、自定义瓦片的加载
//已下载 进行地图显示
ZKTileOverlay * tile = [[ZKTileOverlay alloc] initWithArray:[self str2array:map.url]];
[_mapView addOverlay:tile];
//设置显示的缩放级别
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];