Download an offline map | Maps SDK v6 | iOS | Mapbox
文章推薦指數: 80 %
This page uses v6.4.1 of the Mapbox Maps SDK. A newer version of the SDK is available. Learn about the latest version, v10.4.3, in the Maps SDK ... Youareusinganoutdatedbrowserandwillencountersomeproblemswithourwebsite.Pleaseconsiderupgrading.UpgradeNowMapsSDKforiOSv6SearchGuidesExamplesAPIReferenceAlldocsMapsSDKforiOSv6ExamplesDownloadanofflinemapDownloadanofflinemapAnewerversionoftheMapsSDKisavailableThispageusesv6.4.1oftheMapboxMapsSDK.AnewerversionoftheSDKisavailable.Learnaboutthelatestversion,v10.5.0,intheMapsSDKdocumentation.Yourbrowserdoesn'tsupportHTML5video.Openlinktothevideo.Seeourmobileofflinehelppageformoreinformationaboutusesandlimitations.Foramorecomprehensiveexamplethatmanagesofflinepacks,seeMBXOfflinePacksTableViewController.ViewControllerViewonGitHubSwiftObjective-CimportMapboxclassViewController:UIViewController,MGLMapViewDelegate{varmapView:MGLMapView!varprogressView:UIProgressView!overridefuncviewDidLoad(){super.viewDidLoad()mapView=MGLMapView(frame:view.bounds,styleURL:MGLStyle.darkStyleURL)mapView.autoresizingMask=[.flexibleWidth,.flexibleHeight]mapView.tintColor=.graymapView.delegate=selfview.addSubview(mapView)mapView.setCenter(CLLocationCoordinate2D(latitude:22.27933,longitude:114.16281),zoomLevel:13,animated:false)//Setupofflinepacknotificationhandlers.NotificationCenter.default.addObserver(self,selector:#selector(offlinePackProgressDidChange),name:NSNotification.Name.MGLOfflinePackProgressChanged,object:nil)NotificationCenter.default.addObserver(self,selector:#selector(offlinePackDidReceiveError),name:NSNotification.Name.MGLOfflinePackError,object:nil)NotificationCenter.default.addObserver(self,selector:#selector(offlinePackDidReceiveMaximumAllowedMapboxTiles),name:NSNotification.Name.MGLOfflinePackMaximumMapboxTilesReached,object:nil)}funcmapViewDidFinishLoadingMap(_mapView:MGLMapView){//Startdownloadingtilesandresourcesforz13-14.startOfflinePackDownload()}overridefuncviewDidDisappear(_animated:Bool){super.viewDidDisappear(animated)//Whenleavingthisviewcontroller,suspendofflinedownloads.guardletpacks=MGLOfflineStorage.shared.packselse{return}forpackinpacks{ifletuserInfo=NSKeyedUnarchiver.unarchiveObject(with:pack.context)as?[String:String]{print("Suspendingdownloadofofflinepack:“\(userInfo["name"]??"unknown")”")}pack.suspend()}}funcstartOfflinePackDownload(){//Createaregionthatincludesthecurrentviewportandanytilesneededtoviewitwhenzoomedfurtherin.//Becausetilecountgrowsexponentiallywiththemaximumzoomlevel,youshouldbeconservativewithyour`toZoomLevel`setting.letregion=MGLTilePyramidOfflineRegion(styleURL:mapView.styleURL,bounds:mapView.visibleCoordinateBounds,fromZoomLevel:mapView.zoomLevel,toZoomLevel:14)//Storesomedataforidentificationpurposesalongsidethedownloadedresources.letuserInfo=["name":"MyOfflinePack"]letcontext=NSKeyedArchiver.archivedData(withRootObject:userInfo)//Createandregisteranofflinepackwiththesharedofflinestorageobject.MGLOfflineStorage.shared.addPack(for:region,withContext:context){(pack,error)inguarderror==nilelse{//Thepackcouldn’tbecreatedforsomereason.print("Error:\(error?.localizedDescription??"unknownerror")")return}//Startdownloading.pack!.resume()}}//MARK:-MGLOfflinePacknotificationhandlers@objcfuncofflinePackProgressDidChange(notification:NSNotification){//Gettheofflinepackthisnotificationisregarding,//andtheassociateduserinfoforthepack;inthiscase,`name=MyOfflinePack`ifletpack=notification.objectas?MGLOfflinePack,letuserInfo=NSKeyedUnarchiver.unarchiveObject(with:pack.context)as?[String:String]{letprogress=pack.progress//ornotification.userInfo![MGLOfflinePackProgressUserInfoKey]!.MGLOfflinePackProgressValueletcompletedResources=progress.countOfResourcesCompletedletexpectedResources=progress.countOfResourcesExpected//Calculatecurrentprogresspercentage.letprogressPercentage=Float(completedResources)/Float(expectedResources)//Setuptheprogressbar.ifprogressView==nil{progressView=UIProgressView(progressViewStyle:.default)letframe=view.bounds.sizeprogressView.frame=CGRect(x:frame.width/4,y:frame.height*0.75,width:frame.width/2,height:10)view.addSubview(progressView)}progressView.progress=progressPercentage//Ifthispackhasfinished,printitssizeandresourcecount.ifcompletedResources==expectedResources{letbyteCount=ByteCountFormatter.string(fromByteCount:Int64(pack.progress.countOfBytesCompleted),countStyle:ByteCountFormatter.CountStyle.memory)print("Offlinepack“\(userInfo["name"]??"unknown")”completed:\(byteCount),\(completedResources)resources")}else{//Otherwise,printdownload/verificationprogress.print("Offlinepack“\(userInfo["name"]??"unknown")”has\(completedResources)of\(expectedResources)resources—\(String(format:"%.2f",progressPercentage*100))%.")}}}@objcfuncofflinePackDidReceiveError(notification:NSNotification){ifletpack=notification.objectas?MGLOfflinePack,letuserInfo=NSKeyedUnarchiver.unarchiveObject(with:pack.context)as?[String:String],leterror=notification.userInfo?[MGLOfflinePackUserInfoKey.error]as?NSError{print("Offlinepack“\(userInfo["name"]??"unknown")”receivederror:\(error.localizedFailureReason??"unknownerror")")}}@objcfuncofflinePackDidReceiveMaximumAllowedMapboxTiles(notification:NSNotification){ifletpack=notification.objectas?MGLOfflinePack,letuserInfo=NSKeyedUnarchiver.unarchiveObject(with:pack.context)as?[String:String],letmaximumCount=(notification.userInfo?[MGLOfflinePackUserInfoKey.maximumCount]asAnyObject).uint64Value{print("Offlinepack“\(userInfo["name"]??"unknown")”reachedlimitof\(maximumCount)tiles.")}}}Copy
延伸文章資訊
- 1Offline | Maps SDK | Android | Mapbox
If your user base spends most of their time off the grid, use the Mapbox Maps SDK's offline featu...
- 2Migrate to v10 | Maps SDK | Android | Mapbox
Upgrade your application from the Mapbox Maps SDK for Android v9 to v10. ... Read more about Offl...
- 3Download an offline map | Maps SDK v6 | iOS | Mapbox
This page uses v6.4.1 of the Mapbox Maps SDK. A newer version of the SDK is available. Learn abou...
- 4Migrate to v10 | Maps SDK | iOS | Mapbox
Upgrade your application from the Mapbox Maps SDK for iOS v6 to v10. ... The OfflineManager API c...
- 5Offline maps | Help | Mapbox
4.1 of the Mapbox Maps SDK for iOS. A newer version of the SDK is available. Learn about the late...