Map add marker android

Содержание
  1. How to Add Custom Marker to Google Maps in Android?
  2. What we are going to build in this article?
  3. Step by Step Implementation
  4. Markers and annotations
  5. Annotations
  6. Default markers
  7. Other shapes
  8. Interactivity
  9. Style layers
  10. Marker
  11. Example
  12. Developer Guide
  13. Add a map to your Android app (Kotlin)
  14. 1. Before You Begin
  15. Prerequisites
  16. What you’ll do
  17. What you’ll need
  18. 2. Get set up
  19. Set up Google Maps Platform
  20. 3. Quick start
  21. 4. Add Google Maps
  22. Add your API key
  23. local.properties
  24. app-level build.gradle
  25. project-level build.gradle
  26. Add Google Maps dependency
  27. build.gradle
  28. AndroidManifest.xml
  29. activity_main.xml
  30. MainActivity
  31. 5. Add markers
  32. Get a reference to GoogleMap
  33. MainActivity.onCreate()
  34. Provided class: PlacesReader
  35. PlacesReader
  36. Load places
  37. MainActivity.places
  38. Place
  39. Add markers to map
  40. MainActivity.addMarkers()
  41. 6. Customize markers
  42. Adding an info window
  43. Create marker_info_contents.xml
  44. marker_info_contents.xml
  45. Create an implementation of an InfoWindowAdapter
  46. MarkerInfoWindowAdapter
  47. Update MainActivity
  48. MainActivity.onCreate()
  49. MainActivity.addMarkers()
  50. Add a custom marker image
  51. Set custom bitmap on marker
  52. BitmapHelper
  53. Using the helper method, declare a new property called bicycleIcon and give it the following definition: MainActivity.bicycleIcon
  54. MainActivity.addMarkers()
  55. 7. Cluster markers
  56. Maps SDK for Android Utility Library
  57. Update your build.gradle
  58. build.gradle
  59. Implement clustering
  60. Implement the ClusterItem interface
  61. Place
  62. Subclass the DefaultClusterRenderer class
  63. PlaceRenderer
  64. Create a ClusterManager and add items
  65. MainActivity.onCreate()
  66. MainActivity.addClusteredMarkers()
  67. 8. Draw on the map
  68. Add click listener
  69. MainActivity.addClusteredMarkers()
  70. MainActivity.addCircle()
  71. 9. Camera Control
  72. Camera and view
  73. MainActivity.onCreate()
  74. Listening to camera changes
  75. MainActivity.addClusteredMarkers()
  76. MainActivity.addClusteredMarkers()
  77. 10. Maps KTX
  78. build.gradle
  79. MainActivity.addMarkers(GoogleMap)
  80. MainActivity.addCircle(GoogleMap)
  81. MainActivity.onCreate(Bundle)
  82. 11. Congratulations
  83. Learn more

How to Add Custom Marker to Google Maps in Android?

Google Maps is used in many apps for displaying a location and indicating a specific location on a map. We have seen the use of maps in many apps that provides services such as Ola, Uber, and many more. In these apps, you will get to see How we can add Custom Marker to Google Maps in Android.

What we are going to build in this article?

We will be building a simple application in which we will display a map and on that map, we will be displaying a custom marker on our app. Below is the screenshot in which we will get to see what we are going to do in this project. Note that we are going to implement this project using the Java language.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Make sure to select Maps Activity while creating a new Project.

Step 2: Generating an API key for using Google Maps

To generate the API key for Maps you may refer to How to Generate API Key for Using Google Maps in Android. After generating your API key for Google Maps. We have to add this key to our Project. For adding this key in our app navigate to the values folder > google_maps_api.xml file and at line 23 you have to add your API key in the place of YOUR_API_KEY. After adding this now we are ready for adding the custom marker to our app. After adding the API key, you can run your app and you will get to see a default marker on the Sydney location with the default marker.

Step 3: Adding a custom marker in Google Maps

For adding a custom marker to Google Maps navigate to the app > res > drawable > Right-Click on it > New > Vector Assets and select the icon which we have to show on your Map. You can change the color according to our requirements. After creating this icon now we will move towards adding this marker to our Map.

