Development of mobile applications often requires the use of geolocation to build routes, display points of interest, or track users. Integrating map services into Android Studio is a standard, but demanding task that opens up enormous opportunities for the functionality of your product. In the process of work, you will have to choose between several providers, configure access and correctly implement fragments into the interface.
There are two main directions: using native Google Maps or services popular in the CIS Yandex Maps. Each of them has its own connection features, license agreements and developer tool kits. The choice of a specific solution depends on the target audience of your application and the requirements for detailing the area in a particular region.
In this article we will analyze in detail the entire connection cycle: from obtaining access keys in the personal accounts of developers to writing code on Kotlin or Java. We will look at common mistakes, ways to optimize performance and the nuances of displaying the interface on different smartphone screens.
Selecting a map service and obtaining keys
The first step is to register in the developer console of the selected service. For Google Maps Platform You will need a Google Cloud account and a linked payment card, even if you plan to use the free limit. Without this step, generation API Key will be impossible, since the system requires identity confirmation.
In the case of Yandex MapKit the procedure is slightly different: you need to register in the Yandex developer account and create a new application. Here it is important to immediately indicate the package name of your project, since the key will be strictly tied to it and will not work on other domains or in other applications without re-release.
โ ๏ธ Attention: Never upload files with private keys to public repositories on GitHub. Attackers can steal your key and exhaust your request limit, which will lead to service blocking or financial losses.
After registration, you will receive an access string that you will need to save. For Google Maps, you will also need to create an SHA-1 fingerprint of the debug key and release key. This is done through the command line using the utility keytoolincluded JDK.
The differences in approaches to monetization are also significant. Google provides a monthly credit that covers a significant volume of queries for small projects. Yandex offers a free plan with restrictions on the number of users per day, after exceeding which a paid package is required.
Setting up a project and configuration files
Integration begins with modification of the project assembly files. In the root file build.gradle (Project Level), you need to make sure that the Google repository is available to download dependencies. Usually it is already present by default in new projects created through the Android Studio wizard.
Next we move on to the modular file build.gradle (App Level). Here you need to add a dependency for working with maps. For Google this is a library play-services-maps, and for Yandex - mapkit. You should select the latest versions of libraries, checking the documentation for critical security updates.
dependencies {implementation 'com.google.android.gms:play-services-maps:18.2.0'
implementation 'com.yandex.android:maps.mobile:4.4.1-full'
}
Don't forget to add permissions to the manifest file AndroidManifest.xml. The basic set includes access to the Internet and geolocation. Additional permission flags may be required for maps to work correctly in the background or when the application is minimized.
โ๏ธ Checking the project configuration
Also in the manifest you need to register meta-data with your API key. For Google, this is done through a tag meta-data inside the section application, where the name is indicated com.google.android.geo.API_KEY. An error in one letter of the tag name will result in the map simply not loading, showing a gray screen.
Implementation of the interface using fragments
The map is displayed in modern Android mainly through Fragment. This allows you to flexibly manage the life cycle of a component and easily embed the map in various parts of the interface, for example, in the bottom navigation bar or as a separate screen.
In the markup file activity_main.xml you add a container for the fragment. For Google Maps, a special tag SupportMapFragmentis used, which automatically initializes the necessary components when the view is loaded. For Yandex, a standard one is used FrameLayout with an ID, into which a map fragment is programmatically loaded.
| Component | Google Maps | Yandex MapKit | Purpose |
|---|---|---|---|
| Fragment | SupportMapFragment |
MapFragment |
Container for rendering |
| Map object | GoogleMap |
Map |
State management |
| Marker | Marker |
Placemark |
Point on map |
| Camera | CameraUpdate |
CameraPosition |
Position and zoom |
In the activity or fragment code, you must implement a callback interface OnMapReadyCallback. The method onMapReady works only after the card is fully loaded and ready for interaction. Attempting to change camera settings before this point will throw an exception.
It is important to consider the application lifecycle. The onResume and onPause parent activity methods must be correctly passed to the map fragment. This is necessary to stop rendering when the application is minimized, which saves device battery power and prevents memory leaks.
Why might the map be empty?
If you see a gray screen instead of a map, check three things: 1. The API key in Manifest is correct. 2. Availability of an Internet connection on the emulator or device. 3. Match the SHA-1 fingerprint of the debug key with the one specified in the developer console.
Working with markers and custom elements
Adding points of interest is one of the most common tasks. Markers allow the user to visually navigate the area. You can use standard icons provided by the SDK, or upload your own images in the format BitmapDescriptor.
To create a marker, you must specify its geographic coordinates (latitude and longitude). Additionally, you can customize the title, snippet (short description) and click behavior. When you click on a marker, an information window with object details often opens.
- ๐ Standard markers โred pin by default, the color can be easily adjusted via SDK methods.
- ๐จ Custom icons โallow you to load any PNG resource from your folder
drawableproject. - ๐ Clustering - combining close markers into one group when the camera is too far away to improve performance.
If there are a large number of objects on the screen (more than 100-200), directly adding markers can lead to a drop in FPS and interface slowdowns. In such cases, it is recommended to use the clustering technique, when many points are combined into one aggregated marker with a figure for the number of objects inside.
For Yandex Maps, clustering is built into the main SDK and is enabled by one setting of the cluster manager, while for Google Maps you often need to connect a separate utility library or write your own logic.You can also add polylines for constructing routes and polygons to highlight areas. These elements are drawn on top of the map and respond to user gestures. Adjustment of line thickness and fill color is carried out through the corresponding builder objects.
Use vector drawable resources for marker icons instead of high-resolution raster images. This will significantly reduce the size of the APK file and speed up rendering on devices with low pixel density.
Camera settings and user interaction
The map view is controlled through the camera object. You can programmatically move the focus to a specific point, change the tilt angle and rotation. This is useful, for example, when the user is searching for an address or when starting an application to show the current location.
Camera movement can be smooth or instantaneous. To create a pleasant user experience, it is recommended to use a movement animation lasting 1-2 seconds. Sudden changes in the map can disorient the user and cause unpleasant sensations.
You can limit the map's visibility area by setting boundaries. This is relevant for delivery or taxi applications that operate only within a specific city. The user's attempt to move outside the specified area will be blocked or the camera will return back.
โ ๏ธ Attention: Map APIs have limits on the frequency of requests. Don't call the camera to move in a loop or in a method that fires too often (for example, every time GPS coordinates change without filtering). This may result in your key being temporarily blocked.
Gesture settings are also available. You can disable the ability to rotate, tilt, or zoom the map with your fingers if this conflicts with the logic of your application. However, completely disabling interaction usually degrades usability.
Smooth camera animation and limited viewing area improve the experience of the application, but require careful adjustment of motion parameters to avoid conflicts with user gestures.
Location determination and working with GPS
Displaying the user's current position is a key function of navigation applications. To do this, the Android geolocation service is used, which provides coordinates with varying precision depending on the available signal sources (GPS, Wi-Fi, cell towers).
Starting with Android 6.0, it is necessary to request permissions to access the geolocation while the application is running (runtime permissions). Simply specifying the permission in the manifest is not enough - you need to show the system dialog box and process the user's response.
- ๐ก Fine Location โ exact location via GPS, requires the user's explicit consent.
- ๐ถ Coarse Location โ approximate location via towers and Wi-Fi, less accurate, but faster.
- ๐ Energy consumption โ constant GPS polling quickly drains the battery, use balancing update intervals.
The received coordinates must be converted into a map position object and passed to the camera update method. It is important to consider that the GPS signal may disappear in rooms or tunnels, so the interface must correctly display the โsearch for satellitesโ state or show the last known location.
To display the โMy Locationโ button in the map interface, you can use the built-in controls (UI settings) or create your own button on top of the fragment. When pressed, this button should initiate a request for current coordinates and center the map.
What to do if GPS is not turned on?
Use the LocationSettingsRequest class to check device settings. If GPS is turned off, you can show the user a system dialog box asking you to enable geolocation without leaving the application.
Frequently asked questions about map integration
Why is the map displayed with a gray background instead of an image?
Most often the problem lies in an invalid API key. Check if the SHA-1 fingerprint of your debug key matches what you entered in the developer console. Also make sure that Google Play services are installed on the emulator if you use Google Maps.
How to change the language of labels on the map?
The map language is usually inherited from the system settings of the device. For Google Maps, you can force the locale through the map settings by passing an object Locale. Yandex Maps also allows you to switch the language programmatically through the settings of the map instance.
Can maps be used offline?
Standard Google and Yandex SDKs do not support full offline work without additional preparation. Google allows you to download areas through the Google Maps app, but access to them from a third-party APK is limited. For offline mode, engines based on OSM (OpenStreetMap), such as OSMDroid, are often used.
How to remove the map provider logo?
Removing the logo (Google or Yandex) is prohibited by the license agreement. You can change its position in the corner of the screen, but you cannot completely hide the attribution. Violating this rule may result in your developer account being blocked.
Why does the application crash when the screen is rotated?
When the screen is rotated, the activity is recreated, which leads to the map fragment being reinitialized. If you don't save state or don't handle the lifecycle correctly, a duplicate fragment error may occur. Use retainInstance or ViewModel to save state.