Offline | Maps SDK | Android | Mapbox
文章推薦指數: 80 %
If your user base spends most of their time off the grid, use the Mapbox Maps SDK's offline features to download and store pre-selected regions for use when ... Youareusinganoutdatedbrowserandwillencountersomeproblemswithourwebsite.Pleaseconsiderupgrading.UpgradeNowMapsSDKforAndroidSearchGuidesExamplesAPIReferenceTutorialsTroubleshootingAlldocsMapsSDKforAndroidGuidesOfflineOfflineOnthispageLimitsSpecifyingthestyleandareasthatwillbeusedofflineDefineastylepackDefineatilesetdescriptorandtileregionMetadataWorkingwithdownloadsDownloadastylepackDownloadatileregionManageofflinedataListofflinestylepacksandregionsUpdateastylepackUpdatearegionDeletestylepacksandregionsUnderstandingandconfiguringofflinebehaviorTilestorediskquotaTilecountgranularitySupportedtiledsourcesShareyourfeedbackIfyouruserbasespendsmostoftheirtimeoffthegrid,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-connectionoverheadmoreefficienttotransferoverthenetworkandstoreonthefilesystemthanindividualtiles.Tilepacksonlystoretiles.TheOfflineManagerAPIhandlesmetadataanddescriptorsrelatedtotilesets.TileStore:Thetilestoremanagesretrievingandorganizingtilepacks.Bydefault,theMapsSDKonlyusesthetilestorefortileregions.Thetilestoredoesnotsharetileswiththediskcache(seenoteondiskcachebelow).AlthoughtheOfflineManagerhandlescreatingtilesetdescriptors,itisthejobofthetilestoretomanagetileregions.YoushouldretaintheTileStoreinstancebykeepingareferencetoitwhileusingtheSDKtoavoidunnecessaryre-initializationandpossiblelossofoptionsyouprovidedearlier.Whenausercreatesatilestoreinstance,theuserisresponsibleforinitializingtheTileStorewithproperoptions(usingTileStore#setOption()API),includinganaccesstoken.Stylepack:Astylepackcontainsamapstyleandthenon-tileresourcesitdependsupon,includingloadedsources,fonts,andsprites.Collectively,theseresourcesareusedtotransformmapdatastoredintilesintoarenderedmapwithaparticularlookandfeel.StylepacksareidentifiedbytheirstyleURL.Stylepacksarestoredinthediskcachethatisemployedduringnormalonlinemapuse,buttheirresourcesarenotsubjecttotheprocessesthattypicallyremoveobjectsfromthecachetocontrolitssize.DiskcacheWhenauserloadsandinteractswithamapontheirdevice,anyvisibletilesandstyleresources(styleJSON,fonts,sprites,etc.)areplacedinthedevice'sdiskcache,whichislocatedinthemapsdatadirectorydefinedintheResourceOptions#dataPath.Thediskcacheobserveswhentheseresourcesareusedandmakesintelligentguessesaboutwhichresourcesmaybeneededagain.Whenauserrevisitsaplaceonthemap,itwillloadmorequicklyiftheassociatedresourcesarestillpresentinthediskcache,becausethedevicewillnothavetorequestthoseresourcesfromtheservertorenderthemap.Resourcesthatdonotbelongtoastylepackarenotpermanentlystoredinthediskcache.Therearenoguaranteesonhowlongtheseresourceswillbecached,buttheleast-recentlyusedresourcesarenormallyremovedtomakeroomfornewerresources.LimitsThecumulativeamountofuniquemapstilepacksusedintheofflineregionscannotbegreaterthan750.TheSDKwillnotperformtileregionloadingifitwouldleadtoexceedingthetilepacklimit.OurtermsofservicedonotallowdevelopersorenduserstoredistributeofflinemapsdownloadedfromMapboxservers.UsersoftheSDKmustretrieveMapboxdataintendedforofflineusefromMapboxservers--thedatamaynotbepreloaded,bundledorotherwiseredistributed.SpecifyingthestyleandareasthatwillbeusedofflineTorenderacompletemapinanofflineenvironment,thedeviceneedstofetchtwomaincomponents:astyleandtherequiredmaptiles,eachofwhichneedstobeconfiguredaheadoftime.DefineastylepackTorenderamapoffline,theSDKmustbeabletofetchthenon-tileresourcesthatthemaprequires.Thisincludesloadedsources,fonts,stylesandsprites.TheSDKcalculateswhichresourcesitneedsbasedontheStylePackLoadOptionsyouspecifyandpasstotheOfflineManagerAPI.valstylePackLoadOptions=StylePackLoadOptions.Builder() .glyphsRasterizationMode(GlyphsRasterizationMode.IDEOGRAPHS_RASTERIZED_LOCALLY) .metadata(Value(STYLE_PACK_METADATA)) .build() DefineatilesetdescriptorandtileregionThetilesetdescriptorassociatestiledata(storedinatilepack)toagivenstyle(storedinastylepack).Usethetilesetdescriptortodefineatileset'szoomrangesandpixelratio.Thetileregionisageographicregionanditsmetadata.Itisusedtocalculatewhichtilepackswillbenecessarytoprovideofflinefunctionalityinthatregion.valofflineManager:OfflineManager=OfflineManager(MapInitOptions.getDefaultResourceOptions(this)) valtilesetDescriptor=offlineManager.createTilesetDescriptor( TilesetDescriptorOptions.Builder() .styleURI(Style.OUTDOORS) .minZoom(0) .maxZoom(16) .build() ) valtileRegionLoadOptions=TileRegionLoadOptions.Builder() .geometry(TOKYO) .descriptors(listOf(tilesetDescriptor)) .metadata(Value(TILE_REGION_METADATA)) .acceptExpired(true) .networkRestriction(NetworkRestriction.NONE) .build() MetadataYoumayprovidearbitrarymetadataforbothstylepacksandtileregions.Youmaywanttoprovidemetadatatodistinguishthevariousregionsyourusersdownloadfromoneanotherorforotherrecord-keepingrequirementswithinyourapp.Thisdatawillbeassociatedwiththestylepacksandregionsthatthesystemfetchesandstoreslocally.Whileoptional,providingametadataobjectwithatleastaregionnameisencouraged.Inadditiontoaregionname,youcanstoreanyarbitraryserialisableinformationyou'dlikeaslongasitcanbewrappedintoaValueclass.Forexample,youmightwishtostoretherecordIDofatravelitinerarythatauserhascreatedinanotherpartofyourapp,andforwhichtheofflineregionisbeingretrieved,tolinkthetwotogether.Thecontentsofthemetadatayouspecifywillonlybeavailableinsideyourappandwillnotaffectyourtileregiondownload.AddmetadatatothestylepackwithStylePackLoadOptions.valstylePackLoadOptions=StylePackLoadOptions.Builder() ... .metadata(Value(STYLE_PACK_METADATA)) .build() AddmetadatatothetileregionwithTileRegionLoadOptions.valtileRegionLoadOptions=TileRegionLoadOptions.Builder() ... .metadata(Value(TILE_REGION_METADATA)) .build() WorkingwithdownloadsOncetheabovestepsarecomplete,thesystemhastheinformationnecessarytoknowwhattoresourcesmustbedownloaded.Thenextstepistostartdownloadsforeachofyourstylepacksandtilepacks.DownloadastylepackNowthattheStylePackLoadOptionshasbeencreated,youcanusetheOfflineManagertocreateastylepackasynchronouslybycallingloadStylePack.loadStylePackreturnsaCancelableobject,allowingyoutoabortthedownloadbycallingcancel().Toinitializethedownload,passintheStylePackLoadOptionsyoucreatedinboththeDefineastylepackandMetadatasections.Thiswillprovideyouwithtwocallbacks:StylePackLoadProgressCallbacktrackstheprogressofthedownload.StylePackCallbacktracksthecompletionofthedownloadoranyerrorsthatoccur.ItreturnsaStylePackobjectwhenthedownloadcompletessuccessfully,whichyoucanusetocheckthedownloadedstylepackage,includingitsexpirationdate.valstylePackCancelable=offlineManager.loadStylePack( Style.OUTDOORS, //BuildStylepackloadoptions stylePackLoadOptions, {progress-> //Handlethedownloadprogress }, {expected-> if(expected.isValue){ expected.value?.let{stylePack-> //Stylepackdownloadfinishedsuccessfully } } expected.error?.let{ //Handleerrorsthatoccurredduringthestylepackdownload. } } ) //Cancelthedownloadifneeded stylePackCancelable.cancel() DownloadatileregionInthepreviousstep,youusedtheOfflineManagerAPItodownloadastylepack.Youwillusethetilestoreinasimilarwaytodownloadanytilepacksrequiredtorenderyourmapoffline.Tocreateanasynchronoustileregiondownload,callthetilestore'sloadTileRegionmethodandpassintheTileRegionLoadOptionsyoucreatedintheDefineatilesetdescriptorandtileregionandMetadatasections.loadTileRegionwillreturnaCancelableobject,whichmaybeusedtoabortthedownload.loadTileRegionwillprovideyouwithtwocallbacks:TileRegionLoadProgressCallbacktracksthedownloadprogress.TileRegionCallbacktracksthecompletionofthedownloadoranyerrorsthatoccur.ItprovidesaTileRegionobjectwhenthedownloadcompletessuccessfully,whichyoucanusetocheckthedownloadedtileregion,includingitsexpirationdate.//YouneedtokeepareferenceofthecreatedtileStoreandkeepitduringthedownloadprocess. //YouarealsoresponsibleforinitializingtheTileStoreproperly,includingsettingtheproperaccesstoken. valtileStore=TileStore.create().also{ //Setdefaultaccesstokenforthecreatedtilestoreinstance it.setOption( TileStoreOptions.MAPBOX_ACCESS_TOKEN, TileDataDomain.MAPS, Value(getString(R.string.mapbox_access_token)) ) } valtileRegionCancelable=tileStore.loadTileRegion( TILE_REGION_ID, TileRegionLoadOptions.Builder() .geometry(TOKYO) .descriptors(listOf(tilesetDescriptor)) .metadata(Value(TILE_REGION_METADATA)) .acceptExpired(true) .networkRestriction(NetworkRestriction.NONE) .build(), {progress-> //Handlethedownloadprogress } ){expected-> if(expected.isValue){ //Tileregiondownloadfinishessuccessfully } } expected.error?.let{ //Handleerrorsthatoccurredduringthetileregiondownload. } } //Cancelthedownloadifneeded tileRegionCancelable.cancel() ManageofflinedataOnceadownloadhascompleted,youmaywanttogiveyouruserstheoptiontoviewandmanagetheirdownloadsinoneplace.TheOfflineManagerAPIandtilestoreeachprovidemethodsforlistingandmanagingofflinedata.ListofflinestylepacksandregionsCallOfflineManager#getAllStylePackstogetalistofavailablestylepacks.Thiswillreturnanobject(Expected)thatincludesalistofavailablestylepacksoranerror.//Getalistofstylepacksthatarecurrentlyavailable. offlineManager.getAllStylePacks{expected-> if(expected.isValue){ expected.value?.let{stylePackList-> Log.d("Existingstylepacks:$stylePackList") } } expected.error?.let{stylePackError-> Log.e("StylePackError:$stylePackError") } } Similarly,useTileStore#getAllTileRegionstogetalistofavailabletileregions.Thiswillreturnanobject(Expected)thatincludesalistofavailabletileregionsoranerror.//Getalistoftileregionsthatarecurrentlyavailable. tileStore.getAllTileRegions{expected-> if(expected.isValue){ expected.value?.let{tileRegionList-> Log.d("Existingtileregions:$tileRegionList") } } expected.error?.let{tileRegionError-> Log.e("TileRegionError:$tileRegionError") } } UpdateastylepackTomaintaintheintegrityofastylepackage,themapstylethatbelongstoanofflinepackwillnotbeautomaticallyupdatedifauserreturnstoanareawithnetworkservicesandviewsthemapwhileconnected.Thisincludesloadedstylesandsprites.YoucanmanuallyrefreshstylepacksusingOfflineManager#loadStylePack,passingitthesameStyleUriandanemptyStylePackLoadOptions(notethatiftheacceptExpiredflagissettheexistingoutdatedresourceswillnotberefreshed).Duringtherefresh,anymissingresourceswillbeloadedandexpiredresourceswillbeupdated.UpdatearegionDownloadedtileregionscanberefreshedusingthesameTileStore#loadTileRegioncallyoumadewhenyouinitializedyourdownload.ProvidethesametileregionID(TILE_REGION_IDinthedownloadinitializationexampleabove)andanemptyTileRegionLoadOptions(notethatiftheacceptExpiredflagissettheexistingoutdatedresourceswillnotberefreshed).Duringtherefresh,anymissingresourceswillbeloadedandanyexpiredresourceswillbeupdated.Normally,themapdoesnotloadnewtilepacksfromthenetwork,unlessResourceOptions::TileStoreUsageModeissettoREAD_AND_UPDATE.IfResourceOptions::TileStoreUsageModeissettoREAD_AND_UPDATE,themapwillreplacetheoutdatedvisibletilepackswithfreshonesforallthetileregionsthatrefertothesetilepacks.DeletestylepacksandregionsToremoveofflinedatafromthedatabase,youmustfirstreceivethelistoftileregionsasexplainedintheListofflinestylespacksandregionssection.Oncethislisthasbeenretrieveditmaybeusedtoselectthestylepackand/ortileregionstobedeleted.DeleteastylepackusingtheOfflineManager#removeStylePackAPIandthestyle'sURI.offlineManager.removeStylePack(StyleUri) Notethismaynotimmediatelydeletethedownloadedstylepack.Instead,itwillmarktheresourcesasnotbeingapartofanofflinestylepackandtheywillberemovedfromthediskcacheduringitsnormalcleanupprocess.YoucandeleteatileregionwithTileStore#removeTileRegion.tileStore.removeTileRegion(TILE_REGION_ID) Notethatthismaynotimmediatelydeletethedownloadedtilepacks.Instead,itwillmarkthetilesetasnotbeingapartofanofflinetileregionandtheywillberemovedfromthediskcacheduringitsnormalcleanupprocess.Youcanfullyremovetilesthathavebeendownloadedbysettingthediskquotatozero.Thiswillmakesuretileregionsarefullyremoved.//Thisremovesthetilesthatdonotbelongtoanytileregions. tileStore.setOption(TileStoreOptions.DISK_QUOTA,Value(0)) UnderstandingandconfiguringofflinebehaviorUnderstandingthedefaultbehaviorandoptionsoftheMapsSDK'sofflinefunctionalitycanallowyoutooptimizeyourapp'sofflinefunctionalityandmanageitmoreflexibly.EachMapinstancestoresfilesforboththediskcacheandtilestoreinadefaultlocation(normally,insidetheapplicationcachefolder).Tooverridethedefault,youcanprovideacustomdatapathforthediskcacheandatilestoreinstance.Thereisonlyeveronetilestoreforeachuniquefilepath.TheOfflineManagercanbeconfiguredusingResourceOptions.YoucancompletelydisablethetilestorebysettingResourceOptions.TileStoreUsageModetoDISABLED.Inthiscase,atilestorewillnotbecreatedandtileregionfunctionalitywillnotbeavailable.Bydefault,atilestoreisread-onlyandtheMapsSDKonlyinteractswithittocheckfortilesitneeds.Ifthenecessarytileisnotinthetilestore,theSDKwillrequesttheindividualtileandstoreitinthediskcacheinsteadofthetilestore.Bydefault,theSDKwillnotfetchtilepacksinscenarioslikethis,whereatileisnotavailablelocallyandmustberetrieved.YoucanenableimplicittilepackloadingbysettingtheResourceOptions.TileStoreUsageModeresourceoptiontoREAD_AND_UPDATE.WhensettoREAD_AND_UPDATE,themapenginewillusethetilestoreforloadingtilepacksratherthenloadtilesindividually.Onlytilepackswillbeused.Thisoptioncanbeusefulifthemaptrajectoryispredefinedandtheusercannotpanfreely(e.g.navigationusecases).Inthesecircumstances,itismoreefficienttousetilepacksforallmapdataloadinginsteadofallowingthemaptorequestarbitrarytiles.TilestorediskquotaThemaximumsizeofatilestoremaybeconfigured.Whenthisquotaisreached,theleast-recentlyusedtilepacksthataren'tsharedbyanothertileregionwillberemovedtomakeroomfornewertilepacks.Ifthetilestoreisonlyusedfortileregionsandthereisnoneedtokeeptilepacksboundtothoseregions,youcansetthetilestorediskquotatozero,forcingdiskcleanupafteratileregionisdeleted.TilecountgranularityThetilestoreloadsandstorestilesintilepacks.Eachtilepackhasapre-definedzoomrangeandcontainsallchildtileswithinthatrange.Thecurrentlyusedtilepackzoomrangesare:Globalcoverage:0-5Regionalinformation:6-10Localinformation:11-14Streetsdetail:15-16WhenspecifyingminimumandmaximumzoomlevelsaspartoftheTilesetDescriptorOptions,theactualzoomlevelsoftheretrieveddatawillbedeterminedbytheseranges.Forexample,ifyousetminZoomto8andmaxZoomto15,thedownloadedtileswillincludezoomlevelsrangingfrom6to16.SupportedtiledsourcesTileregionssupportonlythetiledsourceswhosetileendpointURLscorrespondtotheMapboxVector/Rastertilev4URLschema.Yourtiledsourceprobablyusesthev4URLschemaunlessitismorethanafewyearsold.Shareyourfeedback
延伸文章資訊
- 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...
- 2Offline manager | Maps SDK v9 | Android | Mapbox
This page uses v9.7.1 of the Mapbox Maps SDK. A newer version of the SDK is available. Learn abou...
- 3Offline | Maps SDK | iOS | Mapbox
With offline maps for the Mapbox Maps SDK for iOS, you can take your maps with you, even when the...
- 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...