Источник

Markers and annotations

The Mapbox Maps SDK for Android offers several ways to add markers, annotations, and other shapes to a map. This guide helps you choose the best approach for your application based on factors like interaction requirements, number of features, the need for customizing the style of features, and data sources.

Annotations

You can add annotations to the map including point, circle, polyline, and polygon shapes using the Mapbox Maps SDK’s Annotations API. Use the Annotations API to create annotation managers based on the type of annotation that you’re interested in. Every annotation manager handles a collection of annotations. Once a manager has been created, you can create and add individually styled instances of the corresponding annotation type.

Benefits:

  • Built-in interaction support like selecting and dragging annotations around the map.
  • No external data file necessary.
  • Every annotation can be individually styled.
  • Every annotation layer can be adjusted to be above or below another layer.
  • Same performance benefits as using style layers.

Limitations:

  • Inefficient for adding many features (> 250) to the map.
  • No default marker image available.

Default markers

The Mapbox Maps SDK’s Annotations API does not provide a default image for symbol layers. You must provide an image and add it to the style before using the PointAnnotationManager to add it to the map.

See the Add a marker to the map code example for a downloadable red marker image that you can use in your project and details on how to add the image to a map style at runtime. Once you have the image added to your project and to the map style, create a new Annotation API instance and get the PointAnnotationManager .

Use the Annotation API’s PointAnnotationManager to add a single red marker pin to a map.

Other shapes

The Annotation API also supports putting other shapes on the map including circles using CircleAnnotationManager , polylines using PolylineAnnotationManager , and polygons using PolygonAnnotationManager . These annotations work like the point annotations described above, but do not require an image. The options available for each type of annotation varies and you can find a full list in the API reference documentation.

A circle annotation ( CircleAnnotation ) places a circle at a point on the map.

A polyline annotation ( PolylineAnnotation ) connects a list of coordinates on the map with a polyline. The order of the coordinates in the list will determine the order in which to connect the points. Coordinate ordering works the same way as in the GeoJSON specification.

A polygon annotation ( PolygonAnnotation ) takes a list of coordinates and will try to connect those coordinates and add the resulting polygonal shape to the map. The order of the coordinates in the list matters and works the same way as in the GeoJSON specification.

Interactivity

The Annotation API includes the ability make annotations draggable and handles drag gestures for you. You can specify that annotations should be draggable when adding the annotation to the map initially.

Or, you can update an annotation that’s already been added to the map to be draggable.

Style layers

The Annotation API described above makes it unnecessary to write much of the code that would otherwise be required to implement runtime and data-driven styling. But, it is possible to add style layers directly, and in some circumstances doing so will be beneficial.

Benefits:

  • Efficient and performant when adding many features to the map.
  • Compatible with GeoJSON or vector sources.
  • Many style customization options.
  • Could exclude the Annotation API when installing the SDK to reduce the SDK size.

Limitations:

  • No default image available.
  • Most user interactions are not built-in and will require writing custom code.
  • Need to learn the APIs and usage of layers which can be time intensive.
  • Might need to learn how to use expressions to control the source data or use data-driven styling.

Use the Mapbox Maps SDK for Android to add, remove, and modify layers rendered in a map style.

Источник

Marker

An icon placed at a particular point on the map’s surface. A marker icon is drawn oriented against the device’s screen rather than the map’s surface; i.e., it will not necessarily change orientation due to map rotations, tilting, or zooming.

