Offline | Maps SDK | iOS | Mapbox
文章推薦指數: 80 %
With offline maps for the Mapbox Maps SDK for iOS, you can take your maps with you, even when there is no internet connection. Youareusinganoutdatedbrowserandwillencountersomeproblemswithourwebsite.Pleaseconsiderupgrading.UpgradeNowMapsSDKforiOSSearchGuidesExamplesAPIReferenceTutorialsTroubleshootingAlldocsMapsSDKforiOSGuidesOfflineOfflineOnthispageLimitsSpecifyingthestyleandareasthatwillbeusedofflineDefineastylepackDefineatilesetdescriptorandtileregionMetadataWorkingwithdownloadsDownloadastylepackDownloadatileregionManageofflinedataListofflinestylepacksandregionsUpdateastylepackUpdatearegionDeletestylepacksandregionsUnderstandingandconfiguringofflinebehaviorTilestorediskquotaTilecountgranularitySupportedtiledsourcesShareyourfeedbackIfyouruserbasespendsmostoftheirtimeoffthegrid,usetheMapboxMapsSDK'sofflinefeaturestodownloadandstorepre-selectedregionsforusewhenthereisalossofconnectivity.Themapstheydownloadwillbefullyfunctionalandincludethestyles,tiles,andotherresourcesyouspecify.Anofflinemaprequirestwomaincomponents:Styledata,whichisorganizedintostylepacks.UsetheOfflineManagerAPItomanagestylepacks.Mapdata,whichisorganizedintopreassembledtilepacks.Usethetilestoretomanagetilepacks.Theseareafewkeytermsandconceptsyoumayneedtoreferencewhenworkingwithofflinemaps:OfflineManager:TheOfflineManagerAPIprovidesaconfigurationinterfaceandentrypointforofflinemapfunctionality.Itisusedtomanagestylepacksandtoproducetilesetdescriptorsthatcanbeusedwithatilestore.Tilesetdescriptor:Atilesetdescriptorcontainsmetadataaboutthetilesets,zoomranges,andpixelratiothatcachedtilepacksshouldinclude.YoucancreatetilesetdescriptorswiththeOfflineManager.Eachtimeyoucreateatilepack,youwillprovidebothatilesetdescriptorandatileregionbeforetiledatacanbefetchedforofflineuse.Tileregion:Atileregionisageographicareaforwhichofflinedataisneeded.Tileregionsareusedbytilestorestofetchandmanagetilepacksnecessarytoprovideofflinesupportinthatarea.Tocreateatileregion,adevelopermustspecifyageometrydescribingeachregion'sboundaries,sourcetileset(s),andzoomrange(s).Tilepack:Tilepacksarebinaryfilesmadeupofaparenttileanditsdescendanttilescoveringaspecificrangeofzoomlevelsandoverapredefinedgeographicarea.Becausetheyhavelessper-tileandper-connectionoverhead,theyaremoreefficienttotransferoverthenetworkandstoreonthefilesystemthanindividualtiles.Tilepacksonlystoretiles.TheOfflineManagerAPIhandlesmetadataanddescriptorsrelatedtotilesets.TileStore:Thetilestoremanagesretrievingandorganizingtilepacks.Bydefault,theMapsSDKonlyusesthetilestorefortileregions.Thetilestoredoesnotsharetileswiththediskcache(seenoteondiskcachebelow).AlthoughtheOfflineManagerhandlescreatingtilesetdescriptors,itisthejobofthetilestoretomanagetileregions.YoushouldretaintheTileStoreinstancebykeepingareferencetoitwhileusingtheSDK.Thispreventsunnecessaryre-initializationandpossiblelossofoptionsyouprovidedearlier.Theuserisresponsibleforprovidingproperoptions,includinganaccesstoken,whencreatingatilestorewitha`TileStore.setOptionForKey()API.Stylepack:Astylepackcontainsamapstyleandthenon-tileresourcesitdependsupon,includingloadedsources,fonts,andsprites.Collectively,theseresourcesareusedtotransformmapdatastoredintilesintoarenderedmapwithaparticularlookandfeel.StylepacksareidentifiedbytheirstyleURL.Stylepacksarestoredinthediskcachethatisemployedduringnormalonlinemapuse,buttheirresourcesarenotsubjecttotheprocessesthattypicallyremoveobjectsfromthecachetocontrolitssize.DiskcacheWhenauserloadsandinteractswithamapontheirdevice,anyvisibletilesandstyleresources(styleJSON,fonts,sprites,etc.)areplacedinthedevice'sdiskcache,whichislocatedinthemapsdatadirectorydefinedintheResourceOptions.dataPathURL.Thediskcacheobserveswhentheseresourcesareusedandmakesintelligentguessesaboutwhichresourcesmaybeneededagain.Whenauserrevisitsaplaceonthemap,itwillloadmorequicklyiftheassociatedresourcesarestillpresentinthediskcache,becausethedevicewillnothavetorequestthoseresourcesfromtheservertorenderthemap.Resourcesthatdonotbelongtoastylepackarenotpermanentlystoredinthediskcache.Therearenoguaranteesabouthowlongtheseresourceswillbecached,buttheleast-recentlyusedresourcesarenormallyremovedtomakeroomfornewerresources.LimitsThecumulativenumberofuniquemapstilepacksusedintheofflineregionscannotbegreaterthan750.TheSDKwillnotloadtileregionsifitwouldleadtoexceedingthetilepacklimit.OurtermsofservicedonotallowdevelopersorenduserstoredistributeofflinemapsdownloadedfromMapboxservers.UsersoftheSDKmustretrieveMapboxdataintendedforofflineusefromMapboxservers--thedatamaynotbepreloaded,bundledorotherwiseredistributed.SpecifyingthestyleandareasthatwillbeusedofflineTorenderacompletemapinanofflineenvironment,thedeviceneedstofetchtwomaincomponents:astyleandtherequiredmaptiles,eachofwhichneedstobeconfiguredaheadoftime.DefineastylepackTorenderamapoffline,theSDKmustbeabletofetchthenon-tileresourcesthatthemaprequires.Thisincludesloadedsources,fonts,stylesandsprites.TheSDKcalculateswhichresourcesitneedsbasedontheStylePackLoadOptionsyouspecifyandpasstotheOfflineManagerAPI.letoptions=StylePackLoadOptions(glyphsRasterizationMode:.ideographsRasterizedLocally, metadata:["my-key":"my-value"], acceptExpired:false) DefineatilesetdescriptorandtileregionThetilesetdescriptorassociatestiledata(storedinatilepack)withagivenstyle(storedinastylepack).Usethetilesetdescriptortodefineatileset'szoomrangesandpixelratio.Thetileregionisageographicregionanditsmetadata.Itisusedtocalculatewhichtilepackswillbenecessarytoprovideofflinefunctionalityinthatregion.//Whenprovidinga`TileStore`to`ResourceOptions`,youmustensurethat //the`TileStore`iscorrectlyinitializedusing`setOptionForKey(_:value:)`. //Thisincludesprovidinganaccesstoken,ifyouarenotusingadefault //fromtheapplication'sInfo.plist tileStore.setOptionForKey(TileStoreOptions.mapboxAccessToken,value:accessTokenasAny) letofflineManager=OfflineManager(resourceOptions:ResourceOptions(accessToken:accessToken, tileStore:tileStore)) //1.Createthetilesetdescriptor letoptions=TilesetDescriptorOptions(styleURI:.outdoors,zoomRange:0...16) lettilesetDescriptor=offlineManager.createTilesetDescriptor(for:options) //2.CreatetheTileRegionLoadOptions lettileRegionLoadOptions=TileRegionLoadOptions( geometry:Geometry(coordinate:tokyoCoord), descriptors:[tilesetDescriptor], acceptExpired:true) MetadataYoumayprovidearbitrarymetadataforbothstylepacksandtileregions.Youmaywanttoprovidemetadatatodistinguishthevariousregionsyourusersdownloadfromoneanotherorforotherrecord-keepingrequirementswithinyourapp.Thisdatawillbeassociatedwiththestylepacksandregionsthatthesystemfetchesandstoreslocally.Whileoptional,providingametadataobjectwithatleastaregionnameisencouraged.Inadditiontoaregionname,youcanstoreanyarbitraryserialisableinformationyou'dlikeaslongasitcanbewrappedintoaJSONobject.Forexample,youmightwishtostoretherecordIDofatravelitinerarythatauserhascreatedinanotherpartofyourapp,andforwhichtheofflineregionisbeingretrieved,tolinkthetwotogether.Thecontentsofthemetadatayouspecifywillonlybeavailableinsideyourappandwillnotaffectyourtileregiondownload.AddmetadatatothestylepackwithStylePackLoadOptions.letmetadata=["my-key":"my-style-pack-value"] letoptions=StylePackLoadOptions(glyphsRasterizationMode:.ideographsRasterizedLocally, metadata:metadata) AddmetadatatothetileregionwithTileRegionLoadOptions.letmetadata=[ "name":"my-region", "my-other-key":"my-other-tile-region-value"] lettileRegionLoadOptions=TileRegionLoadOptions( geometry:Geometry(coordinate:tokyoCoord), descriptors:[], metadata:metadata, acceptExpired:true) WorkingwithdownloadsOncetheabovestepsarecomplete,thesystemhastheinformationnecessarytoknowwhattoresourcesmustbedownloaded.Thenextstepistostartdownloadsforeachofyourstylepacksandtilepacks.DownloadastylepackNowthattheStylePackLoadOptionshasbeencreated,youcanusetheOfflineManagertodownloadastylepackasynchronouslybycallingloadStylePack.loadStylePackreturnsaCancelableobject,allowingyoutoabortthedownloadbycallingcancel().Toinitializethedownload,passintheStylePackLoadOptionsyoucreated,asshowninboththeDefineastylepackandMetadatasections.Thiswillprovideyouwithtwocallbacks:StylePackLoadProgressCallbacktrackstheprogressofthedownload.StylePackCallbacktracksthecompletionofthedownloadoranyerrorsthatoccur.ItreturnsaStylePackobjectwhenthedownloadcompletessuccessfully,whichyoucanusetocheckthedownloadedstylepackage,includingitsexpirationdate.//Theseclosuresdonotgetcalledfromthemainthread.Dependingon //theusecase,youmayneedtouse`DispatchQueue.main.async`,for //exampletoupdateyourUI. letstylePackCancelable=offlineManager.loadStylePack(for:.outdoors, loadOptions:stylePackLoadOptions){_in // //Handleprogresshere // }completion:{resultin // //HandleStylePackresult // switchresult{ caselet.success(stylePack): //Stylepackdownloadfinishessuccessfully print("Process\(stylePack)") caselet.failure(error): //Handleerroroccurredduringthestylepackdownload ifcaseStylePackError.canceled=error{ handleCancelation() }else{ handleFailure() } } } //Cancelthedownloadifneeded stylePackCancelable.cancel() DownloadatileregionInthepreviousstep,youusedtheOfflineManagerAPItodownloadastylepack.Youwillusethetilestoreinasimilarwaytodownloadanytilepacksrequiredtorenderyourmapoffline.Tocreateanasynchronoustileregiondownload,callthetilestore'sloadTileRegionmethodandpassintheTileRegionLoadOptionsyoucreated,asshownintheDefineatilesetdescriptorandtileregionandMetadatasections.loadTileRegionwillreturnaCancelableobject,whichmaybeusedtoabortthedownload.loadTileRegionwillprovideyouwithtwocallbacks:TileRegionLoadProgressCallbacktracksthedownloadprogress.TileRegionCallbacktracksthecompletionofthedownloadoranyerrorsthatoccur.ItprovidesaTileRegionobjectwhenthedownloadcompletessuccessfully,whichyoucanusetocheckthedownloadedtileregion,includingitsexpirationdate.lettileRegionId="my-tile-region-id" //Loadthetileregion lettileRegionLoadOptions=TileRegionLoadOptions( geometry:Geometry(coordinate:tokyoCoord), descriptors:[tilesetDescriptor], acceptExpired:true)! lettileRegionCancelable=tileStore.loadTileRegion( forId:tileRegionId, loadOptions:tileRegionLoadOptions){_in // //Handleprogresshere // }completion:{resultin // //HandleTileRegionresult // switchresult{ caselet.success(tileRegion): //Tileregiondownloadfinishessuccessfully print("Process\(tileRegion)") caselet.failure(error): //Handleerroroccurredduringthetileregiondownload ifcaseTileRegionError.canceled=error{ handleCancelation() }else{ handleFailure(error) } } } //Cancelthedownloadifneeded tileRegionCancelable.cancel() ManageofflinedataOnceadownloadhascompleted,youmaywanttogiveyouruserstheoptiontoviewandmanagetheirdownloadsinoneplace.TheOfflineManagerAPIandtilestoreeachprovidemethodsforlistingandmanagingofflinedata.ListofflinestylepacksandregionsTheOfflineManageroffersaallStylePacks(completion:)methodwhichreturnsanResulttype,encapsulatingthearrayofstylepacksavailableoranerror.//Getalistofstylepacksthatarecurrentlyavailable. offlineManager.allStylePacks{resultin switchresult{ caselet.success(stylePacks): handleStylePacks(stylePacks) caselet.failure(error)whereerrorisStylePackError: handleStylePackError(error) case.failure(_): handleFailure() } } Similarly,theTileStoreoffersaallTileRegions(completion:)methodwhichreturnsaResulttype,encapsulatingthelistoftileregionsavailableoranerror.//Getalistoftileregionsthatarecurrentlyavailable. tileStore.allTileRegions{resultin switchresult{ caselet.success(tileRegions): handleTileRegions(tileRegions) caselet.failure(error)whereerrorisTileRegionError: handleTileRegionError(error) case.failure(_): handleFailure() } } UpdateastylepackTomaintaintheintegrityofastylepackage,themapstylethatbelongstoanofflinepackwillnotbeautomaticallyupdatedifauserreturnstoanareawithnetworkservicesandviewsthemapwhileconnected.Thisincludesloadedsources,glyphs,andsprites.YoucanmanuallyrefreshstylepacksusingOfflineManager.loadStylePack,passingitthesameStyleURIandanemptyStylePackLoadOptions(notethatiftheacceptExpiredflagissettheexistingoutdatedresourceswillnotberefreshed).Duringtherefresh,anymissingresourceswillbeloadedandexpiredresourceswillbeupdated.UpdatearegionDownloadedtileregionscanberefreshedusingthesameTileStore.loadTileRegioncallyoumadewhenyouinitializedyourdownload.ProvidethesametileregionID(tileRegionIdinthedownloadinitializationexampleabove)andanemptyTileRegionLoadOptions(notethatiftheacceptExpiredflagissettheexistingoutdatedresourceswillnotberefreshed).Duringtherefresh,anymissingresourceswillbeloadedandanyexpiredresourceswillbeupdated.Normally,themapdoesnotloadnewtilepacksfromthenetwork,unlessResourceOptions.tileStoreUsageModeissetto.readAndUpdate.IfResourceOptions.tileStoreUsageModeissetto.readAndUpdate,themapwillreplacetheoutdatedvisibletilepackswithfreshonesforallthetileregionsthatrefertothesetilepacks.DeletestylepacksandregionsToremoveofflinedatafromthedatabase,youmustfirstreceivethelistoftileregionsasexplainedintheListofflinestylespacksandregionssection.Oncethislisthasbeenretrieveditmaybeusedtoselectthestylepackand/ortileregionstobedeleted.DeleteastylepackusingtheOfflineManager.removeStylePackAPIandthestyle'sURI.offlineManager.removeStylePack(for:.outdoors) Notethismaynotimmediatelydeletethedownloadedstylepack.Instead,itwillmarktheresourcesasnotbeingapartofanofflinestylepackandtheywillberemovedfromthediskcacheduringitsnormalcleanupprocess.YoucandeleteatileregionwithTileStore.removeTileRegion.tileStore.removeTileRegion(forId:"my-tile-region-id") Notethatthismaynotimmediatelydeletethedownloadedtilepacks.Instead,itwillmarkthetilesetasnotbeingapartofanofflinetileregionandtheywillberemovedfromthediskcacheduringitsnormalcleanupprocess.Youcanfullyremovetilesthathavebeendownloadedbysettingthediskquotatozero.Thiswillmakesuretileregionsarefullyremoved.tileStore.setOptionForKey(TileStoreOptions.diskQuota,value:0) UnderstandingandconfiguringofflinebehaviorUnderstandingthedefaultbehaviorandcustomizationoptionsoftheMapsSDK'sofflinefunctionalitycanallowyoutooptimizeyourapp'sofflinefunctionalityandmanageitmoreflexibly.EachMapinstancestoresfilesforboththediskcacheandtilestoreinadefaultlocation(normally,insidetheapplicationcachefolder).Tooverridethedefault,youcanprovideacustomdatapathforthediskcacheandatilestoreinstance.Thereisonlyeveronetilestoreforeachuniquefilepath.TheOfflineManagercanbeconfiguredusingResourceOptions.YoucancompletelydisablethetilestorebysettingResourceOptions.tileStoreUsageModeto.disabled.Inthiscase,atilestorewillnotbecreatedandtileregionfunctionalitywillnotbeavailable.Bydefault,atilestoreisread-onlyandtheMapsSDKonlyinteractswithittocheckfortilesitneeds.Ifthenecessarytileisnotinthetilestore,theSDKwillrequesttheindividualtileandstoreitinthediskcacheinsteadofthetilestore.Bydefault,theSDKwillnotfetchtilepacksinscenarioslikethis,whereatileisnotavailablelocallyandmustberetrieved.YoucanenableimplicittilepackloadingbysettingtheResourceOptions.tileStoreUsageModeresourceoption.Whensetto.readAndUpdate,themapenginewillusethetilestoreforloadingtilepacksratherthanloadingtilesindividually.Onlytilepackswillbeused.Thisoptioncanbeusefulifthemaptrajectoryispredefinedandtheusercannotpanfreely(e.g.navigationusecases).Inthesecircumstances,itismoreefficienttousetilepacksforallmapdataloadinginsteadofallowingthemaptorequestarbitrarytiles.TilestorediskquotaLikethediskcache,themaximumsizeofatilestoremaybeconfigured.Whenthisquotaisreached,theleast-recentlyusedtilepacksthataren'tsharedbyanothertileregionwillberemovedtomakeroomfornewertilepacks.Ifthetilestoreisonlyusedfortileregionsandthereisnoneedtokeeptilepacksboundtothoseregions,youcansetthetilestorediskquotatozero,forcingdiskcleanupafteratileregionisdeleted.TilecountgranularityThetilestoreloadsandstorestilesintilepacks.Eachtilepackhasapredefinedzoomrangeandcontainsallchildtileswithinthatrange.Thecurrentlyusedtilepackzoomrangesare:Globalcoverage:0-5Regionalinformation:6-10Localinformation:11-14Streetsdetail:15-16WhenspecifyingminimumandmaximumzoomlevelsaspartoftheTilesetDescriptorOptions,theactualzoomlevelsoftheretrieveddatawillbedeterminedbytheseranges.Forexample,ifyousetminZoomto8andmaxZoomto15,thedownloadedtileswillincludezoomlevelsrangingfrom6to16.SupportedtiledsourcesTileregionssupportonlythetiledsourceswhosetileendpointURLscorrespondtotheMapboxVector/Rastertilev4URLschema.Yourtiledsourceprobablyusesthev4URLschemaunlessitismorethanafewyearsold.Shareyourfeedback
延伸文章資訊
- 1Maps SDK v10 - Mapbox
The Mapbox Mobile Maps SDK v10 is ready for download by all Mapbox users ... a full transition fr...
- 2Migrate to v10 | Maps SDK | iOS | Mapbox
Upgrade your application from the Mapbox Maps SDK for iOS v6 to v10. ... The OfflineManager API c...
- 3Offline | Maps SDK | Android | Mapbox
If your user base spends most of their time off the grid, use the Mapbox Maps SDK's offline featu...
- 4Offline | Android Plugins - Mapbox
The Maps SDK v10 and higher comes with offline functionality built in. See the Offline guide. The...
- 5Migrate to v10 | Maps SDK | Android | Mapbox
Upgrade your application from the Mapbox Maps SDK for Android v9 to v10. ... Read more about Offl...