Mapbox provides the Maps SDK via Maven. To add the Mapbox Maps SDK as a dependency, you will need to configure your build to download the Maps SDK from Mapbox ...
Youareusinganoutdatedbrowserandwillencountersomeproblemswithourwebsite.Pleaseconsiderupgrading.UpgradeNowMapsSDKforAndroidSearchGuidesExamplesAPIReferenceTutorialsTroubleshootingAlldocsMapsSDKforAndroidGuidesInstallationInstallationOnthispageConfigurecredentialsAddthedependencyAddamapShareyourfeedbackBeforestartingtodevelopyourapplicationwiththeMapsSDK,you'llneedtoconfigureyourcredentialsandaddtheSDKasadependency.ThisdocumentdescribesthestepstoinstallthestableversionoftheMapsSDK,butyoucanalsousethenightlybuild(i.e.SNAPSHOT)orthebetaversion,ifoneisavailable.Android's64KmethodcountlimitIfyourapplicationisoverthe64Kmethodlimit,youcanshrink,obfuscate,andoptimizeyourcodewithR8orProGuard.Ifthosestepsdonotloweryourmethodcountbelow64K,youcanalsoenablemultidex.ConfigurecredentialsBeforeinstallingtheSDK,youwillneedtogathertheappropriatecredentials.TheSDKrequirestwopiecesofsensitiveinformationfromyourMapboxaccount.Ifyoudon'thaveaMapboxaccount:signupandnavigatetoyourAccountpage.You'llneed:
Apublicaccesstoken:Fromyouraccount'stokenspage,youcaneithercopyyourdefaultpublictokenorclicktheCreateatokenbuttontocreateanewpublictoken.
AsecretaccesstokenwiththeDownloads:Readscope.
Fromyouraccount'stokenspage,clicktheCreateatokenbutton.
Fromthetokencreationpage,giveyourtokenanameandmakesuretheboxnexttotheDownloads:Readscopeischecked.
ClicktheCreatetokenbuttonatthebottomofthepagetocreateyourtoken.
Thetokenyou'vecreatedisasecrettoken,whichmeansyouwillonlyhaveoneopportunitytocopyitsomewheresecure.
Youshouldnotexposetheseaccesstokensinpublicly-accessiblesourcecodewhereunauthorizedusersmightfindthem.Instead,youshouldstorethemsomewheresafeonyourcomputerandtakeadvantageofGradlepropertiestomakesurethey'reonlyaddedwhenyourappiscompiled.Oncethisconfigurationstephasbeencompleted,youwillbeabletoreferenceyourcredentialsinotherpartsofyourapp.
Configureyoursecrettoken
Toavoidexposingyoursecrettoken,additasanenvironmentvariable:
Findorcreateagradle.propertiesfileinyourGradleuserhomefolder.Thefoldercanbefoundat«USER_HOME»/.gradle.Onceyouhavefoundorcreatedthefile,itspathshouldbe«USER_HOME»/.gradle/gradle.properties.YoucanreadmoreaboutGradlepropertiesintheofficialGradledocumentation.
Addyoursecrettokenyourgradle.propertiesfile:
MAPBOX_DOWNLOADS_TOKEN=YOUR_SECRET_MAPBOX_ACCESS_TOKEN
Configureyourpublictoken
Therearemanywaystoconfigureyourpublicaccesstoken.Manyoftheexamplesandcodesnippetsonthissiteassumeyourtokenisstoredinafileinyourprojectwithotherstringvalues.Ifyouwouldliketomanageyourpublicaccesstokenthisway,openyourproject'sR.strings.xmlfileandaddthefollowingstringresource,replacingYOUR_MAPBOX_ACCESS_TOKENwithyourpublicMapboxAPItoken:
YOUR_MAPBOX_ACCESS_TOKEN
Ifyoueverneedtorotateyouraccesstoken,youwillneedtoupdatethetokenvalueinyourR.strings.xmlfile.
Configurepermissions
YoucanusetheManifestmergefeaturetoreducetheneedtoincludeanySDKrequirementsinyourapplication'smanifestfile.You'llneedtoaddeithertheFineorCoarselocationpermissionifyouplantodisplayauser'slocationonthemaporgettheuser'slocationinformation.TheuserlocationpermissionshouldalsobecheckedduringruntimeusingthePermissionsManager.
guideAccesstokenbestpracticesLearnhowtokeepaccesstokensprivateinmobileapps.AddthedependencyMapboxprovidestheMapsSDKviaMaven.ToaddtheMapboxMapsSDKasadependency,youwillneedtoconfigureyourbuildtodownloadtheMapsSDKfromMapboxdirectly.Thisrequiresavalidusernameandpassword.
OpenyourprojectinAndroidStudio.
DeclaretheMapboxDownloadsAPI'sreleases/mavenendpoint.TodownloadtheMapsSDKdependency,youmustauthenticateyourrequestwithavalidusernameandpassword.Intheprevioussection,youaddedthepasswordtoagradle.propertiesfileinyourGradleuserhomefolder.Theusernamefieldshouldalwaysbe"mapbox".Itshouldnotbeyourpersonalusernameusedtocreatethesecrettoken.WhereyoumakethesedeclarationsdependontheversionsofAndroidStudioandGradleyourprojectisusing:
AndroidStudiolessthanArcticFox(2020.3.1)andGradlelessthanv6.0:Openupyourproject-levelbuild.gradlefile,andaddthecodebelowtodeclaretheendpointintherepositoriesblock:
allprojects{
repositories{
maven{
url'https://api.mapbox.com/downloads/v2/releases/maven'
authentication{
basic(BasicAuthentication)
}
credentials{
//Donotchangetheusernamebelow.
//Thisshouldalwaysbe`mapbox`(notyourusername).
username="mapbox"
//Usethesecrettokenyoustoredingradle.propertiesasthepassword
password=project.properties['MAPBOX_DOWNLOADS_TOKEN']?:""
}
}
}
}
AndroidStudioArcticFox(2020.3.1)orlaterandGradlev6.0orlater:Youmayneedtomakethesedeclarationsinyoursettings.gradlefileinstead.Ifyouseebuilderrorswiththebuild.gradleprocessdescribedabove,theninsteaddeclaretheMapbox'sMavenrepositoryinyoursettings.gradlefilelikebelow:
dependencyResolutionManagement{
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories{
google()
mavenCentral()
maven{
url'https://api.mapbox.com/downloads/v2/releases/maven'
authentication{
basic(BasicAuthentication)
}
credentials{
//Donotchangetheusernamebelow.
//Thisshouldalwaysbe`mapbox`(notyourusername).
username="mapbox"
//Usethesecrettokenyoustoredingradle.propertiesasthepassword
password=MAPBOX_DOWNLOADS_TOKEN
}
}
}
}
Openupyourmodule-levelbuild.gradlefile.
Makesurethatyourproject'sminSdkVersionisatAPI21orhigher.
android{
...
defaultConfig{
minSdkVersion21
}
}
Underdependencies,addanewbuildruleforthelatestMapboxMapsSDKforAndroid.
dependencies{
implementation'com.mapbox.maps:android:10.5.0'
}
Becauseyou'veeditedyourGradlefiles,AndroidStudiowillaskyouwhetheryouwanttosynctheGradlefiles.Youcansyncnow.
Note:YoumighthavemismatchingGradledependenciesonceyouaddtheMapboxMapsSDKforAndroid.Ifnecessary,youcanuseexcludegrouptoremovecertaindependencies:
implementation('com.mapbox.maps:android:10.5.0'){
excludegroup:'group_name',module:'module_name'
}
Additionally,runninggradleapp_module_name_here:dependenciesinyourcommandlinewillprintalistofdependencies../gradlewapp:dependenciesworksifyouhaveaGradlewrapper.TheyarehelpfulfortroubleshootingnimbleGradleconfigurationswhenvariouslibrariesareincludedinasingleproject.Youcanseethedependenciesthatspecificlibrariesarebringingandwhereconflictsmightbehappening.AddamapOpentheactivityyou’dliketoaddamaptoandusethecodebelow.importandroid.os.Bundleimportandroidx.appcompat.app.AppCompatActivityimportcom.mapbox.maps.MapViewimportcom.mapbox.maps.StylevarmapView:MapView?=nullclassMainActivity:AppCompatActivity(){overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)mapView=findViewById(R.id.mapView)mapView?.getMapboxMap()?.loadStyleUri(Style.MAPBOX_STREETS)}}CopyOpentheactivity’sXMLlayoutfileandaddthefollowing:CopyTheMapViewcontainsitsownlifecyclemethodsformanagingAndroid'sOpenGLlifecycle,whichmustbecalleddirectlyfromthecontainingActivity.InorderforyourapptocorrectlycalltheMapView'slifecyclemethods,youmustoverridethefollowinglifecyclemethodsintheActivitythatcontainstheMapViewandcalltherespectiveMapViewmethod.ThefollowinglifecyclemethodsmustbeoverriddenandincludethematchingMapViewmethod.Ifyou'reusingafragment,callmapview.onDestroy()insidethefragment'sonDestroyView()methodratherthaninsideonDestroy().overridefunonStart(){super.onStart()mapView?.onStart()}overridefunonStop(){super.onStop()mapView?.onStop()}overridefunonLowMemory(){super.onLowMemory()mapView?.onLowMemory()}overridefunonDestroy(){super.onDestroy()mapView?.onDestroy()}CopyShareyourfeedback