A marker has the following properties: Alpha Sets the opacity of the marker. Defaults to 1.0. Anchor The point on the image that will be placed at the LatLng position of the marker. This defaults to 50% from the left of the image and at the bottom of the image. Position The LatLng value for the marker’s position on the map. You can change this value at any time if you want to move the marker. Title A text string that’s displayed in an info window when the user taps the marker. You can change this value at any time. Snippet Additional text that’s displayed below the title. You can change this value at any time. Icon A bitmap that’s displayed for the marker. If the icon is left unset, a default icon is displayed. You can specify an alternative coloring of the default icon using defaultMarker(float) . Drag Status If you want to allow the user to drag the marker, set this property to true . You can change this value at any time. The default is false . Visibility By default, the marker is visible. To make the marker invisible, set this property to false . You can change this value at any time. Flat or Billboard If the marker is flat against the map, it will remain stuck to the map as the camera rotates and tilts but will still remain the same size as the camera zooms, unlike a GroundOverlay . If the marker is a billboard, it will always be drawn facing the camera and will rotate and tilt with the camera. The default is a billboard ( false ) Rotation The rotation of the marker in degrees clockwise about the marker’s anchor point. The axis of rotation is perpendicular to the marker. A rotation of 0 corresponds to the default position of the marker. When the marker is flat on the map, the default position is North aligned and the rotation is such that the marker always remains flat on the map. When the marker is a billboard, the default position is pointing up and the rotation is such that the marker is always facing the camera. The default value is 0. zIndex The draw order for the marker. The markers are drawn in order of the zIndex, with the highest zIndex marker drawn on top. By setting the zIndex property for each marker, you can control which tap target your user is most likely to hit. The default value is 0. Tag An Object associated with the marker. For example, the Object can contain data about what the marker represents. This is easier than storing a separate Map . As another example, you can associate a String ID corresponding to the ID from a data set. Google Maps SDK for Android neither reads nor writes this property.

Читайте также:  Как восстановить данные после переустановки андроид

Methods in this class must be called on the Android UI thread. If not, an IllegalStateException will be thrown at runtime.

Example

Developer Guide

For more information, read the Markers developer guide.

Источник

Add a map to your Android app (Kotlin)

1. Before You Begin

This codelab teaches you how to integrate Maps SDK for Android with your app and use its core features by building an app that displays a map of bicycle shops in San Francisco, CA, USA.

Prerequisites

  • Basic knowledge of Kotlin and Android development

What you’ll do

  • Enable and use the Maps SDK for Android to add Google Maps to an Android app.
  • Add, customize, and cluster markers.
  • Draw polylines and polygons on the map.
  • Control the viewpoint of the camera programmatically.

What you’ll need

  • Maps SDK for Android
  • A Google Account with billing enabled
  • Android Studio 2020.3.1 or higher
  • Google Play services installed in Android Studio
  • An Android device or an Android emulator that runs the Google APIs platform based on Android 4.2.2 or higher (see Run apps on the Android Emulator for installation steps.)

2. Get set up

For the following enablement step , you need to enable Maps SDK for Android.

Set up Google Maps Platform

If you do not already have a Google Cloud Platform account and a project with billing enabled, please see the Getting Started with Google Maps Platform guide to create a billing account and a project.

  1. In the Cloud Console, click the project drop-down menu and select the project that you want to use for this codelab.

  1. Enable the Google Maps Platform APIs and SDKs required for this codelab in the Google Cloud Marketplace. To do so, follow the steps in this video or this documentation.
  2. Generate an API key in the Credentials page of Cloud Console. You can follow the steps in this video or this documentation. All requests to Google Maps Platform require an API key.

3. Quick start

To get you started as quickly as possible, here’s some starter code to help you follow along with this codelab. You’re welcomed to jump to the solution, but if you want to follow along with all the steps to build it yourself, keep reading.

  1. Clone the repository if you have git installed.

Alternatively, you can click the following button to download the source code.

Give me the code

  1. Upon getting the code, go ahead and open the project found inside the starter directory in Android Studio.

4. Add Google Maps

In this section, you will add Google Maps so that it loads when you launch the app.

Add your API key

The API key that you created in an earlier step needs to be provided to the app so that Maps SDK for Android can associate your key with your app.

  1. To provide this, open the file called local.properties in the root directory of your project (the same level where gradle.properties and settings.gradle are).
  2. In that file, define a new key GOOGLE_MAPS_API_KEY with its value being the API key that you created.

local.properties

