Using the MapLibre GL Native SDK for Android with Amazon ...

文章推薦指數: 80 %
投票人數:10人

The MapLibre GL Native SDK for Android is a library based on Mapbox GL Native , and is compatible with the styles and tiles provided by the Amazon Location ... UsingtheMapLibreGLNativeSDKforAndroidwithAmazonLocationService-AmazonLocationServiceAWSDocumentationAmazonLocationServiceDeveloperGuideInitializationConfigurationActivitylayoutRequesttransformationMainactivityUsingtheMapLibreGLNativeSDKfor AndroidwithAmazonLocationServiceUseMapLibreGL NativeSDKtoembedinteractivemapsintoyourAndroid applications.TheMapLibreGLNativeSDKforAndroidisalibrarybasedonMapboxGLNative, andiscompatiblewiththestylesandtilesprovidedbytheAmazonLocationServiceMapsAPI. YoucanintegrateMapLibreGLNativeSDKforAndroidtoembedinteractivemap viewswithscalable,customizablevectormapsinyourAndroid applications.ThistutorialdescribeshowtointegratetheMapLibreGLNativeSDKfor AndroidwithAmazonLocation.Thesampleapplicationforthistutorialisavailableas partoftheAmazonLocationServicesamplesrepositoryonGitHub. Buildingthe application:Initialization Toinitializeyourapplication: CreateanewAndroidStudioprojectfromtheEmpty Activitytemplate. EnsurethatKotlinisselectedforthe projectlanguage. SelectaMinimumSDKofAPI14:Android4.0(IceCream Sandwich)ornewer. OpenProjectStructure,thengoto File>Project Structure...tochoosethe Dependenciessection. Withselected,thenchoose the+buttontoaddanewLibrary Dependency. AddAWSAndroidSDKversion2.20.0orlater. Forexample: com.amazonaws:aws-android-sdk-core:2.20.0 AddtheMapLibreGLNativeSDKforAndroid version9.4.0orlater.Forexample: org.maplibre.gl:android-sdk:9.4.0 Attheprojectlevelofyourbuild.gradle file,addthefollowingmavenrepositorytoaccesstheMapLibre packagesforAndroid: allprojects{ repositories{ //Retainyourexistingrepositories google() jcenter() //DeclaretherepositoriesforMapLibre mavenCentral() } } Buildingthe application:Configuration ToconfigureyourapplicationwithyourresourcesandAWSRegion: us-east-1:54f2ba88-9390-498d-aaa5-0d97fb7ca3bd ExampleMap us-east-1 Buildingthe application:Activitylayout Editapp/src/main/res/layout/activity_main.xml: AddaMapView,whichrendersthemap.Thiswillalso setthemap'sinitialcenterpoint. AddaTextView,whichdisplaysattribution. NoteYoumustprovidewordmarkortextattributionforeachdataprovider thatyouuse,eitheronyourapplicationoryourdocumentation. Attributionstringsareincludedinthestyledescriptorresponseunder thesources.esri.attributionand sources.here.attributionkeys.WhenusingAmazonLocation resourceswithdata providers,makesuretoreadtheservicetermsand conditions. Building theapplication:Requesttransformation CreateaclassnamedSigV4InterceptortointerceptAWS requestsandsignthemusingSignatureVersion 4.ThiswillberegisteredwiththeHTTPclientusedtofetch mapresourceswhentheMainActivityiscreated. packageaws.location.demo.okhttp importcom.amazonaws.DefaultRequest importcom.amazonaws.auth.AWS4Signer importcom.amazonaws.auth.AWSCredentialsProvider importcom.amazonaws.http.HttpMethodName importcom.amazonaws.util.IOUtils importokhttp3.HttpUrl importokhttp3.Interceptor importokhttp3.Request importokhttp3.Response importokio.Buffer importjava.io.ByteArrayInputStream importjava.net.URI classSigV4Interceptor( privatevalcredentialsProvider:AWSCredentialsProvider, privatevalserviceName:String ):Interceptor{ overridefunintercept(chain:Interceptor.Chain):Response{ valoriginalRequest=chain.request() if(originalRequest.url().host().contains("amazonaws.com")){ valsigner=if(originalRequest.url().encodedPath().contains("@")){ //thepresenceof"@"indicatesthatitdoesn'tneedtobedoubleURL-encoded AWS4Signer(false) }else{ AWS4Signer() } valawsRequest=toAWSRequest(originalRequest,serviceName) signer.setServiceName(serviceName) signer.sign(awsRequest,credentialsProvider.credentials) returnchain.proceed(toSignedOkHttpRequest(awsRequest,originalRequest)) } returnchain.proceed(originalRequest) } companionobject{ funtoAWSRequest(request:Request,serviceName:String):DefaultRequest{ //clonetherequest(AWS-style)sothatitcanbepopulatedwithcredentials valdr=DefaultRequest(serviceName) //copyrequestinfo dr.httpMethod=HttpMethodName.valueOf(request.method()) with(request.url()){ dr.resourcePath=uri().path dr.endpoint=URI.create("${scheme()}://${host()}") //copyparameters for(pinqueryParameterNames()){ if(p!=""){ dr.addParameter(p,queryParameter(p)) } } } //copyheaders for(hinrequest.headers().names()){ dr.addHeader(h,request.header(h)) } //copytherequestbody valbodyBytes=request.body()?.let{body-> valbuffer=Buffer() body.writeTo(buffer) IOUtils.toByteArray(buffer.inputStream()) } dr.content=ByteArrayInputStream(bodyBytes?:ByteArray(0)) returndr } funtoSignedOkHttpRequest( awsRequest:DefaultRequest, originalRequest:Request ):Request{ //copysignedrequestbackintoanOkHttpRequest valbuilder=Request.Builder() //copyheadersfromthesignedrequest for((k,v)inawsRequest.headers){ builder.addHeader(k,v) } //startbuildinganHttpUrl valurlBuilder=HttpUrl.Builder() .host(awsRequest.endpoint.host) .scheme(awsRequest.endpoint.scheme) .encodedPath(awsRequest.resourcePath) //copyparametersfromthesignedrequest for((k,v)inawsRequest.parameters){ urlBuilder.addQueryParameter(k,v) } returnbuilder.url(urlBuilder.build()) .method(originalRequest.method(),originalRequest.body()) .build() } } } Buildingthe application:Mainactivity TheMainActivityisresponsibleforinitializingtheviewsthatwillbe displayedtousers.Thisinvolves: InstantiatinganAmazonCognitoCredentialsProvider. RegisteringtheSignatureVersion4interceptor. Configuringthemapbypointingitatamapstyledescriptor,and displayingappropriateattribution. MainActivityisalsoresponsibleforforwardinglifecycle eventstothemapview,allowingittopreservetheactiveviewportbetween invocations. packageaws.location.demo.maplibre importandroid.os.Bundle importandroid.widget.TextView importandroidx.appcompat.app.AppCompatActivity importaws.location.demo.okhttp.SigV4Interceptor importcom.amazonaws.auth.CognitoCachingCredentialsProvider importcom.amazonaws.regions.Regions importcom.mapbox.mapboxsdk.Mapbox importcom.mapbox.mapboxsdk.maps.MapView importcom.mapbox.mapboxsdk.maps.Style importcom.mapbox.mapboxsdk.module.http.HttpRequestUtil importokhttp3.OkHttpClient privateconstvalSERVICE_NAME="geo" classMainActivity:AppCompatActivity(){ privatevarmapView:MapView?=null overridefunonCreate(savedInstanceState:Bundle?){ super.onCreate(savedInstanceState) //configuration validentityPoolId=getString(R.string.identityPoolId) valregion=getString(R.string.awsRegion) valmapName=getString(R.string.mapName) //Credentialinitialization valcredentialProvider=CognitoCachingCredentialsProvider( applicationContext, identityPoolId, Regions.fromName(identityPoolId.split(":").first()) ) //initializeMapLibre Mapbox.getInstance(this,null) HttpRequestUtil.setOkHttpClient( OkHttpClient.Builder() .addInterceptor(SigV4Interceptor(credentialProvider,SERVICE_NAME)) .build() ) //initializetheview setContentView(R.layout.activity_main) //initializethemapview mapView=findViewById(R.id.mapView) mapView?.onCreate(savedInstanceState) mapView?.getMapAsync{map-> map.setStyle( Style.Builder() .fromUri("https://maps.geo.${region}.amazonaws.com/maps/v0/maps/${mapName}/style-descriptor") ){style-> findViewById(R.id.attributionView).text=style.sources.first()?.attribution } } } overridefunonStart(){ super.onStart() mapView?.onStart() } overridefunonResume(){ super.onResume() mapView?.onResume() } overridefunonPause(){ super.onPause() mapView?.onPause() } overridefunonStop(){ super.onStop() mapView?.onStop() } overridefunonSaveInstanceState(outState:Bundle){ super.onSaveInstanceState(outState) mapView?.onSaveInstanceState(outState) } overridefunonLowMemory(){ super.onLowMemory() mapView?.onLowMemory() } overridefunonDestroy(){ super.onDestroy() mapView?.onDestroy() } } Runningthisapplicationdisplaysafull-screenmapinthestyleofyour choosing.ThissampleisavailableaspartoftheAmazonLocationServicesamplesrepositoryon GitHub.DocumentConventionsMapLibreGLJSMapLibreGLNativeSDKforiOSDidthispagehelpyou?-YesThanksforlettingusknowwe'redoingagoodjob!Ifyou'vegotamoment,pleasetelluswhatwedidrightsowecandomoreofit.Didthispagehelpyou?-NoThanksforlettingusknowthispageneedswork.We'resorryweletyoudown.Ifyou'vegotamoment,pleasetellushowwecanmakethedocumentationbetter.



請為這篇文章評分?