TPLMaps Pvt.
Ltd. |
|
|
TPL Maps Android SDK |
|
|
|
|
|
Release Date: October 09, 2019
Document Version: 1.4.1
Latest API Versions:
·
maps:1.4.1
·
places:1.1.3
·
routing:1.1.2
Step 1. Download Android Studio
Step 2. Create TPL Maps application project
Step 4. Setup map in your application
Step 5.
Connect an Android device
Step 6.
Build and run your app
Add Style Map
(JSON Formatted Style)
TPL Maps Android API provides help to add maps to your application. The API automatically handles access to our TPL Maps servers, data downloading, map display, and response to map gestures. You can do add markers, shapes, show/hide 3D buildings, show/hide point of interests, custom map styles and much more.
This guide is a quick start to adding a map to an Android app. Android Studio is the recommended development environment for building an app with the TPL Maps Android SDK.
Follow
the guides to download and install Android Studio.
Follow these steps to create a new app project including a map activity:
1.
Start Android Studio.
2.
Create a new project as follows:
a.
If you see the Welcome to Android
Studio dialog,
choose Start a new
Android Studio project, available under 'Quick Start' on the
right of the dialog.
b.
Otherwise, click File in the Android Studio menu bar, then New, New Project.
3.
Enter your app name, company domain, and project location,
as prompted. Then click Next.
4.
Select the form factors you need for your app. If you're
not sure what you need, just select Phone and Tablet.
Then click Next.
5.
Select Empty Activity in the 'Add an activity to Mobile'
dialog. Then click Next.
6.
Enter the activity name ‘ActivityTPLMaps’, layout name ‘layout_tpl_maps.xml’
and title as prompted. Then click Finish.
Android Studio starts Gradle and builds your project. This may
take a few seconds. For more information about creating a project in Android
Studio, see the Android
Studio documentation.
When the build is finished, Android Studio opens the layout_tpl_maps.xml and the ActivityTPLMaps.java files in the editor. (Note that your activity may have a
different name, but it will be the one you configured during setup). The
next section describes getting the API key in more detail.
Create an account on TPLMaps LBS Portal.
Generate Android API Key through Generate Key option.
Copy the key put it into meta-tag mentioned below and copy the tag in your project’s manifest.xml under <application> tag
<meta-data android:name="com.tplmaps.android.sdk.API_KEY" |
For setting map in your android application, you need to follow the instructions given in Setup Map section of this document
The simplest way to see your app in action is to connect an Android device to your computer. Follow the instructions to enable developer options on your Android device and configure your application and system to detect the device.
Alternatively, you can use the Android Emulator to run your app. Use the Android Virtual Device (AVD) Manager to configure one or more virtual devices which you'll be able to use with the Android Emulator when you build and run your app. When choosing your emulator, ensure that you use Android 4.2.2 or higher, and be careful to pick an image that includes the Google APIs, or the application will not have the requisite runtime APIs in order to execute. Also, take note of the instructions for configuring virtual machine acceleration, which you should use with an x86 target AVD as described in the instructions. This will improve your experience with the emulator.
In Android Studio, click the Run menu option (or the play button icon) to run your app.
When prompted to choose a device, choose one of the following options:
· Select the Android device that's connected to your computer.
· Alternatively, select the Launch emulator radio button and choose the virtual device that you've previously configured.
Click OK. Android Studio will invoke Gradle to build your app, and then display the results on the device or on the emulator. It could take a couple of minutes before the app opens.
You should see a map with a marker positioned over Sydney, Australia. If you don't see a map, confirm that you've completed all the steps described on this page. In particular, check that you've added an API key as described above.
You
may wish to look at some sample code.
To setup TPL Maps in your application follow these steps:
1. Add the following gradle configuration in your project level build.gradle file:
allprojects { } |
2. Add the following gradle dependency in your android application module’s build.gradle file:
dependencies { |
3. Add Internet permission in your manifest.xml
<uses-permission android:name="android.permission.INTERNET" /> |
4. Configure API Key for your project. See section Configure API KEY.
5. Add MapView in your layout file
<com.tplmaps3d.MapView |
6. Get MapView resource in your Activity’s onCreate() method, also call mapView.onCreate() life cycle method by adding the following lines of code
MapView
mapView= (MapView) findViewById(R.id.map); mapView.onCreate(savedInstanceState); |
7. Call MapView’s other life cycle methods by putting this code snippet into your Activity
@Override } |
8.
Implement MapView.OnMapReadyCallback interface with your Activity and use the onMapReady(MapController) callback method to get a
handle to the MapController object. The callback is
triggered when the map is ready to be used. It provides a non-null instance of MapController. You can use the MapController object to set the view options
for the map e.g. add a marker.
The method will look like this:
@Override |
9.
Load Map by adding the
below lines of code. The method loads
map asynchronously and you will get
callback in onMapReady(MapController)when map ready. The method will take a reference of MapView.OnMapReadyCallback instance as
parameter.
mapView.loadMapAsync(this); |
Note: MapView.loadMapAsync() must be called from the main thread, and the callback will be executed in the main thread
10.
Your Final code will be look like:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
|
ActivityTPLMaps.java
public class ActivityTPLMaps extends AppCompatActivity implements MapView.OnMapReadyCallback { |
layout_tpl_maps.xml
<?xml version="1.0" encoding="utf-8"?>
|
11. You will get TPL Maps loaded successfully in your application.
12. Furthermore, you can view or download our open source samples project to get help for more features of SDK.
Maps are represented in the API by the MapView and MapController classes.
The TPL Maps Android SDK allows you to display a map in your Android application. These maps have the same appearance as the maps you see in the TPL Maps for Mobile (TMM) app, and the API exposes many of the same features. Two notable differences between the TMM application and the maps displayed by the TPL Maps Android SDK are:
· Map tiles displayed by the API don't contain any personalized content, such as personalized smart icons.
· Not all icons on the map are clickable. For example, transit station icons can’t be clicked. However, markers that you add to the map are clickable, and the API has a listener callback interface for various marker interactions.
In addition to mapping functionality, the API also supports a full range of interactions that are consistent with the Android UI model. For example, you can set up interactions with a map by defining listeners that respond to user gestures.
The key class when working with a map object is the MapController class. The class models the map object within your application. Within your UI, a map will be represented by MapView object.
MapController handles the following operations automatically:
· Downloading map tiles.
· Displaying tiles on the device screen.
· Displaying various controls such as pan and zoom.
· Responding to pan and zoom gestures by moving the map and zooming in or out.
· Adding markers and different shapes and their interaction events.
In addition to these automatic operations, you can control the behavior of maps with objects and methods of the API. For example, MapController has callback methods that respond to touch gestures on the map. You can also set marker icons on your map and add overlays to it, using objects you provide to MapController.
MapView, a subclass of the Android FrameLayout class, allows you to place a map in an Android View. A View represents a rectangular region of the screen, and is a fundamental building block for Android applications and widgets.
When using the API, users of the MapView class must forward the following activity lifecycle methods to the corresponding methods in the MapView class: onCreate(), onStart(), onResume(),onPause(), onStop(), onDestroy(), onSaveInstanceState(), and onLowMemory(). A samples project on GitHub includes the code that demonstrates how to forward the activity lifecycle methods.
There are mode of maps available within the TPL Maps Android SDK. A map's mode governs the overall representation of the map.
The TPL Maps Android SDK offers two modes of maps:
Typical road map in Day mode. Shows lighter theme of roads, some features built by humans, and important natural features like rivers. Road and feature labels are also visible.
Typical road map in Night mode. Shows darker theme of roads, some features built by humans, and important natural features like rivers. Road and feature labels are also visible.
To set the mode of a map, call the MapView object's setMapMode() method, passing one of the type constants
defined in MapMode
e.g. MapMode.NIGHT
For example, to display Night mode:
mMapView.setMapMode(MapMode.NIGHT); |
Note: If you want use this functionality as default then call this method
with desired input before calling MapView.loadMapAsync()
method. Otherwise, if you want to have this functionality on runtime then you
can call this method in OnMapReadyCallback.onMapReady()callback
method.
The image below shows a comparison of default (day) and night maps for the same location:
The Maps API allows you to configure the initial state of the map to suit your application's needs. You can specify the following:
· The camera position, including: location, zoom, bearing and tilt.
· The map mode.
· Whether the zoom buttons, My Location Button and/or compass appear on screen.
· The map gesture a user can use to manipulate the camera.
You can configure the initial state of the map programmatically for now.
This section describes how to set the initial state of the
map if you have added a map to your application programmatically.
If you have setup maps successfully, then you can configure its initial state by calling functionalities/method from MapView or MapController class objects your settings specified. You can get a MapController object in MapView.OnMapReadyCallback.onMapReady()callback method like this:
@Override |
Call MapView.setMapMode() as below. This allows you to specify the mode of map to display. Pass MapMode.DEFAULT or MapMode.NIGHT as an argument to the method
mMapView.setMapMode(MapMode.NIGHT | MapMode.DEFAULT); |
Note: If you want use this functionality as default then call this method
with desired input before calling MapView.loadMapAsync()
method. Otherwise, if you want to have this functionality on runtime then you
can call this method in OnMapReadyCallback.onMapReady()callback method.
First, you need to get a MapController class object as defined above in this section. And then you can call MapController.setCamera(CameraPosition) or MapController.animateCamera(CameraPosition, int) to set camera without or with animation respectively. You need to build a CameraPosition class object with your values and passing it as an argument to both the methods. MapController.animateCamera(CameraPosition, int)will take animation duration in milliseconds as second argument. These allow you to specify the initial camera position.
The code specified below will take camera to the position (Faisal Mosque, Islamabad) on zoom level 17.0F (float) with tilt 1.0F (float) and rotation of 250.0F (float value in degrees)by performing animation of2000 milliseconds duration:
mapController.animateCamera(new CameraPosition.builder() |
Note: Pass rotation value by converting it in Radian unit
First, you need to get a MapController class object as defined above in this section. And then you can get Map UISettings from MapController by calling MapController.getUiSettings() after you can change or setup the following settings. These allow you to specify the initial Map UI settings.
·
Compass You can show/hide compass by passing true or false
value to the method as follow:
mapController.getUiSettings().showCompass(true); |
· Zoom Controls You can show/hide zoom controls by passing true or false value to the method as follow:
mapController.getUiSettings().showZoomControls(true); |
· Map Mode You can change MapMode as follows:
mMapView.setMapMode(MapMode.NIGHT | MapMode.DEFAULT); |
· 3D buildings You can show/hide building by passing true or false value to the method as follow:
mMapView.setBuildingsEnabled(true); |
· POIs (Point of interests) You can show/hide pois by passing true or false value to the method as follow:
mMapView.setPOIsEnabled(true); |
· Traffic You can hide/show traffic layer as follow:
mMapView.setTrafficEnabled(checked); |
· My Location Controls To use or enable My Location functionality and map UI control, See Enable Location on map section in this document
You can plot your current location on map by calling MapController.setMyLocationEnabled(boolean); Map will listen and plot your location through Location marker (Green filled and white outlined circle shaped marker, as screenshot below). The function will require a location runtime permission check above its calling. Add the permission check above this code snippet.
The function will automatically listen for location
updates received from location providers and will update the current location
marker layer continuously.
For more info please consult the API Documentation
of MapController
class.
You can make map listen and plot your location through Location marker (Green filled and white outlined circle shaped marker). Map will constantly listen your location and give you location updates through OnMyLocationChangeListener interface.
// To enable map to listen and plot your location |
Marker describe a single point or location on a map. They appear on the map as an icon and can display an info window with additional information when clicked. To draw marker on map, user must create MarkerOptions in which user can set different properties including location/point, icon, title, description etc. And then pass MarkerOptions to addMarker() method.
1. Add a marker:
Marker marker = mapController.addMarker(new MarkerOptions()
|
2. Customize marker icon
User can specify a custom
icon by using the IconFactory object and passing it to the marker. If user don’t specify an icon
, marker will be
given the default marker icon. User can also set size of custom marker with an
additional IconSize parameter
marker1.setIcon(IconFactory.defaultMarker(IconFactory.ORANGE));
marker1.setIcon(IconFactory.fromResource(R.drawable.ic_pin_drop));
marker1.setIcon(IconFactory.fromResource(R.drawable.ic_pin_drop, new IconSize(50, 50)));
|
3. Set or
customize an info window:
If user has set title or description of marker,
then a default info window will be shown on marker click. But user can also set
a custom info window to markers as follow:
mapController.setCustomInfoWindow(new MapController.CustomInfoWindow() {
|
Custom info window can be set by returning view in two callback methods. Controller first call onInfoWindow() method if returned view is null then onInfoWindowContent()gets called. If both are null then default info window will be shown.
4.
Remove marker:
User can remove a specific
marker by two ways as follow:
marker.remove(); // mapController.removeMarker(marker); |
All markers can also be removed in single call
mapController.removeAllMarkers(); |
User can also remove any shape polyline, polygon,
and circle in same way
Polyline is a path between two locations. There must be at least two points to draw a polyline. To draw polyline on map, user must create PolylineOptions in which user can set different properties including list of location/point, color, width, outline width, outline color etc. And then pass PolylineOptions to addPolyline() method
Polyline polyline = mapController.addPolyline(new PolylineOptions() .outlineWidth(2).outlineColor(Color.BLUE));
|
User can also draw a Polygon shape on map giving list of points. Polygon must have three points. To draw polygon on map, user must create PolygonOptions in which user can set different properties including list of location/point, fill color, outline width, outline color etc. And then pass PolygonOptions to addPolygon() method
ArrayList<LngLat> lngLats1 = new ArrayList<>();
|
To draw circle on map, user must create CircleOptions in which user can set different properties including center point, radius, fill color, outline width, outline color etc. And then pass CircleOptions to addCircle() method. Center point and radius must be set to draw a valid circle.
Circle circle = mapController.addCircle(new CircleOptions()
|
User can set click listener
for markers, info windows and all shapes. Marker and info windows are clickable
by default. But to get polyline, polygon and circle click listener, user must setClickable(true). Click listeners can be set as follow:
mapController.setOnMarkerClickListener(new mapController.OnMarkerClickListener() { |
You can set custom map style by calling this method
MapView.setMapStyle(String); |
All overrides of this method requires json formatted style which is described below:
A JSON style declaration consists of the following elements:
· FeatureType - the features to select for this style modification. Features are geographic characteristics on the map, including roads, parks, bodies of water, and more.
· Stylers - the rules to apply to the selected features. Stylers indicate the color, width, visibility, outline color and outline width of the feature. You can apply one or more stylers to a feature.
FeatureType
The following JSON snippet selects all roads on the map:
{ |
Features, or feature types, are geographic characteristics on the map, including roads, parks, bodies of water, businesses, and more.
Features contain child features you specify using a dot notation. For example, road.motorway or road.street. You must specify both parent and child the styles you specify for the parent apply to all its children, such as road.motorway and road.highway.
The following features are available:
·
map selects map
o
map.mode selects map
modes
o
map.pois selects pois
o map.buildings selects buildings
·
road selects road.
o
road.motorway selects motorways (e.g. M2, Pakistan)
o
road.highway selects highways
(e.g. Kashmir Highway, Islamabad)
o
road.main selects main
road (e.g. Jinnah Avenue, Islamabad)
o
road.secondary selects secondary roads (e.g.
Nazim ud Din Road, Islamabad)
o
road.tertiary selects tertiary roads
(e.g. Service roads)
o road.street selects streets
Styler
Styler is formatting options that you can apply to map features and elements.
The following JSON snippet displays a feature as bright green, using an RGB value:
"styler":[ ] |
The following style options are supported:
·
mode sets the mode
value of the feature.
You can use this method with map.mode feature
·
color (an RGB hex
string of format #RRGGBB) sets the color of the feature
Note: You need
to input color’s hex value in apostrophes character e.g. ”color”:”’#RRGGBB’”
·
width sets the width of the feature
Specify value for feature road
for different zoom levels
for example:[[5,0.4px],[10,2px],…,[15,5px],[20,65px]]
In this value, [[5,0.4px]] tuple
defines width (0.4px) at zoom level 5 and the next tuple [10,2px] defines width (2px) at zoom
level 10 and width values between these two zoom levels are linearly
interpolated.
· outline.color sets the outline color of the feature
· outline.width sets the outline width of the feature
·
Specify outline width for feature
road
for different zoom levels
for example[[5,0.4px],[10,2px],…,[20,65px]]
In this value, [[5,0.4px]] tuple defines width (0.4px) at zoom level 5 and the
next tuple [10,2px] defines width (2px) at zoom level 10 and width values
between these two zoom levels are linearly interpolated.
·
Visible sets the visibility of feature
[{ "featureType":
"map.mode", "styler": { "mode":
"night" } },{ "featureType":
"map.pois", "styler": { "visible":
"true" } },{ "featureType":
"map.buildings", "styler": { "visible":
"true" } },{ "featureType":
"road.motorway", "styler": { "color":
"'#4194f4'", "width": "[[5, 0.4px],[10,2px],[15,5px],[20,65px]]", "outline.color":
"'#000000'", "outline.width":
"[[5, 0.1px],[10, 0.5px],[15,1px],[20,2px]]", "visible":
"true" } },{ "featureType":
"road.street", "styler": { "color":
"'#f44141'", "width": "[[14, 1px],[15,3.5px],[20,50px]]",
"outline.color":
"'#000000'", "visible":
"true" } },{ "featureType":
"road.main", "styler": { "color":
"'#55f441'", "width": "[[7,
0.5px],[10,1px],[15,4px],[20,100px]]", "outline.color":
"'#000000'", "outline.width":
"[[5, 0.1px],[10, 0.5px],[15,1px]]", "visible":
"true" } }] |
API provides help to add places API to your application. The API automatically handles access to our TPL Maps servers, for fetching the better results of input query. You can implements it as places suggestion or results.
To setup Places API in your application follow these steps:
1. Add the following gradle configuration in your project level build.gradle file:
allprojects { } |
2. Add the following gradle dependency in your android application module’s build.gradle file:
dependencies { |
3. Add Internet permission in your manifest.xml
<uses-permission android:name="android.permission.INTERNET" /> |
4. Configure API Key for your project. See section Configure API KEY.
5.
Initialize an instance of SearchManager class by passing your
Activity’s reference as:
SearchManager searchManager= new SearchManager(this); |
In the above code this belongs to your Activity.
6.
Implement OnSearchResult interface and its
methods with your activity. There you will get responses against your search
queries.
Interface’s callback will look like this:
@Override |
7. Register a search listener by adding this line of code
searchManager.setListener(this); |
The method will take a reference of OnSearchResult class’s instance
8.
Call SearchManager.request (String, Params)
method by setting at least one param named Params.query you will get response in your
callback methods defined by your listener. In case of missing some
configurations related to the API or exceptions, you will get informed in these
callbacks.
searchManager.request(Params.builder() |
Note: Call SearchManager.request(Params) for search query after an
interval of minimum 3 seconds because of network limitations applied on our
servers otherwise all your request will be suspended
API provides help to add routing to your application. The API automatically handles access to our TPL Maps servers, for effective and possible routes from the given source and destination location. You can implement it to incorporate routing feature which can further be developed to Navigate users to the destination location (response containing instructions with route segments).
To setup Places API in your application follow these steps:
1. Add the following gradle configuration in your project level build.gradle file:
allprojects { } |
2. Add the following gradle dependency in your android application module’s build.gradle file:
dependencies
{ |
3. Add Internet permission in your manifest.xml
<uses-permission android:name="android.permission.INTERNET" /> |
4. Configure API Key for your project. See section Configure API KEY
5.
Initialize locations
array with source and destination locations
//
Initializing locations array |
6.
Prepare TPLRouteConfig object and pass it to TPLRouteManager#calculate() method
with necessary arguments as given below, You will get list of multiple routes
if exist between source & destination locations in IMapRoute#onMapRoutingOverview(ArrayList<Place>
endPoints, ArrayList<TPLRoute> routes) callback.
TPLRouteConfig
config = new TPLRouteConfig.Builder(false, locations) routes) { // TODO
Use data from ArrayList<TPLRoute> routes } |
You can see API documentation by hitting this link API Documentation
The samples
on GitHub includes
samples that demonstrate the use of MapController object and the MapView.
You can view or download our open source running samples project
to get help for the features of SDK.
·
Muhammad Hassan Jamil
Assistant Manager and Team Lead – Android Development
Email: hassan.jamil@tplmaps.com
·
Nouman Bhatti
Assistant Manager & Senior Software Engineer (Android)
Email: noman.bhatti@tplmaps.com
·
Faraz Khalid
Team Lead (Research and Development)
Email: faraz.khalid@tplmaps.com