Notice that local.properties is listed in the .gitignore file in the Git repository. This is because your API key is considered sensitive information and should not be checked in to source control, if possible.

  1. Next, to expose your API so it can be used throughout your app, include the Secrets Gradle Plugin for Android plugin in your app’s build.gradle file located in the app/ directory and add the following line within the plugins block:

app-level build.gradle

You will also need to modify your project-level build.gradle file to include the following classpath:

project-level build.gradle

This plugin will make keys you have defined within your local.properties file available as build variables in the Android manifest file and as variables in the Gradle-generated BuildConfig class at build time. Using this plugin removes the boilerplate code that would otherwise be needed to read properties from local.properties so that it can be accessed throughout your app.

Note: API keys are sensitive credentials that should be carefully protected to avoid abuse. For more information about best practices for securing your API key, read Protecting API keys. For more Gradle tips, see Gradle tips and recipes.

Note: Make sure to update the correct build.gradle file. In your project, there should be two. One project-level build.gradle file and a module-specific one ( app/build.gradle ). The latter is the correct one to use.

Add Google Maps dependency

  1. Now that your API key can be accessed inside the app, the next step is to add the Maps SDK for Android dependency to your app’s build.gradle file.

In the starter project that comes with this codelab, this dependency has already been added for you.

build.gradle

  1. Next, add a new meta-data tag in AndroidManifest.xml to pass in the API key that you created in an earlier step. To do so, go ahead and open this file in Android Studio and add the following meta-data tag inside the application object in your AndroidManifest.xml file, located in app/src/main .

AndroidManifest.xml

Note: Notice that the injected build variable matches the same name as the variable you declared in your local.properties file earlier. Normally, you would have to modify your build.gradle file to inject build variables into your manifest file, but this is all handled by the Secrets Gradle Plugin for Android plugin.

  1. Next, create a new layout file called activity_main.xml in the app/src/main/res/layout/ directory and define it as follows:

activity_main.xml

This layout has a single FrameLayout containing a SupportMapFragment . This fragment contains the underlying GoogleMaps object that you use in later steps.

  1. Lastly, update the MainActivity class located in app/src/main/java/com/google/codelabs/buildyourfirstmap by adding the following code to override the onCreate method so you can set its contents with the new layout you just created.

MainActivity

  1. Now go ahead and run the app. You should now see the map load on your device’s screen.

5. Add markers

In this task, you add markers to the map that represent points of interest that you want to highlight on the map. First, you retrieve a list of places that have been provided in the starter project for you, then add those places to the map. In this example, these are bicycle shops.

Get a reference to GoogleMap

First, you need to obtain a reference to the GoogleMap object so that you can use its methods. To do that, add the following code in your MainActivity.onCreate() method right after the call to setContentView() :

MainActivity.onCreate()

The implementation first finds the SupportMapFragment that you added in the previous step by using the findFragmentById() method on the SupportFragmentManager object. Once a reference has been obtained, the getMapAsync() call is invoked followed by passing in a lambda. This lambda is where the GoogleMap object is passed. Inside this lambda, the addMarkers() method call is invoked, which is defined shortly.

Note: As you copy and paste code from this codelab to your project, expect to see Unresolved reference errors. To fix these, you need to import the class in to your file. You can do this automatically in Android Studio by hovering on the class that displays an error and clicking Import in the helper dialog.

Provided class: PlacesReader

In the starter project, the class PlacesReader has been provided for you. This class reads a list of 49 places that are stored in a JSON file called places.json and returns these as a List

. The places themselves represent a list of bicycle shops around San Francisco, CA, USA.

If you are curious about the implementation of this class, you can access it on GitHub or open the PlacesReader class in Android Studio.

PlacesReader

Load places

To load the list of bicycle shops, add a property in MainActivity called places and define it as follows:

Читайте также:  Слайд шоу рабочий стол андроид

MainActivity.places

Note: This property is declared as lazy so that reading all the places from the file is performed only when needed—right after the GoogleMap object is initialized. For more information about lazy properties, see Lazy.

This code invokes the read() method on a PlacesReader , which returns a List

. A Place has a property called name , the name of the place, and a latLng —the coordinates where the place is located.

