Pro Android with Kotlin


Download 5.42 Mb.
Pdf ko'rish
bet157/223
Sana04.11.2023
Hajmi5.42 Mb.
#1746807
1   ...   153   154   155   156   157   158   159   160   ...   223
Bog'liq
@de android telegram Pro Android with Kotlin Developing Modern Mobile

184
CHAPTER 8: APIs
Maps
Adding a map to your location-related app greatly improves the usability for your users.
To add a Google API map, the easiest way is to use the wizard provided by Android Studio. 
Follow these steps:
1. Add a map activity: right-click your module, in the menu choose 
New ➤ Activity ➤ Gallery, and from the gallery choose Google 
Maps Activity. Click Next. On the screen that follows, enter activity 
parameters according to your needs. However, choosing an 
appropriate activity name basically is all you need. The defaults make 
sense in most cases.
2. You need an API key to use Google Maps. For this purpose, inside 
the file /res/values/google_maps_api.xml, locate the link inside the 
comments; it might look like 
https://console.developers.google.
com/flows/enableapi?
.... Open this link in a browser and follow the 
instructions there. Finally, enter the key generated online as the text 
of the  element in that file.
What we have now is an activity class prepared for us, a fragment layout file that we can 
include in our app, and a registered API key that allows us to fetch maps data from the 
Google server.
To include the fragment as defined by /res/layout/activity_maps.xml, you write the 
following in your layout, with sizes adapted according to your needs:
android:layout_width="fill_parent"
android:layout_height="250dp"
layout="@layout/activity_maps" />
Inside the code we first add a snippet to fetch a map from the server. You do this inside your 
onCreate() callback as follows:
override fun onCreate(savedInstanceState: Bundle?) {
...
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map)
as SupportMapFragment
mapFragment.getMapAsync(this)
}
Here, R.id.map points to the map’s ID inside /res/layout/activity_maps.xml.
Next we add a callback that gets called when the map is loaded and ready to receive 
commands. To do so, we extend the activity that handles the map to also implement the 
interface com.google.android.gms.maps.OnMapReadyCallback.
class MainActivity : AppCompatActivity(),
OnMapReadyCallback { ... }



Download 5.42 Mb.

Do'stlaringiz bilan baham:
1   ...   153   154   155   156   157   158   159   160   ...   223




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling