Android Maps SDK Quickstart
This is the Android Maps SDK Quickstart guide aimed to assist you in integrating maps into your Android applications. With the help of this guide, you'll be able to understand the basics of the Android Maps SDK and how to effectively use it to create rich, location-based experiences for your users. Whether you're already an experienced Android developer or just starting out, this guide will provide a step-by-step approach to get you up and running with the Android Maps SDK. Let's dive in!
Prerequisites
-
Access Key: if you don’t have your Access Key yet, don’t hesitate to contact us
-
IDE (Android Studio): to build and develop the Android application
- There are no restrictions on IDE version, but we recommend developers to use Arctic Fox | 2020.3.1 and above
Installation
The guide explains how to install the SDK by adding the necessary dependencies to your project. It provides instructions on adding the maven dependencies of SDK to your app's build.gradle file.
Maven dependencies
In your app-level build.gradle file, add the Nextbillion.ai dependency for the Maps SDK for Android.
1dependencies {
2 def version = "0.0.1"
3 implementation 'ai.nextbillion:nb-maps-android:$version'
4}
This line of code tells Gradle to download the Nextbillion Android Maps SDK version 0.0.1 from the Maven Central repository and include it in the build process for your app, making the functionality provided by the SDK available to your app at runtime. The use of the variable ‘version’ allows easy updating of the SDK version, by changing just one line of code.
Note: Since the Gradle file has been edited. Android Studio will ask you whether to sync the files or not. Select Yes, and sync the Gradle files for successful installation of Android Maps SDK.
Initialisation
Before we start using any functionalities from both SDKs, we need to initialize the Maps SDK first, by initializing it means to pass your Access Key to the singleton method of the class Nextbillion. A common way to initialize the SDK is to put the following code in an Application’s onCreate() callback, otherwise, please make sure you have called the code below before you start using any functionalities of the SDK.
1Nextbillion.getInstance(getApplicationContext(), "your access key");
Access Key
The maps SDK doesn’t enforce users to configure the access key in any strict manner, users can maintain and store their key in the below ways:
-
Local file(xml, Sharedpreference, or file)
-
Database
-
Cloud/Backend server
-
More
For example, configure the key in XML,
1<string name="nbmap_access_key">your-access-key</string>
and then pass the value to
1Nextbillion.getInstance(getApplicationContext(), "your access key");
Base Uri
By default the Maps SDK will try to read the XML strings resource to see if users have set the desired base Uri to “nbmap_base_uri”, and all instances of MapView will use this base Uri to request style and tiles.
1<string name="nbmap_base_uri">http://api.nextbillion.io</string>
If we want to override the base Uri for a particular MapView, there are two ways:
- Set nbmap_baseUri in layout XML file
1 <ai.nextbillion.maps.core.MapView 2android:id="@+id/mapView" 3android:layout_width="match_parent" 4android:layout_height="match_parent" 5app:nbmap_basrUri="https://api.nextbillion.io" />
- Set apiBaseUri in NextbillionMapOptions
1NextbillionMapOptions options = NextbillionMapOptions.createFromAttributes(this, null) 2.apiBaseUri("https://api.nextbillion.io"); 3mapView = new MapView(this, options);
MapView
MapView is a crucial component of the Android Maps SDK that allows developers to display maps in their Android applications. With MapView, developers can create engaging and interactive location-based experiences for their users. This custom view provides a powerful set of features, including map styling, markers, camera animations, and user interactions such as touch and zoom. Whether you're building a mapping app, location-based service, or simply need to display maps in your application, MapView is the key to making it happen. The Android Maps SDK provides an easy-to-use and flexible API that makes it simple to integrate MapView into your app and start creating amazing maps experiences.
Integration of MapView
There are two ways to integrate a MapView to your App
- Add MapView to your layout XML
1<ai.nextbillion.maps.core.MapView
2 android:id="@+id/map_view"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent" />
1<ai.nextbillion.maps.core.MapView
2 android:id="@+id/map_view"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 app:nbmap_cameraTargetLat="40.38532445"
6 app:nbmap_cameraTargetLng="-82.91441935"
7 app:nbmap_cameraZoom="10" />
This code creates a ‘MapView’ object with an ID of "map_view" and sets its width and height to match the parent view. In the second code snippet, additional attributes such as nbmap_cameraTargetLat, nbmap_cameraTargetLng, and nbmap_cameraZoom are added to set the initial camera position and zoom level for the ‘MapView’.
-
Instantiate a MapView and then add it to a parent view
1 mapView = new MapView(context); 2 3 4 parentView.addView(mapView); 5 //or 6 setContentView(mapView);
This code creates a new instance of ‘MapView’ by calling the constructor with a context object. The ‘MapView’ is then added to a parent view either by calling ‘parentView.addView(mapView)’ or ‘setContentView(mapView)’. The choice of which method to use depends on the specific use case and the desired parent view.
Obtain maps interface
NextbillionMap is the interface of the MapView, which allows developers to make changes to the MapView, for example, add a marker to the MapView. To get an instance of the NextbillionMap, we need to register an OnMapReadyCallback to the MapView as soon as we get the reference to it. There are two ways to register the callback:
- Implementing the OnMapReadyCallback interface within the class that requires the NextbillionMap instance.
1 public class YourClass implements OnMapReadyCallback
2 private NextbillionMap nextbillionMap;
3 mapView.getMapAsync(this);
4
5 @Override
6
7 public void onMapReady(@NonNull NextbillionMap nextbillionMap) {
8 this.nextbillionMap = nextbillionMap;
9 }
- Defining an anonymous OnMapReadyCallback class.
1private OnMapReadyCallback onMapReadyCallback = new OnMapReadyCallback() { 2 @Override 3 public void onMapReady(@NonNull NextbillionMap nextbillionMap) { 4 this.nextbillionMap = nextbillionMap; 5 } 6}; 7 8 9mapView.getMapAsync(onMapReadyCallback);
Once the map is ready, the onMapReady method will be triggered and the nextbillionMap instance variable will be set to the NextbillionMap that is passed as an argument to the method. Now, the code can make changes to the MapView using the nextbillionMap instance.
Lifecycle of MapView
Also, to avoid unexpected behaviors, don’t forget to bind MapView’s lifecycle to Activity
1 @Override
2 protected void onCreate(Bundle savedInstanceState) {
3 super.onCreate(savedInstanceState);
4 setContentView(R.layout.activity_main);
5
6 mapView = findViewById(R.id.map_view);
7 mapView.onCreate(savedInstanceState);
8 mapView.getMapAsync(this);
9 }
10
11 ///////////////////////////////////////////////////////////////////////////
12 /// Lifecycle
13 ////////////////////////////////////////////////////////////////////////
14
15 @Override
16 protected void onStart() {
17 super.onStart();
18 mapView.onStart();
19 }
20
21 @Override
22 protected void onResume() {
23 super.onResume();
24 mapView.onResume();
25 }
26
27 @Override
28 protected void onPause() {
29 super.onPause();
30 mapView.onPause();
31 }
32
33 @Override
34 protected void onStop() {
35 super.onStop();
36 mapView.onStop();
37 }
38
39 @Override
40 protected void onSaveInstanceState(@NonNull Bundle outState) {
41 super.onSaveInstanceState(outState);
42 mapView.onSaveInstanceState(outState);
43 }
44
45 @Override
46 protected void onDestroy() {
47 super.onDestroy();
48 mapView.onDestroy();
49 }
50
51 @Override
52 public void onLowMemory() {
53 super.onLowMemory();
54 mapView.onLowMemory();
55 }
The MapView's lifecycle should be bound to the activity's lifecycle by calling corresponding lifecycle methods of the MapView in each activity method, such as onCreate, onStart, onResume, onPause, onStop, onSaveInstanceState, onDestroy, and onLowMemory. In the onCreate method, the MapView is initialized with mapView.onCreate and loaded with mapView.getMapAsync. If you're using a fragment, call mapView.onDestroy() inside the fragment's onDestroyView().
Annotations
For more details of annotations, please refer to Android Maps SDK annotations
Add a marker
The addMarker method takes an instance of the LatLng class as an argument, which represents the coordinates(latitude and longitude) of the marker. In this example, the marker is placed at the coordinate 12.97551913, 77.58917229. This line of code will add a marker to the map at that location, allowing the user to visualize and interact with the location in the map view.
1nextbillionMap.addMarker(new LatLng(12.97551913,77.58917229));
Add a polyline
The addPolyline method takes three arguments: origin, dest, and a color value represented in an ARGB int. The origin and dest parameters represent the starting and ending points of the polyline. The color value determines the color of the polyline. In this example, the polyline is drawn from origin to dest and is set to the color with an ARGB value of 0xff00ffff, which represents a shade of cyan. This line of code will add a polyline to the map that connects the two points, allowing the user to visualize a path or route between them.
1nextbillionMap.addPolyline(origin, dest, 0xff00ffff);
Add a polygon
The addPolygon method takes two arguments: a list of points and a color value represented in an ARGB int. The points parameter represents the vertices of the polygon. The color value determines the color of the polygon. In this example, the polygon is defined by the vertices in points and is set to the color with an ARGB value of 0xffff0000, which represents the color red. This line of code will add a polygon to the map, allowing the user to visualize and interact with a region defined by the vertices.
1 nextbillionMap.addPolygon(points, 0xffff0000);
Camera
The Android Maps SDK provides a camera component that allows developers to control the view of the map. The camera component can be used to manipulate the position, orientation, and zoom level of the map view. With the camera, developers can provide a customized map experience for their users, for example, by zooming in on specific locations or tilting the view to show a particular perspective. The camera component is essential in creating dynamic and interactive map-based applications with the Nextbillion Android Maps SDK.
Get current Camera Position
The code snippet demonstrates how to retrieve the current camera position from a NextbillionMap object.
1 CameraPosition currentCameraPosition = nextbillionMap.getCameraPosition();
2 double currentZoom = currentCameraPosition.zoom;
3 double currentTilt = currentCameraPosition.tilt;
The getCameraPosition method of the NextbillionMap object is used to retrieve the current camera position, which is represented by a CameraPosition object. This CameraPosition object contains several properties, including the zoom level and the tilt angle of the camera. In this example, two variables are defined: currentZoom and currentTilt. These variables are set to the zoom and tilt properties of the CameraPosition object, respectively. This code will allow a developer to retrieve the current camera position and use it in further operations, such as adjusting the camera position or performing calculations based on the current camera position.
Update Camera Position
The code snippet demonstrates how to update the camera position in the NextbillionMap object.
1int millisecondSpeed = 300;
2CameraPosition position = new CameraPosition.Builder()
3 .target(new LatLng(12.97551913,77.58917229))
4 .zoom(12)
5 .tilt(20)
6 .build();
7nextbillionMap.animateCamera(CameraUpdateFactory.newCameraPosition(position), millisecondSpeed);
The animateCamera method of the NextbillionMap is used to animate the camera to a new position, represented by a CameraPosition object. A CameraPosition object is constructed using the CameraPosition.Builder class. The target position, zoom level, and tilt angle of the camera are specified using the target, zoom, and tilt methods, respectively. Once the CameraPosition object is constructed, a CameraUpdate object is created using the CameraUpdateFactory.newCameraPosition method, passing the CameraPosition object as an argument. Finally, the animateCamera method is called on the NextbillionMap object, passing the CameraUpdate object and the millisecondSpeed variable as arguments. The millisecondSpeed variable represents the speed of the camera animation, in milliseconds. The animateCamera method will animate the camera to the specified position over the specified duration, resulting in a smooth transition to the new camera position.