Place

Add markers to map

Now that the list of places have been loaded to memory, the next step is to represent these places on the map.

  1. Create a method in MainActivity called addMarkers() and define it as follows:

MainActivity.addMarkers()

This method iterates through the list of places followed by invoking the addMarker() method on the provided GoogleMap object. The marker is created by instantiating a MarkerOptions object, which allows you to customize the marker itself. In this case, the title and position of the marker is provided, which represents the bicycle shop name and its coordinates, respectively.

  1. Go ahead and run the app, and head over to San Francisco to see the markers that you just added!

6. Customize markers

There are several customization options for markers you have just added to help them stand out and convey useful information to users. In this task, you’ll explore some of those by customizing the image of each marker as well as the information window displayed when a marker is tapped.

Adding an info window

By default, the info window when you tap on a marker displays its title and snippet (if set). You customize this so that it can display additional information, such as the place’s address and rating.

Create marker_info_contents.xml

First, create a new layout file called marker_info_contents.xml .

  1. To do so, right click on the app/src/main/res/layout folder in the project view in Android Studio and select New >Layout Resource File.

  1. In the dialog, type marker_info_contents in the File name field and LinearLayout in the Root element field, then click OK.

This layout file is later inflated to represent the contents within the info window.

  1. Copy the contents in the following code snippet, which adds three TextViews within a vertical LinearLayout view group, and overwrite the default code in the file.

marker_info_contents.xml

Create an implementation of an InfoWindowAdapter

After creating the layout file for the custom info window, the next step is to implement the GoogleMap.InfoWindowAdapter interface. This interface contains two methods, getInfoWindow() and getInfoContents() . Both methods return an optional View object wherein the former is used to customize the window itself, while the latter is to customize its contents. In your case, you implement both and customize the return of getInfoContents() while returning null in getInfoWindow() , which indicates that the default window should be used.

  1. Create a new Kotlin file called MarkerInfoWindowAdapter in the same package as MainActivity by right-clicking the app/src/main/java/com/google/codelabs/buildyourfirstmap folder in the project view in Android Studio, then select New >Kotlin File/Class.

  1. In the dialog, type MarkerInfoWindowAdapter and keep File highlighted.

  1. Once you have the file created, copy the contents in the following code snippet in to your new file.

MarkerInfoWindowAdapter

In the contents of the getInfoContents() method, the provided Marker in the method is casted to a Place type, and if casting is not possible, the method returns null (you haven’t set the tag property on the Marker yet, but you do that in the next step).

Next, the layout marker_info_contents.xml is inflated followed by setting the text on containing TextViews to the Place tag.

Update MainActivity

To glue all the components you have created so far, you need to add two lines in your MainActivity class.

First, to pass the custom InfoWindowAdapter , MarkerInfoWindowAdapter , inside the getMapAsync method call, invoke the setInfoWindowAdapter() method on the GoogleMap object and create a new instance of MarkerInfoWindowAdapter .

  1. Do this by adding the following code after the addMarkers() method call inside the getMapAsync() lambda.

MainActivity.onCreate()

Lastly, you’ll need to set each Place as the tag property on every Marker that’s added to the map.

  1. To do that, modify the places.forEach<> call in the addMarkers() function with the following:

MainActivity.addMarkers()

Add a custom marker image

Customizing the marker image is one of the fun ways to communicate the type of place the marker represents on your map. For this step, you display bicycles instead of the default red markers to represent each shop on the map. The starter project includes the bicycle icon ic_directions_bike_black_24dp.xml in app/src/res/drawable , which you use.

Set custom bitmap on marker

With the vector drawable bicycle icon at your disposal, the next step is to set that drawable as each markers’ icon on the map. MarkerOptions has a method icon , which takes in a BitmapDescriptor that you use to accomplish this.

First, you need to convert the vector drawable you just added into a BitmapDescriptor . A file called BitMapHelper included in the starter project contains a helper function called vectorToBitmap() , which does just that.

BitmapHelper

