Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.
This codelab is part of the Advanced Android in Kotlin course. You'll get the most value out of this course if you work through the codelabs in sequence, but it is not mandatory. All the course codelabs are listed on the Advanced Android in Kotlin codelabs landing page.
This codelab is part of a series that guides you through adding maps to your apps. We recommend that you do all the codelabs in order, because they progress through tasks step-by-step.
The codelabs in this series are:
- Download Google Earth in Apple App Store Download Google Earth in Google Play Store Launch Earth. Create stories and maps. With creation tools, you can draw on the map, add.
- Googlemapsapi.xml—You use this configuration file to hold your API key. The template generates two googlemapsapi.xml files: one for debug and one for release. The file for the API key for the debug certificate is located in src/debug/res/values.
- Sign in - Google Accounts.
Building apps with Google Maps allows you to add features to your app, such as satellite imagery, robust UI controls for maps, location tracking, and location markers. You can add value to the standard Google Maps by showing information from your own dataset, such as the locations of well-known fishing or climbing areas. You can also create games in which the player explores the physical world, like in a treasure hunt or even augmented reality games.
In this lesson, you create a Google Maps app called Wander that displays customized maps and shows the user's location.
What you'll learn
- How to get an API key from the Google API Console and register the key to your app
- How to integrate a Google Map in your app
- How to display different map types
- How to style the Google Map
- How to add markers to your map
- How to enable the user to place a marker on a point of interest (POI)
- How to enable location tracking
- How to create The
Wander
app, which has an embedded Google Map - How to create custom features for your app, such as markers and styling
- How to enable location tracking in your app
In this codelab, you create the Wander
app, which displays a Google map with custom styling. The Wander app allows you to drop markers onto locations, add overlays, and see your location in real time.
The Maps SDK for Android requires an API key. To obtain the API key, register your project in the API & Services page. The API key is tied to a digital certificate that links the app to its author. For more information about using digital certificates and signing your app, see Sign your app.
In this codelab, you use the API key for the debug certificate. The debug certificate is insecure by design, as described in Sign your debug build. Published Android apps that use the Maps SDK for Android require a second API key: the key for the release certificate. For more information about obtaining a release certificate, see Get an API Key.
Android Studio includes a Google Maps Activity template, which generates helpful template code. The template code includes a google_maps_api.xml file containing a link that simplifies obtaining an API key.
Note: If you want to build the activity without using the template, follow the steps in the Get an API Key to obtain the API key without using the link in the template.
- Name the project
Wander
. - Set the minimum API level to API 19. Make sure the language is Kotlin.
- Click Finish.
- Once the app is done building, take a look at your project and the following maps-related files that Android Studio creates for you:
google_maps_api.xml—You use this configuration file to hold your API key. The template generates two google_maps_api.xml files: one for debug and one for release. The file for the API key for the debug certificate is located in src/debug/res/values. The file for the API key for the release certificate is located in src/release/res/values. In this codelab, you only use the debug certificate.
activity_maps.xml—This layout file contains a single fragment that fills the entire screen. The SupportMapFragment
class is a subclass of the Fragment
class. A SupportMapFragment
is the simplest way to place a map in an app. It's a wrapper around a view of a map to automatically handle the necessary lifecycle needs.
You can include SupportMapFragment
in a layout file using a <fragment>
tag in any ViewGroup
, with an additional name
attribute.
MapsActivity.java—The MapsActivity.kt file instantiates the SupportMapFragment
in the onCreate()
method, and uses the class' getMapAsync
()
to automatically initialize the maps system and the view. The activity that contains the SupportMapFragment
must implement the OnMapReadyCallback
interface and that interface's onMapReady()
method. The onMapReady()
method is called when the map is loaded.
Note: If you run the app now, the map fails to load. If you look in the logs, you see a message saying that your API key is not properly set up. In the next step, you obtain the API key to make the app display the map.
Note: If you test the Wander app on an emulator, you must use a system image that includes Google Play. Select an image that shows Google Play in the Target column of the virtual-devices list.
AIza'
.google_maps_api.xml
file, paste the key into the google_maps_key
string where it says YOUR_KEY_HERE
.Note: The API key may take up to 5 minutes to take effect. You may also need to restart Android Studio.
MapsActivity has a private lateinit
var
called mMap
, which is of type GoogleMap
. To follow Kotlin naming conventions, change the name of mMap
to map
.- In
MapsActivity
, right-click mMap
and click Refactor > Rename...
- Change the variable name to
map
.
MapsActivity
, right-click mMap
and click Refactor > Rename...map
.Notice how all the references to mMap
in the onMapReady()
function also change to map
.
Google Maps includes several map types: normal, hybrid, satellite, terrain, and 'none' (for no map at all).
Normal map | Satellite map | Hybrid map | Terrain map |
Each type of map provides different kinds of information. For example, when using maps for navigation in a car, it's helpful to see street names, so you could use the normal option. When you are hiking, the terrain map could be helpful to decide how much more you have to climb to get to the top.
In this task you:
- Add an app bar with an options menu that allows the user to change the map type.
- Move the map's starting location to your own home location.
- Add support for markers, which indicate single locations on a map and can include a label.
In this step, you add an app bar with an options menu that allows the user to change the map type.
- To create a new menu XML file, right-click your res directory and select New > Android Resource File.
- In the dialog, name the file
map_options
. - Choose Menu for the resource type.
- Click OK.
- In the Code tab, replace the code in the new file with the following code to create the map menu options. The 'none' map type is omitted because 'none' results in the lack of any map at all. This step causes an error, but you resolve it in the next step.
- In
strings.xml
, add resources for thetitle
attributes in order to resolve the errors.
- In
MapsActivity
, override theonCreateOptionsMenu()
method and inflate the menu from themap_options
resource file.
- In
MapsActivity.kt
, override theonOptionsItemSelected()
method. Change the map type using map-type constants to reflect the user's selection.
- Run the app.
- Click to change the map type. Notice how the map's appearance changes between the different modes.
By default, the onMapReady()
callback includes code that places a marker in Sydney, Australia, where Google Maps was created. The default callback also animates the map to pan to Sydney.
In this task, you make the map's camera move to your home, zoom to a level you specify, and place a marker there.
MapsActivity.kt
file, find the onMapReady()
method. Remove the code in it that places the marker in Sydney and moves the camera. This is what your method should look like now.- Find the latitude and longitude of your home by following these instructions.
- Create a value for the latitude and a value for the longitude, and input their float values.
- Create a new
LatLng
object calledhomeLatLng
. In thehomeLatLng
object, pass in the values you just created.
- Create a
val
for how zoomed in you want to be on the map. Use zoom level 15f.
The zoom level controls how zoomed in you are on the map. The following list gives you an idea of what level of detail each level of zoom shows:
1
: World5
: Landmass/continent10
: City15
: Streets20
: Buildings
- Move the camera to
homeLatLng
by calling themoveCamera()
function on themap
object and pass in aCameraUpdate
object usingCameraUpdateFactory.newLatLngZoom()
. Pass in thehomeLatLng
object and thezoomLevel
.
- Add a marker to the map at
homeLatLng
.
Your final method should look like this:
- Run your app. The map should pan to your home, zoom to the desired level, and place a marker on your home.
Google Maps Satellite View
MapsActivity
called setMapLongClick()
that takes a GoogleMap
as an argument.setOnMapLongClickListener
listener to the map object.- In
setOnMapLongClickListener()
, call theaddMarker()
method. Pass in a newMarkerOptions
object with the position set to the passed-inLatLng
.
- At the end of the
onMapReady()
method, callsetMapLongClick()
withmap
.
- Run your app.
- Touch and hold the map to place a marker at a location.
- Tap the marker, which centers it on the screen.
Note: When a marker is tapped, navigation buttons appear, allowing the user to use the Google Maps app to navigate to the marked position.
InfoWindow that displays the coordinates of the marker when the marker is tapped.- In
setMapLongClick()setOnMapLongClickListener()
, create a val
for snippet
. A snippet is additional text displayed after the title. Your snippet displays the latitude and longitude of a marker.
- In
addMarker()
, set the title
of the marker to Dropped Pin using a R.string.
dropped_pin
string resource. - Set the marker's
snippet
to snippet
.
setMapLongClick()setOnMapLongClickListener()
, create a val
for snippet
. A snippet is additional text displayed after the title. Your snippet displays the latitude and longitude of a marker.addMarker()
, set the title
of the marker to Dropped Pin using a R.string.
dropped_pin
string resource.snippet
to snippet
.The completed function looks like this:
- Run your app.
- Touch and hold the map to drop a location marker.
- Tap the marker to show the info window.
normal, business POIs also appear on the map. Business POIs represent businesses, such as shops, restaurants, and hotels.
In this step, you add a GoogleMap.OnPoiClickListener
to the map. This click listener places a marker on the map immediately when the user clicks a POI. The click listener also displays an info window that contains the POI name.
- Create a method stub in
MapsActivity
calledsetPoiClick()
that takes aGoogleMap
as an argument. - In the
setPoiClick()
method, set anOnPoiClickListener
on the passed-inGoogleMap
.
- In the
setOnPoiClickListener()
, create aval poiMarker
for the marker . - Set it to a marker using
map.addMarker()
withMarkerOptions
setting thetitle
to the name of the POI.
- In the
setOnPoiClickListener()
function, callshowInfoWindow()
onpoiMarker
to immediately show the info window.
Your final code for the setPoiClick()
function should look like this.
- At the end of
onMapReady()
, callsetPoiClick()
and pass inmap
.
- Run your app and find a POI, such as a park or a coffee shop.
- Tap the POI to place a marker on it and display the POI's name in an info window.
You can customize Google Maps in many ways, giving your map a unique look and feel.
You can customize a MapFragment
object using the available XML attributes, as you would customize any other fragment. However, in this step, you customize the look and feel of the content of the MapFragment
, using methods on the GoogleMap
object.
To create a customized style for your map, you generate a JSON file that specifies how features in the map are displayed. You don't have to create this JSON file manually. Google provides the Maps Platform Styling Wizard, which generates the JSON for you after you visually style your map. In this task, you style the map with a retro theme, meaning that the map uses vintage colors and you add colored roads.
Note: Styling only applies to maps that use the normal
map type.
- Click More Options.
- Select Road > Fill.
- Change the color of the roads to any color you choose (such as pink).
- Click Finish.
- Copy the JSON code from the resulting dialog and, if you wish, stash it in a plain text note for use in the next step.
res
directory, create a resource directory and name it raw
. You use the raw
directory resources like JSON code.res/raw
called map_style.json
.MapsActivity
, create a TAG
class variable above the onCreate()
method. This is used for logging purposes.- Also in
MapsActivity
, create asetMapStyle()
function that takes in aGoogleMap
. - In
setMapStyle()
, add atry{}
block. - In the
try{}
block, create aval success
for the success of styling. (You add the following catch block.) - In the
try{}
block, set the JSON style to the map, callsetMapStyle()
on theGoogleMap
object. Pass in aMapStyleOptions
object, which loads the JSON file. - Assign the result to
success
. ThesetMapStyle()
method returns a boolean indicating the success status of parsing the styling file and setting the style.
- Add an if statement for
success
being false. If the styling is unsuccessful, print a log that the parsing has failed.
- Add a
catch{}
block to handle the situation of a missing style file. In thecatch
block, if the file can't be loaded, then throw aResources.NotFoundException
.
The finished method should look like the following code snippet:
- Finally, call the
setMapStyle()
method in theonMapReady()
method passing in yourGoogleMap
object.
- Run your app.
- Set the map to
normal
mode and the new styling should be visible with retro theming and roads of your chosen color.
Note: If you zoom out enough, the map does not show roads anymore, so you don't see them.
onMapLongClick()
method, add the following line of code to the MarkerOptions()
of the constructor to use the default marker, but change the color to blue.Now onMapLongClickListener()
looks like this:
- Run the app. The markers that appear after you long click are now shaded blue. Note that POI markers are still red because you didn't add styling to the
onPoiClick()
method.
One way you can customize the Google map is by drawing on top of it. This technique is useful if you want to highlight a particular type of location, such as popular fishing spots.
- Shapes: You can add polylines, polygons, and circles to the map.
GroundOverlay
objects: A ground overlay is an image that is fixed to a map. Unlike markers, ground overlays are oriented to the Earth's surface rather than to the screen. Rotating, tilting, or zooming the map changes the orientation of the image. Ground overlays are useful when you wish to fix a single image in one area on the map.
res/drawable
folder. (Make sure the file name is android.png
.)- In
onMapReady()
, after the call to move the camera to your home's position, create aGroundOverlayOptions
object. - Assign the object to a variable called
androidOverlay
.
- Use the
BitmapDescriptorFactory.fromResource()
method to create aBitmapDescriptor
object from the downloaded image resource. - Pass the resulting
BitmapDescriptor
object into theimage()
method of theGroundOverlayOptions
object.
- Create a
float overlaySize
for the width in meters of the desired overlay. For this example, a width of100f
works well.
Set the position
property for the GroundOverlayOptions
object by calling the position()
method, and pass in the homeLatLng
object and the overlaySize
.
- Call
addGroundOverlay()
on theGoogleMap
object and pass in yourGroundOverlayOptions
object.
- Run the app.
- Change the value of
zoomLevel
to 18f to see the Android image as an overlay.
Users often use Google Maps to see their current location. To display the device location on your map, you can use the location-data layer.
The location-data layer adds My Location icon to the map.
When the user taps the button, the map centers on the device's location. The location is shown as a blue dot if the device is stationary and as a blue chevron if the device is moving.
In this task, you enable the location-data layer.
AndroidManifest.xml
file, verify that the FINE_LOCATION
permission is already present. Android Studio inserted this permission when you selected the Google Maps template.- In
MapsActivity
, create aREQUEST_LOCATION_PERMISSION
class variable.
- To check if permissions are granted, create a method in the
MapsActivity
calledisPermissionGranted()
. In this method, check if the user has granted the permission.
- To enable location tracking in your app, create a method in
MapsActivity
calledenableMyLocation()
that takes no arguments and doesn't return anything. Inside, check for theACCESS_FINE_LOCATION
permission. If the permission is granted, enable the location layer. Otherwise, request the permission.
- Call
enableMyLocation()
from theonMapReady()
callback to enable the location layer.
- Override the
onRequestPermissionsResult()
method. Check if therequestCode
is equal toREQUEST_LOCATION_PERMISSION
. If it is, that means that the permission is granted. If the permission is granted, also check if thegrantResults
array containsPackageManager.PERMISSION_GRANTED
in its first slot. If that is true, callenableMyLocation()
.
- Run your app. There should be a dialog requesting access to the device's location. Go ahead and allow permission.
Note: This dialog may look different if you are not running API level 29.
The map now displays the device's current location using a blue dot. Notice that there is a location button. If you move the map away from your location and click this button, it centers the map back to the device's location.
Note: When you run the app on an emulator, the location may not be available. If you haven't used the emulator settings to set a location, the location button is unavailable.
Download the code for the finished codelab.
Alternatively, you can download the repository as a zip file, unzip it and open it in Android Studio.
Note: You need to add an API key to the solution code or no map appears.
Congratulations! You added a Google map to an Android Kotlin app and styled it.
Android developer documentation:
Reference documentation:
For links to other codelabs in this course, see the Advanced Android in Kotlin codelabs landing page.
This codelab is part of the Advanced Android in Kotlin course. You'll get the most value out of this course if you work through the codelabs in sequence, but it is not mandatory. All the course codelabs are listed on the Advanced Android in Kotlin codelabs landing page.
This codelab is part of a series that guides you through adding maps to your apps. We recommend that you do all the codelabs in order, because they progress through tasks step-by-step.
The codelabs in this series are:
Building apps with Google Maps allows you to add features to your app, such as satellite imagery, robust UI controls for maps, location tracking, and location markers. You can add value to the standard Google Maps by showing information from your own dataset, such as the locations of well-known fishing or climbing areas. You can also create games in which the player explores the physical world, like in a treasure hunt or even augmented reality games.
In this lesson, you create a Google Maps app called Wander that displays customized maps and shows the user's location.
What you'll learn
- How to get an API key from the Google API Console and register the key to your app
- How to integrate a Google Map in your app
- How to display different map types
- How to style the Google Map
- How to add markers to your map
- How to enable the user to place a marker on a point of interest (POI)
- How to enable location tracking
- How to create The
Wander
app, which has an embedded Google Map - How to create custom features for your app, such as markers and styling
- How to enable location tracking in your app
In this codelab, you create the Wander
app, which displays a Google map with custom styling. The Wander app allows you to drop markers onto locations, add overlays, and see your location in real time.
The Maps SDK for Android requires an API key. To obtain the API key, register your project in the API & Services page. The API key is tied to a digital certificate that links the app to its author. For more information about using digital certificates and signing your app, see Sign your app.
In this codelab, you use the API key for the debug certificate. The debug certificate is insecure by design, as described in Sign your debug build. Published Android apps that use the Maps SDK for Android require a second API key: the key for the release certificate. For more information about obtaining a release certificate, see Get an API Key.
Android Studio includes a Google Maps Activity template, which generates helpful template code. The template code includes a google_maps_api.xml file containing a link that simplifies obtaining an API key.
Note: If you want to build the activity without using the template, follow the steps in the Get an API Key to obtain the API key without using the link in the template.
- Name the project
Wander
. - Set the minimum API level to API 19. Make sure the language is Kotlin.
- Click Finish.
- Once the app is done building, take a look at your project and the following maps-related files that Android Studio creates for you:
google_maps_api.xml—You use this configuration file to hold your API key. The template generates two google_maps_api.xml files: one for debug and one for release. The file for the API key for the debug certificate is located in src/debug/res/values. The file for the API key for the release certificate is located in src/release/res/values. In this codelab, you only use the debug certificate.
activity_maps.xml—This layout file contains a single fragment that fills the entire screen. The SupportMapFragment
class is a subclass of the Fragment
class. A SupportMapFragment
is the simplest way to place a map in an app. It's a wrapper around a view of a map to automatically handle the necessary lifecycle needs.
You can include SupportMapFragment
in a layout file using a <fragment>
tag in any ViewGroup
, with an additional name
attribute.
MapsActivity.java—The MapsActivity.kt file instantiates the SupportMapFragment
in the onCreate()
method, and uses the class' getMapAsync
()
to automatically initialize the maps system and the view. The activity that contains the SupportMapFragment
must implement the OnMapReadyCallback
interface and that interface's onMapReady()
method. The onMapReady()
method is called when the map is loaded.
Note: If you run the app now, the map fails to load. If you look in the logs, you see a message saying that your API key is not properly set up. In the next step, you obtain the API key to make the app display the map.
Note: If you test the Wander app on an emulator, you must use a system image that includes Google Play. Select an image that shows Google Play in the Target column of the virtual-devices list.
AIza'
.google_maps_api.xml
file, paste the key into the google_maps_key
string where it says YOUR_KEY_HERE
.Note: The API key may take up to 5 minutes to take effect. You may also need to restart Android Studio.
MapsActivity has a private lateinit
var
called mMap
, which is of type GoogleMap
. To follow Kotlin naming conventions, change the name of mMap
to map
.- In
MapsActivity
, right-click mMap
and click Refactor > Rename...
- Change the variable name to
map
.
MapsActivity
, right-click mMap
and click Refactor > Rename...map
.Notice how all the references to mMap
in the onMapReady()
function also change to map
.
Google Maps includes several map types: normal, hybrid, satellite, terrain, and 'none' (for no map at all).
Normal map | Satellite map | Hybrid map | Terrain map |
Each type of map provides different kinds of information. For example, when using maps for navigation in a car, it's helpful to see street names, so you could use the normal option. When you are hiking, the terrain map could be helpful to decide how much more you have to climb to get to the top.
In this task you:
- Add an app bar with an options menu that allows the user to change the map type.
- Move the map's starting location to your own home location.
- Add support for markers, which indicate single locations on a map and can include a label.
map_options
.- In
strings.xml
, add resources for thetitle
attributes in order to resolve the errors.
- In
MapsActivity
, override theonCreateOptionsMenu()
method and inflate the menu from themap_options
resource file.
- In
MapsActivity.kt
, override theonOptionsItemSelected()
method. Change the map type using map-type constants to reflect the user's selection.
- Run the app.
- Click to change the map type. Notice how the map's appearance changes between the different modes.
By default, the onMapReady()
callback includes code that places a marker in Sydney, Australia, where Google Maps was created. The default callback also animates the map to pan to Sydney.
In this task, you make the map's camera move to your home, zoom to a level you specify, and place a marker there.
MapsActivity.kt
file, find the onMapReady()
method. Remove the code in it that places the marker in Sydney and moves the camera. This is what your method should look like now.- Find the latitude and longitude of your home by following these instructions.
- Create a value for the latitude and a value for the longitude, and input their float values.
- Create a new
LatLng
object calledhomeLatLng
. In thehomeLatLng
object, pass in the values you just created.
- Create a
val
for how zoomed in you want to be on the map. Use zoom level 15f.
The zoom level controls how zoomed in you are on the map. The following list gives you an idea of what level of detail each level of zoom shows:
1
: World5
: Landmass/continent10
: City15
: Streets20
: Buildings
- Move the camera to
homeLatLng
by calling themoveCamera()
function on themap
object and pass in aCameraUpdate
object usingCameraUpdateFactory.newLatLngZoom()
. Pass in thehomeLatLng
object and thezoomLevel
.
- Add a marker to the map at
homeLatLng
.
Your final method should look like this:
- Run your app. The map should pan to your home, zoom to the desired level, and place a marker on your home.
MapsActivity
called setMapLongClick()
that takes a GoogleMap
as an argument.setOnMapLongClickListener
listener to the map object.- In
setOnMapLongClickListener()
, call theaddMarker()
method. Pass in a newMarkerOptions
object with the position set to the passed-inLatLng
.
- At the end of the
onMapReady()
method, callsetMapLongClick()
withmap
.
- Run your app.
- Touch and hold the map to place a marker at a location.
- Tap the marker, which centers it on the screen.
Note: When a marker is tapped, navigation buttons appear, allowing the user to use the Google Maps app to navigate to the marked position.
InfoWindow that displays the coordinates of the marker when the marker is tapped.- In
setMapLongClick()setOnMapLongClickListener()
, create a val
for snippet
. A snippet is additional text displayed after the title. Your snippet displays the latitude and longitude of a marker.
- In
addMarker()
, set the title
of the marker to Dropped Pin using a R.string.
dropped_pin
string resource. - Set the marker's
snippet
to snippet
.
setMapLongClick()setOnMapLongClickListener()
, create a val
for snippet
. A snippet is additional text displayed after the title. Your snippet displays the latitude and longitude of a marker.addMarker()
, set the title
of the marker to Dropped Pin using a R.string.
dropped_pin
string resource.snippet
to snippet
.The completed function looks like this:
- Run your app.
- Touch and hold the map to drop a location marker.
- Tap the marker to show the info window.
normal, business POIs also appear on the map. Business POIs represent businesses, such as shops, restaurants, and hotels.
In this step, you add a GoogleMap.OnPoiClickListener
to the map. This click listener places a marker on the map immediately when the user clicks a POI. The click listener also displays an info window that contains the POI name.
- Create a method stub in
MapsActivity
calledsetPoiClick()
that takes aGoogleMap
as an argument. - In the
setPoiClick()
method, set anOnPoiClickListener
on the passed-inGoogleMap
.
- In the
setOnPoiClickListener()
, create aval poiMarker
for the marker . - Set it to a marker using
map.addMarker()
withMarkerOptions
setting thetitle
to the name of the POI.
- In the
setOnPoiClickListener()
function, callshowInfoWindow()
onpoiMarker
to immediately show the info window.
Your final code for the setPoiClick()
function should look like this.
- At the end of
onMapReady()
, callsetPoiClick()
and pass inmap
.
- Run your app and find a POI, such as a park or a coffee shop.
- Tap the POI to place a marker on it and display the POI's name in an info window.
You can customize Google Maps in many ways, giving your map a unique look and feel.
You can customize a MapFragment
object using the available XML attributes, as you would customize any other fragment. However, in this step, you customize the look and feel of the content of the MapFragment
, using methods on the GoogleMap
object.
To create a customized style for your map, you generate a JSON file that specifies how features in the map are displayed. You don't have to create this JSON file manually. Google provides the Maps Platform Styling Wizard, which generates the JSON for you after you visually style your map. In this task, you style the map with a retro theme, meaning that the map uses vintage colors and you add colored roads.
Note: Styling only applies to maps that use the normal
map type.
- Click More Options.
- Select Road > Fill.
- Change the color of the roads to any color you choose (such as pink).
- Click Finish.
- Copy the JSON code from the resulting dialog and, if you wish, stash it in a plain text note for use in the next step.
res
directory, create a resource directory and name it raw
. You use the raw
directory resources like JSON code.res/raw
called map_style.json
.MapsActivity
, create a TAG
class variable above the onCreate()
method. This is used for logging purposes.- Also in
MapsActivity
, create asetMapStyle()
function that takes in aGoogleMap
. - In
setMapStyle()
, add atry{}
block. - In the
try{}
block, create aval success
for the success of styling. (You add the following catch block.) - In the
try{}
block, set the JSON style to the map, callsetMapStyle()
on theGoogleMap
object. Pass in aMapStyleOptions
object, which loads the JSON file. - Assign the result to
success
. ThesetMapStyle()
method returns a boolean indicating the success status of parsing the styling file and setting the style.
- Add an if statement for
success
being false. If the styling is unsuccessful, print a log that the parsing has failed.
- Add a
catch{}
block to handle the situation of a missing style file. In thecatch
block, if the file can't be loaded, then throw aResources.NotFoundException
.
The finished method should look like the following code snippet:
- Finally, call the
setMapStyle()
method in theonMapReady()
method passing in yourGoogleMap
object.
- Run your app.
- Set the map to
normal
mode and the new styling should be visible with retro theming and roads of your chosen color.
Note: If you zoom out enough, the map does not show roads anymore, so you don't see them.
onMapLongClick()
method, add the following line of code to the MarkerOptions()
of the constructor to use the default marker, but change the color to blue.Now onMapLongClickListener()
looks like this:
- Run the app. The markers that appear after you long click are now shaded blue. Note that POI markers are still red because you didn't add styling to the
onPoiClick()
method.
One way you can customize the Google map is by drawing on top of it. This technique is useful if you want to highlight a particular type of location, such as popular fishing spots.
- Shapes: You can add polylines, polygons, and circles to the map.
GroundOverlay
objects: A ground overlay is an image that is fixed to a map. Unlike markers, ground overlays are oriented to the Earth's surface rather than to the screen. Rotating, tilting, or zooming the map changes the orientation of the image. Ground overlays are useful when you wish to fix a single image in one area on the map.
res/drawable
folder. (Make sure the file name is android.png
.)- In
onMapReady()
, after the call to move the camera to your home's position, create aGroundOverlayOptions
object. - Assign the object to a variable called
androidOverlay
.
- Use the
BitmapDescriptorFactory.fromResource()
method to create aBitmapDescriptor
object from the downloaded image resource. - Pass the resulting
BitmapDescriptor
object into theimage()
method of theGroundOverlayOptions
object.
- Create a
float overlaySize
for the width in meters of the desired overlay. For this example, a width of100f
works well.
Set the position
property for the GroundOverlayOptions
object by calling the position()
method, and pass in the homeLatLng
object and the overlaySize
.
- Call
addGroundOverlay()
on theGoogleMap
object and pass in yourGroundOverlayOptions
object.
- Run the app.
- Change the value of
zoomLevel
to 18f to see the Android image as an overlay.
Users often use Google Maps to see their current location. To display the device location on your map, you can use the location-data layer.
The location-data layer adds My Location icon to the map.
Google Maps App
When the user taps the button, the map centers on the device's location. The location is shown as a blue dot if the device is stationary and as a blue chevron if the device is moving.
In this task, you enable the location-data layer.
AndroidManifest.xml
file, verify that the FINE_LOCATION
permission is already present. Android Studio inserted this permission when you selected the Google Maps template.- In
MapsActivity
, create aREQUEST_LOCATION_PERMISSION
class variable.
- To check if permissions are granted, create a method in the
MapsActivity
calledisPermissionGranted()
. In this method, check if the user has granted the permission.
- To enable location tracking in your app, create a method in
MapsActivity
calledenableMyLocation()
that takes no arguments and doesn't return anything. Inside, check for theACCESS_FINE_LOCATION
permission. If the permission is granted, enable the location layer. Otherwise, request the permission.
- Call
enableMyLocation()
from theonMapReady()
callback to enable the location layer.
- Override the
onRequestPermissionsResult()
method. Check if therequestCode
is equal toREQUEST_LOCATION_PERMISSION
. If it is, that means that the permission is granted. If the permission is granted, also check if thegrantResults
array containsPackageManager.PERMISSION_GRANTED
in its first slot. If that is true, callenableMyLocation()
.
Google Maps Street View
- Run your app. There should be a dialog requesting access to the device's location. Go ahead and allow permission.
Note: This dialog may look different if you are not running API level 29.
The map now displays the device's current location using a blue dot. Notice that there is a location button. If you move the map away from your location and click this button, it centers the map back to the device's location.
Google Maps Google Earth Satellite View
Note: When you run the app on an emulator, the location may not be available. If you haven't used the emulator settings to set a location, the location button is unavailable.
Download the code for the finished codelab.
Alternatively, you can download the repository as a zip file, unzip it and open it in Android Studio.
Note: You need to add an API key to the solution code or no map appears.
Congratulations! You added a Google map to an Android Kotlin app and styled it.
Google Maps Timeline
Android developer documentation:
Reference documentation:
For links to other codelabs in this course, see the Advanced Android in Kotlin codelabs landing page.