This method takes in a Context , a drawable resource ID, as well as a color integer, and creates a BitmapDescriptor representation of it.

Note: vectorToBitmap was taken from the Maps SDK for Android samples. For more information, see it on GitHub.

Using the helper method, declare a new property called bicycleIcon and give it the following definition: MainActivity.bicycleIcon

This property uses the predefined color colorPrimary in your app, and uses that to tint the bicycle icon and return it as a BitmapDescriptor .

  1. Using this property, go ahead and invoke the icon method of MarkerOptions in the addMarkers() method to complete your icon customization. Doing this, the marker property should look like this:

MainActivity.addMarkers()

  1. Run the app to see the updated markers!

Note: For more information about what you can customize on markers, see Markers.

7. Cluster markers

Depending on how far you zoom into the map, you may have noticed that the markers you added overlap. Overlapping markers are very hard to interact with and create a lot of noise, which affects the usability of your app.

To improve the user experience for this, whenever you have a large dataset that is clustered closely, it’s best practice to implement marker clustering. With clustering, as you zoom in and out of the map, markers that are in close proximity are clustered together like this:

To implement this, you need the help of the Maps SDK for Android Utility Library.

Maps SDK for Android Utility Library

The Maps SDK for Android Utility Library was created as a way to extend the functionality of the Maps SDK for Android. It offers advanced features, such as marker clustering, heatmaps, KML and GeoJson support, polyline encoding anddecoding, and a handful of helper functions around spherical geometry.

Note: One of the best parts about the Maps SDK for Android Utility Library is that it is open sourced on GitHub. This library is continually evolving, so if you have any suggestions or ideas, feel free to stop by and contribute!

Update your build.gradle

Because the utility library is packaged separately from Maps SDK for Android, you need to add an additional dependency to your build.gradle file.

  1. Go ahead and update the dependencies section of your app/build.gradle file.

build.gradle

  1. Upon adding this line, you have to perform a project sync to fetch the new dependencies.

Implement clustering

To implement clustering on your app, follow these three steps:

  1. Implement the ClusterItem interface.
  2. Subclass the DefaultClusterRenderer class.
  3. Create a ClusterManager and add items.

Implement the ClusterItem interface

All objects that represent a clusterable marker on the map need to implement the ClusterItem interface. In your case, that means that the Place model needs to conform to ClusterItem . Go ahead and open the Place.kt file and make the following modifications to it:

Place

The ClusterItem defines these three methods:

  • getPosition() , which represents the place’s LatLng .
  • getTitle() , which represents the place’s name
  • getSnippet() , which represents the place’s address.

Subclass the DefaultClusterRenderer class

The class in charge of implementing clustering, ClusterManager , internally uses a ClusterRenderer class to handle creating the clusters as you pan and zoom around the map. By default, it comes with the default renderer, DefaultClusterRenderer , which implements ClusterRenderer . For simple cases, this should suffice. In your case, however, because markers need to be customized, you need to extend this class and add the customizations in there.

Go ahead and create the Kotlin file PlaceRenderer.kt in the package com.google.codelabs.buildyourfirstmap.place and define it as follows:

PlaceRenderer

This class overrides these two functions:

  • onBeforeClusterItemRendered() , which is called before the cluster is rendered on the map. Here, you can provide customizations through MarkerOptions —in this case, it sets the marker’s title, position, and icon.
  • onClusterItemRenderer() , which is called right after the marker is rendered on the map. This is where you can access the created Marker object—in this case, it sets the marker’s tag property.

Create a ClusterManager and add items

Lastly, to get clustering working, you need to modify MainActivity to instantiate a ClusterManager and provide the necessary dependencies to it. ClusterManager handles adding the markers (the ClusterItem objects) internally, so instead of adding markers directly on the map, this responsibility is delegated to ClusterManager . Additionally, ClusterManager also calls setInfoWindowAdapter() internally so setting a custom info window will have to be done on ClusterManger ‘s MarkerManager.Collection object.

  1. To start, modify the contents of the lambda in the getMapAsync() call in MainActivity.onCreate() . Go ahead and comment out the call to addMarkers() and setInfoWindowAdapter() , and instead invoke a method called addClusteredMarkers() , which you define next.
Читайте также:  Увеличение памяти для андроида без рут прав

MainActivity.onCreate()

  1. Next, in MainActivity , define addClusteredMarkers() .

MainActivity.addClusteredMarkers()

This method instantiates a ClusterManager , passes the custom renderer PlacesRenderer to it, adds all the places, and invokes the cluster() method. Also, since ClusterManager uses the setInfoWindowAdapter() method on the map object, setting the custom info window will have to be done on ClusterManager.markerCollection object. Lastly, because you want clustering to change as the user pans and zooms around the map, an OnCameraIdleListener is provided to googleMap , such that when the camera goes idle, clusterManager.onCameraIdle() is invoked.

  1. Go ahead and run the app to see the new clustered shops!

8. Draw on the map

While you have already explored one way to draw on the map (by adding markers), the Maps SDK for Android supports numerous other ways you can draw to display useful information on the map.

For example, if you wanted to represent routes and areas on the map, you can use polylines and polygons to display these on the map. Or, if you wanted to fix an image to the ground’s surface, you can use ground overlays.

In this task, you learn how to draw shapes, specifically a circle, around a marker whenever it is tapped.

Add click listener

Typically, the way you would add a click listener to a marker is by passing in a click listener directly on the GoogleMap object via setOnMarkerClickListener() . However, because you’re using clustering, the click listener needs to be provided to ClusterManager instead.

  1. In the addClusteredMarkers() method in MainActivity , go ahead and add the following line right after the invocation to cluster() .

MainActivity.addClusteredMarkers()

This method adds a listener and invokes the method addCircle() , which you define next. Lastly, false is returned from this method to indicate that this method has not consumed this event.

Note: It’s important to return false from setOnClusterItemClickListener() so that your custom info window is still displayed.

  1. Next, you need to define the property circle and the method addCircle() in MainActivity .

MainActivity.addCircle()

The circle property is set so that whenever a new marker is tapped, the previous circle is removed and a new one is added. Notice that the API for adding a circle is quite similar to adding a marker.

  1. Go ahead now and run the app to see the changes.

Note: The nomenclature GoogleMap.add is a common way to draw on the map. If you’re curious, you can explore all the different ways you can add functionality to the map by typing in .add on a GoogleMap object in Android Studio. This autocompletes all the different methods supported.

9. Camera Control

As your last task, you look at some camera controls so that you can focus the view around a certain region.

Camera and view

If you noticed when you run the app, the camera displays the continent of Africa, and you have to painstakingly pan and zoom to San Francisco to find the markers you added. While it can be a fun way to explore the world, it’s not useful if you want to display the markers right away.

To help with that, you can set the camera’s position programmatically so that the view is centered where you want it.

  1. Go ahead and add the following code to the getMapAsync() call to adjust the camera view so that it is initialized to San Francisco when the app is launched.

MainActivity.onCreate()

First, the setOnMapLoadedCallback() is called so that the camera update is only performed after the map is loaded. This step is necessary because the map properties, such as dimensions, need to be computed before making a camera update call.

In the lambda, a new LatLngBounds object is constructed, which defines a rectangular region on the map. This is incrementally built by including all the place LatLng values in it to ensure all places are inside the bounds. Once this object has been built, the moveCamera() method on GoogleMap is invoked and a CameraUpdate is provided to it through CameraUpdateFactory.newLatLngBounds(bounds.build(), 20) .

  1. Run the app and notice that the camera is now initialized in San Francisco.

Listening to camera changes

In addition to modifying the camera position, you can also listen to camera updates as the user moves around the map. This could be useful if you wanted to modify the UI as the camera moves around.

Just for fun, you modify the code to make the markers translucent whenever the camera is moved.

  1. In the addClusteredMarkers() method, go ahead and add the following lines toward the bottom of the method:

MainActivity.addClusteredMarkers()

This adds an OnCameraMoveStartedListener so that, whenever the camera starts moving, all the markers’ (both clusters and markers) alpha values are modified to 0.3f so that the markers appear translucent.

  1. Lastly, to modify the translucent markers back to opaque when the camera stops, modify the contents of the setOnCameraIdleListener in the addClusteredMarkers() method to the following:

MainActivity.addClusteredMarkers()

  1. Go ahead and run the app to see the results!

10. Maps KTX

For Kotlin apps using one or more Google Maps Platform Android SDKs, Kotlin extension or KTX libraries are available to enable you to take advantage of Kotlin language features such as coroutines, extension properties/functions, and more. Each Google Maps SDK has a corresponding KTX library as shown below:

In this task, you will use the Maps KTX and Maps Utils KTX libraries to your app and refactor previous tasks’ implementations so that you can use Kotlin-specific language features in your app.

Note: The Google Maps Platform KTX libraries are all open sourced on GitHub. See android-maps-ktx and android-places-ktx to learn more.

  1. Include KTX dependencies in your app-level build.gradle file

Since the app uses both the Maps SDK for Android and the Maps SDK for Android Utility Library, you will need to include the corresponding KTX libraries for these libraries. You will also be using a feature found in the AndroidX Lifecycle KTX library in this task so include that dependency as well in your app-level build.gradle file as well.

build.gradle

  1. Use GoogleMap.addMarker() and GoogleMap.addCircle() extension functions

The Maps KTX library provides a DSL-style API alternative for the GoogleMap.addMarker(MarkerOptions) and GoogleMap.addCircle(CircleOptions) used in previous steps. To use the aforementioned APIs, construction of a class containing options for a marker or circle is necessary whereas with the KTX alternatives you are able to set the marker or circle options in the lambda you provide.

To use these APIs, update the MainActivity.addMarkers(GoogleMap) and MainActivity.addCircle(GoogleMap) methods:

MainActivity.addMarkers(GoogleMap)

MainActivity.addCircle(GoogleMap)

Rewriting the above methods in this way is a lot more concise to read which is made possible using Kotlin’s function literal with receiver.

Note: other DSL-style methods are also available for adding other shapes to the map—polygons, polylines, and so on. Refer to the android-maps-ktx reference documents to learn more.

  1. Use SupportMapFragment.awaitMap() and GoogleMap.awaitMapLoad() extension suspending functions

The Maps KTX library also provides suspending function extensions to be used within coroutines. Specifically, there are suspending function alternatives for SupportMapFragment.getMapAsync(OnMapReadyCallback) and GoogleMap.setOnMapLoadedCallback(OnMapLoadedCallback) . Using these alternative APIs removes the need for passing callbacks and instead allows you to receive the response of these methods in a serial and synchronous way.

Since these methods are suspending functions, their usage will need to occur within a coroutine. The Lifecycle Runtime KTX library offers an extension to provide lifecycle-aware coroutine scopes so that coroutines are run and stopped at the appropriate lifecycle event.

Combining these concepts, update the MainActivity.onCreate(Bundle) method:

MainActivity.onCreate(Bundle)

The lifecycleScope.launchWhenCreated coroutine scope will execute the block when the activity is at least in the created state. Also notice that the calls to retrieve the GoogleMap object, and to wait for the map to finish loading, have been replaced with SupportMapFragment.awaitMap() and GoogleMap.awaitMapLoad() , respectively. Refactoring code using these suspending functions enable you to write the equivalent callback-based code in a sequential manner.

  1. Go ahead and re-build the app with your refactored changes!

11. Congratulations

Congratulations! You covered a lot of content and hopefully you have a better understanding of the core features offered in the Maps SDK for Android.

Learn more

  • Places SDK for Android—explore the rich set of places data to discover businesses around you.
  • android-maps-ktx—an open source library allowing you to integrate with Maps SDK for Android and the Maps SDK for Android Utility Library in a Kotlin-friendly way.
  • android-place-ktx—an open source library allowing you to integrate with Places SDK for Android in a Kotlin-friendly way.
  • android-samples—sample code on GitHub demonstrating all the features covered in this codelab and more.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Оцените статью