Getting Started
MapmyIndia Maps SDK for Android lets you easily add MapmyIndia Maps and web services to your own Android application. The SDK for Android supports API 14+. You can have a look at the map and features you will get in your own app by using the MapmyIndia Maps SDK for Android.
Through customized tiles, you can add different map layers to your application and add bunch of controls and gestures to enhance map usability thus creating potent map based solutions for your customers. The SDK handles downloading of map tiles and their display along with a bunch of controls and native gestures.
API Usage
Your MapmyIndia Maps SDK usage needs a set of license keys (get them here) and is governed by the API terms and conditions. As part of the terms and conditions, you cannot remove or hide the MapmyIndia logo and copyright information in your project.
The allowed SDK hits are described on the user dashboard (http://www.mapmyindia.com/api/dashboard) page. Note that your usage is shared between platforms, so the API hits you make from a web application, Android app or an iOS app all add up to your allowed daily limit.
Setup your project
Follow these steps to add the SDK to your project –
- Create a new project in Android Studio
- Add MapmyIndia repository in your project level build.gradle
allprojects {
repositories {
maven {
url 'https://maven.mapmyindia.com/repository/mapmyindia/'
}
}
}
- Add below dependency in your app-level build.gradle
implementation 'com.mapmyindia.sdk:mapmyindia-android-sdk:6.8.2'
- Add these permissions in your project
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
Add Java 8 Support to the project
add following lines in your app module's build.gradle
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
Add your API keys to the SDK
Add your API keys to the SDK (in your application's onCreate() or before using map)
MapmyIndiaAccountManager.getInstance().setRestAPIKey(getRestAPIKey());
MapmyIndiaAccountManager.getInstance().setMapSDKKey(getMapSDKKey());
MapmyIndiaAccountManager.getInstance().setAtlasGrantType(getAtlasGrantType());
MapmyIndiaAccountManager.getInstance().setAtlasClientId(getAtlasClientId());
MapmyIndiaAccountManager.getInstance().setAtlasClientSecret(getAtlasClientSecret());
MapmyIndia.getInstance(getApplicationContext());
MapmyIndiaAccountManager.getInstance().restAPIKey = getRestAPIKey()
MapmyIndiaAccountManager.getInstance().mapSDKKey = getMapSDKKey()
MapmyIndiaAccountManager.getInstance().atlasGrantType = getAtlasGrantType()
MapmyIndiaAccountManager.getInstance().atlasClientId = getAtlasClientId()
MapmyIndiaAccountManager.getInstance().atlasClientSecret = getAtlasClientSecret()
MapmyIndia.getInstance(applicationContext)
You cannot use the MapmyIndia Map Mobile SDK without these function calls. You will find your keys in your API Dashboard.
Add a MapmyIndia Map to your application
<com.mapbox.mapboxsdk.maps.MapView
android:id="@id/map_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
NOTE: All the lifecycle methods that need to be overridden:
Initialize the mapView
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_layout);
mapView = findViewById(R.id.map_view);
mapView.onCreate(savedInstanceState);
}
@Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
@Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.base_layout)
mapView = findViewById(R.id.map_view)
mapView.onCreate(savedInstanceState)
}
override fun onStart() {
super.onStart()
mapView.onStart()
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onStop() {
super.onStop()
mapView.onStop()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
map_view.onSaveInstanceState(outState)
}
Map Interactions
The MapmyIndia Maps Android SDK allows you to define interactions that you can activate on the map to enable gestures and click events. The following interactions are supported –
Zoom Controls
The map supports the familiar two-finger pinch and zooms to change zoom level as well as double tap to zoom in. Set zoom to 4 for country level display and 18 for house number display. In this SDK the camera position plays an important role
And following operations can be performed using the CameraPosition
Target
The target is single latitude and longitude coordinate that the camera centers it on. Changing the camera's target will move the camera to the inputted coordinates. The target is a LatLng object. The target coordinate is always at the center of the viewport.
Tilt
Tilt is the camera's angle from the nadir (directly facing the Earth) and uses unit degrees. The camera's minimum (default) tilt is 0 degrees, and the maximum tilt is 60. Tilt levels use six decimal point of precision, which enables you to restrict/set/lock a map's bearing with extreme precision.
The map camera tilt can also adjust by placing two fingertips on the map and moving both fingers up and down in parallel at the same time or
Bearing
Bearing represents the direction that the camera is pointing in and measured in degrees clockwise from north.
The camera's default bearing is 0 degrees (i.e. "true north") causing the map compass to hide until the camera bearing becomes a non-zero value. Bearing levels use six decimal point precision, which enables you to restrict/set/lock a map's bearing with extreme precision. In addition to programmatically adjusting the camera bearing, the user can place two fingertips on the map and rotate their fingers.
Zoom
Zoom controls scale of the map and consumes any value between 0 and 22. At zoom level 0, viewport shows continents and other world features. A middle value of 11 will show city level details.At a higher zoom level, map will begin to show buildings and points of interest. Camera can zoom in following ways:
- Pinch motion two fingers to zoom in and out.
- Quickly tap twice on the map with a single finger to zoom in.
- Quickly tap twice on the map with a single finger and hold your finger down on the screen after the second tap.
- Then slide the finger up to zoom out and down to zoom out.
Sdk provides a OnMapReadyCallback, implements this callback and override it's onMapReady() and set the Camera position inside this method
CameraPosition position = new CameraPosition.Builder()
.target(new LatLng(22.8978, 77.3245)) // Sets the new camera position
.zoom(14) // Sets the zoom to level 14
.tilt(45) // Set the camera tilt to 45 degrees
.build();
mapmyIndiaMap.setCameraPosition(position)
val cameraPosition = CameraPosition.Builder()
.target(LatLng(22.8978, 77.3245))
.zoom(10.0)
.tilt(0.0)
.build()
mapmyIndiaMap?.cameraPosition = cameraPosition
Sdk allows various method to Move, ease,animate Camera to a particular location :
mapmyIndiaMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(22.8978,77.3245),14);
mapmyIndiaMap.easeCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(22.8978,77.3245),14);
mapmyIndiaMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(22.8978,77.3245),14);
mapmyIndiaMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(22.8978,77.3245), 14.0))
mapmyIndiaMap?.easeCamera(CameraUpdateFactory.newLatLngZoom(LatLng(22.8978,77.3245), 14.0))
mapmyIndiaMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(22.8978,77.3245), 14.0))
Map Events
The SDK allows you to listen to certain events on the map. It sets a callback that is invoked when camera movement has started.
mapmyIndiaMap.addOnCameraMoveStartedListener(new MapboxMap.OnCameraMoveStartedListener() {
private final String[] REASONS = {
"REASON_API_GESTURE",
"REASON_DEVELOPER_ANIMATION",
"REASON_API_ANIMATION"};
@Override
public void onCameraMoveStarted(int reason) {
String string = String.format(Locale.US, "OnCameraMoveStarted: %s", REASONS[reason - 1]);
Toast.makeText(MainActivity.this, string, Toast.LENGTH_LONG).show();
}
});
mapmyIndiaMap.addOnCameraMoveStartedListener(object : MapboxMap.OnCameraMoveStartedListener {
private val REASONS: Array<String> = arrayOf(
"REASON_API_GESTURE",
"REASON_DEVELOPER_ANIMATION",
"REASON_API_ANIMATION"
)
override fun onCameraMoveStarted(i: Int) {
var string: String = String.format("OnCameraMoveStarted: %s", REASONS[i - 1])
Toast.makeText(this@MainActivity, string, Toast.LENGTH_SHORT).show()
}
})
It sets a callback that is invoked when camera movement was cancelled.
mapmyIndiaMap.addOnCameraMoveCancelListener(new MapboxMap.OnCameraMoveCanceledListener() {
@Override
public void onCameraMoveCanceled() {
Toast.makeText(MainActivity.this, "onCameraMoveCanceled", Toast.LENGTH_LONG).show();
}
});
mapmyIndiaMap.addOnCameraMoveCancelListener(object : MapboxMap.OnCameraMoveCanceledListener {
override fun onCameraMoveCanceled() {
Toast.makeText(this@MainActivity, "onCameraMoveCanceled", Toast.LENGTH_SHORT).show()
}
})
It sets a callback that is invoked when camera movement has ended.
mapmyIndiaMap.addOnCameraIdleListener(new MapboxMap.OnCameraIdleListener() {
@Override
public void onCameraIdle() {
Toast.makeText(MainActivity.this, "onCameraIdle", Toast.LENGTH_LONG).show();
}
});
mapmyIndiaMap.addOnCameraIdleListener(object : MapboxMap.OnCameraIdleListener {
override fun onCameraIdle() {
Toast.makeText(this@MainActivity, "onCameraIdle", Toast.LENGTH_SHORT).show()
}
})
Map Click/Long Press
If you want to respond to a user tapping on a point on the map, you can use a MapEventsOverlay which you need to add on the map as an Overlay.
It sets a callback that's invoked when the user clicks on the map view.
mapmyIndiaMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
@Override
public void onMapClick(@NonNull LatLng point) {
String string = String.format(Locale.US, "User clicked at: %s", point.toString())
Toast.makeText(MainActivity.this, string, Toast.LENGTH_LONG).show();
}
});
mapmyIndiaMap.addOnMapClickListener(object: MapboxMap.OnMapClickListener {
override fun onMapClick(latLng: LatLng) {
val string: String = String.format("User clicked at: %s", latLng.toString())
Toast.makeText(this@MainActivity, string, Toast.LENGTH_LONG).show()
}
})
Sets a callback that's invoked when the user long clicks on the map view.
mapmyIndiaMap.addOnMapLongClickListener(new MapboxMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(@NonNull LatLng point) {
String string = String.format(Locale.US, "User long clicked at: %s", point.toString());
Toast.makeText(MainActivity.this, string, Toast.LENGTH_LONG).show();
}
});
mapmyIndiaMap.addOnMapLongClickListener(object: MapboxMap.OnMapLongClickListener {
override fun onMapLongClick(latLng: LatLng) {
var string: String = String.format("User long clicked at: %s", latLng.toString())
Toast.makeText(this@MainActivity, string, Toast.LENGTH_LONG).show()
}
})
Map Overlays
Add a marker
Add markers to the map by following these steps –
MarkerOptions markerOptions = new MarkerOptions().position(point).icon(IconFactory.getInstance(SimpleMapActivity.this).fromResource(R.drawable.ic_android));
markerOptions.setTitle("Marker");
markerOptions.setSnippet("This is a Marker");
Marker marker = mapmyIndiaMap.addMarker(markerOptions);
val markerOptions: MarkerOptions = MarkerOptions().position(point).icon(IconFactory.getInstance(this@SimpleMapActivity).fromResource(R.drawable.ic_android))
markerOptions.title= "Marker"
markerOptions.snippet = "This is a Marker"
mapmyIndiaMap?.addMarker(markerOptions)
Remove a Marker
mapmyIndiaMap.removeMarker(marker)
mapmyIndiaMap?.removeMarker(marker)
Customize a marker
MarkerOptions markerOptions = new MarkerOptions().position(point).icon(IconFactory.getInstance(context).fromResource(R.drawable.ic_android));
Marker marker = mapmyIndiaMap.addMarker(markerOptions);
marker.setTitle("title");
mapmyIndiaMap.setInfoWindowAdapter(new MapboxMap.InfoWindowAdapter() {
@Nullable
@Override
public View getInfoWindow(@NonNull Marker marker) {
View view = getLayoutInflater().inflate(R.layout.layout, null);
TextView text = view.findViewById(R.id.text);
text.setText(marker.getTitle());
return view;
}
});
val markerOptions: MarkerOptions = MarkerOptions().position(point).icon(IconFactory.getInstance(context).fromResource(R.drawable.ic_android))
markerOptions.title= "Marker"
mapmyIndiaMap?.addMarker(markerOptions)
mapmyIndiaMap?.setInfoWindowAdapter {
val view: View? = getLayoutInflater().inflate(R.layout.layout, null)
val textView: TextView = view?.findViewById(R.id.text)!!
textView.text = it.title
return@setInfoWindowAdapter view
}
Add a Polyline
Draw polyline on the map
mapmyIndiaMap.addPolyline(new PolylineOptions()
.addAll(points)//list of LatLng
.color(Color.parseColor("#3bb2d0"))
.width(2));
mapmyIndiaMap.addPolyline(PolylineOptions()
.addAll(points)
.color(Color.parseColor("#3bb2d0"))
.width(2f))
Remove Polyline
To remove a polyline from map:
mapmyIndiaMap.removePolyline(polyline);
mapmyIndiaMap.removePolyline(polyLine!!)
Add A Polygon
Draw a polygon on the map
mapmyIndiaMap.addPolygon(new PolygonOptions()
.addAll(polygon)//list of LatLng.
.fillColor(Color.parseColor("#3bb2d0")));
mapmyIndiaMap.addPolygon(PolygonOptions()
.addAll(polygon)
.fillColor(Color.parseColor("#3bb2d0")))
Remove Polygon
To remove a polygon from map:
mapmyIndiaMap.removePolygon(polygon);
mapmyIndiaMap.removePolygon(polygon!!)
Show user location
Show the current user location
Implement LocationEngineListener and override it's method
LocationComponentOptions options = LocationComponentOptions.builder(context)
.trackingGesturesManagement(true)
.accuracyColor(ContextCompat.getColor(this, R.color.colorAccent))
.build();
// Get an instance of the component LocationComponent
locationComponent = mapmyIndiaMap.getLocationComponent();
// Activate with options
locationComponent.activateLocationComponent(context, options);
// Enable to make component visible
locationComponent.setLocationComponentEnabled(true);
locationEngine = locationComponent.getLocationEngine();
locationEngine.addLocationEngineListener(this);
// Set the component's camera mode
locationComponent.setCameraMode(CameraMode.TRACKING);
locationComponent.setRenderMode(RenderMode.COMPASS);
@Override
public void onConnected() {
locationEngine.requestLocationUpdates();
}
@Override
public void onLocationChanged(Location location) {
mapmyIndiaMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 16));
}
@Override
protected void onResume() {
super.onResume();
if (locationEngine != null) {
locationEngine.removeLocationEngineListener(this);
locationEngine.addLocationEngineListener(this);
}
}
@Override
protected void onPause() {
super.onPause();
if (locationEngine != null)
locationEngine.removeLocationEngineListener(this);
}
}
@Override
protected void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationEngineListener(this);
locationEngine.removeLocationUpdates();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
}
val options: LocationComponentOptions = LocationComponentOptions.builder(context)
.trackingGesturesManagement(true)
.accuracyColor(ContextCompat.getColor(this, R.color.colorAccent))
.build()
locationComponent = mapmyIndiaMap.locationComponent
locationComponent.activateLocationComponent(this, options)
locationComponent.isLocationComponentEnabled = true
locationEngine = locationComponent.locationEngine!!
locationEngine.addLocationEngineListener(this)
locationComponent.cameraMode = CameraMode.TRACKING
locationComponent.renderMode = RenderMode.COMPASS
override fun onConnected() {
locationEngine?.requestLocationUpdates()
}
override fun onLocationChanged(location: Location) {
mapmyIndiaMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(
LatLng(location.latitude, location.longitude), 16.0))
}
override fun onResume() {
super.onResume()
if (locationEngine != null) {
locationEngine?.removeLocationEngineListener(this);
locationEngine?.addLocationEngineListener(this);
}
}
override fun onPause() {
super.onPause()
if (locationEngine != null)
locationEngine?.removeLocationEngineListener(this);
}
override fun onStop() {
super.onStop()
if (locationEngine != null) {
locationEngine?.removeLocationEngineListener(this);
locationEngine?.removeLocationUpdates();
}
}
override fun onDestroy() {
super.onDestroy()
if (locationEngine != null) {
locationEngine?.deactivate();
}
}
Dashed PolyLine
DashPolyline Plugin provides option to add or remove dash polyline.
Add Dashed PolyLine
DashedPolylinePlugin dashedPolylinePlugin = new DashedPolylinePlugin(mapmyIndiaMap, mapView);
dashedPolylinePlugin.createPolyline(listOfLatLng);
val dashedPolylinePlugin = DashedPolylinePlugin(mapmyIndiaMap, map_view!!)
dashedPolylinePlugin.createPolyline(listOfLatLng!!)
Remove Dashed PolyLine
dashedPolylinePlugin.clear();
dashedPolylinePlugin.clear();
Calculate distance between two points
To calculate aerial distance between two points:
LatLng firstLatLng = new LatLng(28, 77);
LatLng secondLatLng = new LatLng(28.67, 77.65);
firstLatLng.distanceTo(secondLatLng);
val firstLatLng = LatLng(28.0, 77.0)
val secondLatLng = LatLng(28.67, 77.65)
firstLatLng.distanceTo(secondLatLng)
Proguard
# Retrofit 2
# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on RoboVM on iOS. Will not be used at runtime.
-dontnote retrofit2.Platform
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes *Annotation*,Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions
# For using GSON @Expose annotation
-keepattributes *Annotation*
# Gson specific classes
-dontwarn sun.misc.**
-dontwarn okio.**
-dontwarn okhttp3.**
-keep class retrofit.**
-keep class retrofit.** { *; }
-keepclasseswithmembers class * {
@retrofit.http.* <methods>;
}
-keep class com.mmi.services.account.** {
<fields>;
<methods>;
}
-keep class com.mmi.services.api.** {
<fields>;
<methods>;
}
-keep class com.mmi.services.utils.** {
<fields>;
<methods>;
}
Map UI settings
Compass Settings
To change compass related settings:
Enable/ Disable compass
To enable or disable the compass:
mapmyIndiaMap.getUiSettings().setCompassEnabled(true);
mapmyIndiaMap?.uiSettings?.isCompassEnabled = true
Enable/Disable Fading of the compass when facing north
To enable or disable fading of the compass when facing north:
mapmyIndiaMap.getUiSettings().setCompassFadeFacingNorth(true);
mapmyIndiaMap?.uiSettings?.setCompassFadeFacingNorth(true)
Gravity of Compass
To set the gravity of compass view:
mapmyIndiaMap.getUiSettings().setCompassGravity(Gravity.TOP);
mapmyIndiaMap?.uiSettings?.compassGravity = Gravity.TOP
Margins of compass
To set the margin of compass view:
mapmyIndiaMap.getUiSettings().setCompassMargins(left, top, right, bottom);
mapmyIndiaMap?.uiSettings?.setCompassMargins(left, top, right, bottom)
Enable/Disable zoom of map on double tap
To enable or disable zoom on double tap:
mapmyIndiaMap.getUiSettings().setDoubleTapGesturesEnabled(false);
mapmyIndiaMap?.uiSettings?.isDoubleTapGesturesEnabled = false
Logo Settings
To change the positions of logo:
Gravity of Logo
To set the gravity of Logo view:
mapmyIndiaMap.getUiSettings().setLogoGravity(Gravity.TOP);
mapmyIndiaMap?.uiSettings?.logoGravity = Gravity.TOP
Margin of Logo
To set the margins of Logo view
mapmyIndiaMap.getUiSettings().setLogoMargins(left, top, right, bottom);
mapmyIndiaMap?.uiSettings?.setLogoMargins(left, top, right, bottom)
Enable/ Disable Map Rotation Gesture
To enable or disable the map rotation:
mapmyIndiaMap.getUiSettings().setRotateGesturesEnabled(false);
mapmyIndiaMap?.uiSettings?.isRotateGesturesEnabled = false
Enable/Disable Map Scrolling Gesture
To enable or disable the map scrolling:
Enable/ Disable Map Tilt Gesture
To enable or disable map tilt:
mapmyIndiaMap.getUiSettings().setTiltGesturesEnabled(false);
mapmyIndiaMap?.uiSettings?.isTiltGesturesEnabled = false
Show Zoom control button
To show or hide zoom control button:
mapmyIndiaMap.getUiSettings().setZoomControlsEnabled(true);
mapmyIndiaMap?.uiSettings?.isZoomControlsEnabled = true
Enable/Disable Zoom Gesture
To enable or disable zoom gesture
mapmyIndiaMap.getUiSettings().setZoomGesturesEnabled(false);
mapmyIndiaMap?.uiSettings?.isZoomGesturesEnabled = false
Check Demo application for more implementation details
REST APIs
Search API's
The following search services are available as part of the SDK bundled by default –
Auto Suggest
The Autosuggest API helps users to complete queries faster by adding intelligent search capabilities to your web or mobile app. This API returns a list of results as well as suggested queries as the user types in the search field.
MapmyIndiaAutoSuggest.builder()
.query(searchText)
.build()
.enqueueCall(new Callback<AutoSuggestAtlasResponse>() {
@Override
public void onResponse(@NonNull Call<AutoSuggestAtlasResponse> call, @NonNull Response<AutoSuggestAtlasResponse> response) {
//handle response
}
@Override
public void onFailure(@NonNull Call<AutoSuggestAtlasResponse> call, @NonNull Throwable t) {
t.printStackTrace();
}
});
MapmyIndiaAutoSuggest.builder()
.query(searchText)
.build()
.enqueueCall(object : Callback<AutoSuggestAtlasResponse> {
override fun onResponse(call: Call<AutoSuggestAtlasResponse>, response: Response<AutoSuggestAtlasResponse>) {
//handle response
}
override fun onFailure(call: Call<AutoSuggestAtlasResponse>, t: Throwable) {
t.printStackTrace()
}
})
Request Parameters
Mandatory Parameter
-
query(String) : e.g. Shoes, Coffee, Versace, Gucci, H&M, Adidas, Starbucks, B130 {POI, House Number, keyword, tag}.
Optional Parameters
-
setLocation(latitude, longitude): e.g. setLocation(28.454,77.435).
-
zoom (double) : takes the zoom level of the current scope of the map (min: 4, max: 18).
-
tokenizeAddress(boolean): provides the different address attributes in a structured object.
-
pod (string) = it takes in the place type code which helps in restricting the results to certain chosen type.Below mentioned are the codes for the pod
- AutoSuggestCriteria.POD_SUB_LOCALITY
- AutoSuggestCriteria.POD_LOCALITY
- AutoSuggestCriteria.POD_CITY
- AutoSuggestCriteria.POD_VILLAGE
- AutoSuggestCriteria.POD_SUB_DISTRICT
- AutoSuggestCriteria.POD_DISTRICT
- AutoSuggestCriteria.POD_STATE
- AutoSuggestCriteria.POD_SUB_SUB_LOCALITY
-
filter = this parameter helps you restrict the result either by mentioning a bounded area or to certain eloc (6 digit code to any poi, locality, city, etc.), below mentioned are the both types:
-
filter = bounds: lat1, lng1; lat2, lng2 (latitude, longitude) {e.g. filter("bounds: 28.598882, 77.212407; 28.467375, 77.353513")
-
filter = cop: {eloc} (string) {e.g. filter("cop:YMCZ0J")
Response Code (as HTTP response code)
Success:
- 200: To denote a successful API call.
- 204: To denote the API was a success but no results were found.
Client side issues:
- 400: Bad Request, User made an error while creating a valid request.
- 401: Unauthorized, Developer’s key is not allowed to send a request with restricted parameters.
- 403: Forbidden, Developer’s key has hit its daily/hourly limit.
Server-Side Issues:
- 500: Internal Server Error, the request caused an error in our systems.
- 503: Service Unavailable, during our maintenance break or server downtimes.
Response Messages (as HTTP response message)
- 200: Success.
- 204: No matches were found for the provided query.
- 400: Something’s just not right with the request.
- 401: Access Denied.
- 403: Services for this key has been suspended due to daily/hourly transactions limit.
- 500: Something went wrong.
- 503: Maintenance Break.
Response parameters
-
suggestedLocations(ArrayList<ELocation>): A List of the suggested location
-
userAddedLocations(ArrayList<ELocation>): List of user added locations
-
suggestedSearches(ArrayList<SuggestedSearchAtlas>): List of suggestion related to your search.
ELocation Response result parameters:
-
poiId(String): Place Id of the location 6-char alphanumeric.
-
placeAddress(String): Address of the location.
-
latitude(String): Latitude of the location.
-
longitude(String): longitude of the location.
-
type(String): type of location POI or Country or City
-
placeName(String): Name of the location.
-
user(String): Name of the user who add the place
-
index(Integer): the order where this result should be placed
-
addressTokens(AddressToken)
AddressToken parameters:
-
houseNumber(String): house number of the location.
-
houseName(String): house name of the location.
-
poi(String): name of the POI (if applicable)
-
street(String): name of the street. (if applicable)
-
subSubLocality(String): the sub-sub-locality to which the location belongs. (if applicable)
-
subLocality(String): the sub-locality to which the location belongs. (if applicable)
-
locality(String): the locality to which the location belongs. (if applicable)
-
village(String): the village to which the location belongs. (if applicable)
-
subDistrict(String): the sub-district to which the location belongs. (if applicable)
-
district(String): the district to which the location belongs. (if applicable)
-
city(String): the city to which the location belongs. (if applicable)
-
state(String): the state to which the location belongs. (if applicable)
-
pincode(String): the PIN code to which the location belongs. (if applicable)
SuggestedSearchAtlas Response Result Parameters
-
keyword (string): what the user typed in.
-
identifier (string): what did the API use for it to qualify it as a suggested search request
-
location (string): the name of the location to which the nearby will run in context to.
-
hyperlink (string): the ready-made link for the nearby API pre-initialized with all default parameters and location with code to search for.
Geocoding
Our Geocoding API converts real addresses into these geographic coordinates (latitude/longitude) to be placed on a map, be it for any street, area, postal code, POI or a house number etc.
MapmyIndiaGeoCoding.builder()
.setAddress("Delhi")
.build()
.enqueueCall(new Callback<GeoCodeResponse>() {
@Override
public void onResponse(Call<GeoCodeResponse> call, Response<GeoCodeResponse> response) {
//handle response
}
@Override
public void onFailure(Call<GeoCodeResponse> call, Throwable t) {
t.printStackTrace();
}
});
MapmyIndiaGeoCoding.builder()
.setAddress("Delhi")
.build()
.enqueueCall(object : Callback<GeoCodeResponse> {
override fun onResponse(call: Call<GeoCodeResponse>, response: Response<GeoCodeResponse>) {
//handle response
}
override fun onFailure(call: Call<GeoCodeResponse>, t: Throwable) {
t.printStackTrace()
}
})
Request Parameters
Mandatory Parameter
-
setAddress(String) : address to be geocoded e.g. 237 Okhla industrial estate phase 3 new delhi, delhi 110020.
Optional Parameters
-
itemCount(Integer): parameter can be set to get maximum number of result items from the API (default: 1).
-
podFilter(String)This parameter can be used to set admin level restriction. The result will be either the given admin level or equivalent admin or higher in the hierarchy. Below mentioned are the codes for the pod:
- GeoCodingCriteria.POD_HOUSE_NUMBER
- GeoCodingCriteria.POD_HOUSE_NAME
- GeoCodingCriteria.POD_POINT_OF_INTEREST
- GeoCodingCriteria.POD_STREET
- GeoCodingCriteria.POD_SUB_SUB_LOCALITY
- GeoCodingCriteria.POD_VILLAGE
- GeoCodingCriteria.POD_SUB_LOCALITY
- GeoCodingCriteria.POD_SUB_DISTRICT
- GeoCodingCriteria.POD_LOCALITY
- GeoCodingCriteria.POD_CITY
- GeoCodingCriteria.POD_DISTRICT
- GeoCodingCriteria.POD_PINCODE
- GeoCodingCriteria.POD_STATE
-
bias(String): This parameter can be used to set Urban or Rural bias. A positive value sets the Urban bias and a negative value sets Rural bias. Below mentioned are the codes for the bias:
- GeoCodingCriteria.BIAS_DEFAULT (No bias)
- GeoCodingCriteria.BIAS_RURAL
- GeoCodingCriteria.BIAS_URBAN
-
bound(String): This parameter can be used to set admin boundary, which means geocoding will be done within the given admin. The allowed admin bounds are Sub-District, District, City, State and Pincode. The parameter accepts the admin eLoc as value.
Note: Please note that podFilter & bound parameters are mutually exclusive. They cannot be used together in an API call.
Response Code {as HTTP response code}
Success:
- 200: To denote a successful API call.
- 204: To denote the API was a success but no results were found.
Client-Side Issues:
- 400: Bad Request, User made an error while creating a valid request.
- 401: Unauthorized, Developer’s key is not allowed to send a request with restricted parameters.
- 403: Forbidden, Developer’s key has hit its daily/hourly limit.
Server-Side Issues:
- 500: Internal Server Error, the request caused an error in our systems.
- 503: Service Unavailable, during our maintenance break or server downtimes.
Response Messages (as HTTP response message)
- 200: Success.
- 204: No matches were found for the provided query.
- 400: Something’s just not right with the request.
- 401: Access Denied.
- 403: Services for this key has been suspended due to daily/hourly transactions limit.
- 500: Something went wrong.
- 503: Maintenance Break.
Response Parameters
-
GeoCodeResponse(List<GeoCode>): All the details regarding place.
GeoCode response Result parameters
-
houseNumber (String): the houseNumber of the address/location
-
houseName (String): houseName of the address/location
-
poi(string): the point of interest or famous landmark nearby the location
-
street(string): the street or road of the location
-
subsubLocality(string): the subSubLocality of the location
-
subLocality(string): the subLocality of the location
-
locality(string): the locality of the location
-
village(string): the village of the location
-
subDistrict(string): the subDistrict of the location
-
district(string): the district of the location
-
city(string): the city of the location
-
state(string): the state of the location
-
pincode(string): the pincode of the location
-
formattedAddress(string): the general protocol following address
-
eloc(string): eloc of the particular location
-
latitude(double): the latitude for the location.
-
longitude(double): the longitude for the location.
-
geocodeLevel(string): the best matched address component.
Reverse Geocode
Reverse Geocoding is a process to give the closest matching address to a provided geographical coordinates (latitude/longitude). MapmyIndia reverse geocoding API provides real addresses along with nearest popular landmark for any such geo-positions on the map.
MapmyIndiaReverseGeoCode.builder()
.setLocation(28, 77)
.build()
.enqueueCall(new Callback<PlaceResponse>() {
@Override
public void onResponse(Call<PlaceResponse> call,Response<PlaceResponse> response) {
//handle response
}
@Override
public void onFailure(Call<PlaceResponse> call, Throwable t) {
t.printStackTrace();
}
});
MapmyIndiaReverseGeoCode.builder()
.setLocation(28.0, 77.0)
.build()
.enqueueCall(object : Callback<PlaceResponse> {
override fun onResponse(call: Call<PlaceResponse>, response: Response<PlaceResponse>) {
//handle response
}
override fun onFailure(call: Call<PlaceResponse>, t: Throwable) {
t.printStackTrace()
}
})
Request Parameters
-
setLocation(latitude, longitude): the latitude and longitude of the location for which the address is required.
Response Code (as HTTP response code)
Success:
- 200: To denote a successful API call.
- 204: To denote the API was a success but no results were found.
Client-Side Issues:
- 400: Bad Request, User made an error while creating a valid request.
- 401: Unauthorized, Developer’s key is not allowed to send a request with restricted parameters.
- 403: Forbidden, Developer’s key has hit its daily/hourly limit.
Server-Side Issues:
- 500: Internal Server Error, the request caused an error in our systems.
- 503: Service Unavailable, during our maintenance break or server downtimes.
Response Messages (as HTTP response message)
- 200: Success.
- 204: No matches were found for the provided query.
- 400: Something’s just not right with the request.
- 401: Access Denied.
- 403: Services for this key has been suspended due to daily/hourly transactions limit.
- 500: Something went wrong.
- 503: Maintenance Break.
Response Parameters
-
responseCode(Long): Response codes of the api.
-
version(String): Version of the Api.
-
places(List<Places>): All the details regarding place.
Place Response result parameters:
-
houseNumber(String): the houseNumber of the address/location
-
houseName(String): houseName of the address/location
-
poi(String): the point of interest or famous landmark nearby the location
-
poiDist(String): distance from nearest POI in metres.
-
street(String): the street or road of the location
-
streetDist(String): distance from nearest Street in metres.
-
subsubLocality(String): the subSubLocality of the location
-
subLocality(String): the subLocality of the location
-
locality(String): the locality of the location
-
village(String): the village of the location
-
subDistrict(String): the subDistrict of the location
-
district(String): the district of the location
-
city(String): the city of the location
-
state(String): the state of the location
-
pincode(String): the pincode of the location
-
formattedAddress(String): the general protocol following address
-
lat(Double): the latitude for the location.
-
lng(Double): the longitude for the location.
-
area(String): the area of the location.
Nearby Places
Nearby Places API, enables you to add discovery and search of nearby POIs by searching for a generic keyword used to describe a category of places or via the unique code assigned to that category.
MapmyIndiaNearby.builder()
.keyword("Parking")
.setLocation(28d, 77d)
.build()
.enqueueCall(new Callback<NearbyAtlasResponse>() {
@Override
public void onResponse(Call<NearbyAtlasResponse> call, Response<NearbyAtlasResponse> response) {
//handle response
}
@Override
public void onFailure(Call<NearbyAtlasResponse> call, Throwable t) {
t.printStackTrace();
}
});
MapmyIndiaNearby.builder()
.keyword("Parking")
.setLocation(28.0, 77.0)
.build()
.enqueueCall(object : Callback<NearbyAtlasResponse> {
override fun onResponse(call: Call<NearbyAtlasResponse>, response: Response<NearbyAtlasResponse>) {
//handle response
}
override fun onFailure(call: Call<NearbyAtlasResponse>, t: Throwable) {
t.printStackTrace()
}
})
Request Parameters
Mandatory Parameters:
-
keyword(String): performs search on the basis of provided key
-
setLocation(latitude, longitude):Provide the location around which the search will be performed
Optional Parameters:
- `sort(String)`` provides configured sorting operations for the client on cloud.Below are the available sorts:
-
NearbyCriteria.DISTANCE_ASCENDING NearbyCriteria.DISTANCE_DESCENDING will sort data in order of distance from the passed location (default).
-
NearbyCriteria.NAME_ASCENDING NearbyCriteria.NAME_DESCENDING will sort the data on alphabetically bases.
-
page (integer): provides number of the page to provide results from.
-
radius(integer): provides the range of distance to search over(default: 1000, min: 500, max: 10000)
-
bounds (x1,y1;x2,y2): Allows the developer to send in map bounds to provide a nearby search of the geobounds. where x1,y1 are the lat lng of.
-
userName(String): Use to set the user name
-
richData(Boolean): rich data related to poi
Response Code (as HTTP response code)
Success:
- 200: To denote a successful API call.
- 204: To denote the API was a success but no results were found.
Client-Side Issues:
- 400: Bad Request, User made an error while creating a valid request.
- 401: Unauthorized, Developer’s key is not allowed to send a request with restricted parameters.
- 403: Forbidden, Developer’s key has hit its daily/hourly limit.
Server-Side Issues:
- 500: Internal Server Error, the request caused an error in our systems.
- 503: Service Unavailable, please contact MapmyIndia
Response Messages (as HTTP response message)
- 200: Success.
- 204: No matches were found for the provided query.
- 400: Something’s just not right with the request.
- 401: Access Denied.
- 403: Services for this key has been suspended due to daily/hourly transactions limit.
- 500: Something went wrong.
- 503: Maintenance Break.
On Response Parameters
-
suggestedLocations(ArrayList<NearbyAtlasResult>): List of nearby places
NearbyAtlasResult Response Result Parameters
-
distance (integer): provides the distance from the provided location bias in meters.
-
eLoc (string): Place Id of the location 6-char alphanumeric.
-
email (string): Email for contact.
-
entryLatitude (double): latitude of the entrance of the location.
-
entryLongitude (double): longitude of the entrance of the location.
-
keywords ( [ string ] ): provides an array of matched keywords or codes.
-
landlineNo (string): Email for contact.
-
latitude (double): Latitude of the location.
-
longitude (double): longitude of the location.
-
mobileNo : Phone number for contact.
-
orderIndex (integer): the order where this result should be placed
-
placeAddress (string): Address of the location.
-
placeName (string): Name of the location.
-
city(string): City of the location
-
state(string): State of the location
-
pincode(string): Pincode of the location
-
richInfo(Map): To show advance information of location
-
type (string): Type of location POI or Country or City.
eLoc / Place Details
MapmyIndia eloc is a simple, standardized and precise pan-India digital address system. Every location has been assigned a unique digital address or an eLoc. The eLoc API can be used to extract the details of a place with the help of its eLoc i.e. a 6 digit code or a place_id.
MapmyIndiaELoc.builder()
.setELoc("mmi000")
.build()
.enqueueCall(new Callback<PlaceResponse>() {
@Override
public void onResponse(Call<PlaceResponse> call, Response<PlaceResponse> response) {
//handle response
}
@Override
public void onFailure(Call<PlaceResponse> call, Throwable t) {
t.printStackTrace();
}
});
MapmyIndiaELoc.builder()
.setELoc("mmi000")
.build()
.enqueueCall(object : Callback<PlaceResponse> {
override fun onResponse(call: Call<PlaceResponse>, response: Response<PlaceResponse>) {
//handle response
}
override fun onFailure(call: Call<PlaceResponse>, t: Throwable) {
t.printStackTrace()
}
})
Request Parameters
Mandatory Parameters:
-
setEloc(String): the id or eLoc of the place whose details are required. The 6-digit alphanumeric
code for any location. (e.g. mmi000).
Response Code (as HTTP response code)
Success:
- 200: To denote a successful API call.
- 204: To denote the API was a success but no results were found.
Client-Side Issues:
- 400: Bad Request, User made an error while creating a valid request.
- 401: Unauthorized, Developer’s key is not allowed to send a request with restricted parameters.
- 403: Forbidden, Developer’s key has hit its daily/hourly limit.
Server-Side Issues:
- 500: Internal Server Error, the request caused an error in our systems.
- 503: Service Unavailable, during our maintenance break or server downtimes.
Response Messages (as HTTP response message)
- 200: Success.
- 204: No matches were found for the provided query.
- 400: Something’s just not right with the request.
- 401: Access Denied.
- 403: Services for this key has been suspended due to daily/hourly transactions limit.
- 500: Something went wrong.
- 503: Maintenance Break.
On Response Parameters
-
places(List<Place>): List of nearby places
Place result parameter
-
houseNumber (string): The house number of the location.
-
houseName (string): The name of the location.
-
poi (string): The name of the POI if the location is a place of interest (POI).
-
street (string): The name of the street of the location.
-
subSubLocality (string): The name of the sub-sub-locality where the location exists.
-
subLocality (string): The name of the sub-locality where the location exists.
-
locality (string): The name of the locality where the location exists.
-
village (string): The name of the village if the location exists in a village.
-
district (string): The name of the district in which the location exists.
-
subDistrict (string): The name of the sub-district in which the location exists.
-
city (string): The name of the city in which the location exists.
-
state(string): The name of the state in which the location exists.
-
pincode (string): The pin code of the location area.
-
latitude (double): The latitude of the location.
-
longitude (double): The longitude of the location.
-
placeId (string): The eLoc or placeId assigned for a place in map database. An eLoc is the digital identity for an address or business to identify its unique location. For more information on eLoc, click here.
-
type (string): defines the type of location matched (HOUSE_NUMBER, HOUSE_NAME, POI, STREET, SUB_LOCALITY, LOCALITY, VILLAGE, DISTRICT, SUB_DISTRICT, CITY, STATE, SUBSUBLOCALITY, PINCODE)
Routes & Navigation API
Routing API
Routing and displaying driving directions on map, including instructions for navigation, distance to destination, traffic etc. are few of the most important parts of developing a map based application. This REST API calculates driving routes between specified locations including via points based on route type(fastest or shortest), includes delays for traffic congestion , and is capable of handling additional route parameters like: type of roads to avoid, travelling vehicle type etc.
MapmyIndiaDirections.builder()
.origin(startPointLocal)
.steps(true)
.resource(DirectionsCriteria.RESOURCE_ROUTE_ETA)
.profile(DirectionsCriteria.PROFILE_DRIVING)
.overview(DirectionsCriteria.OVERVIEW_FULL)
.destination(endPointLocal)
.build()
.enqueueCall(new Callback<DirectionsResponse>() {
@Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
//handle response
}
@Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
t.printStackTrace();
}
});
MapmyIndiaDirections.builder()
.origin(startPointLocal)
.steps(true)
.resource(DirectionsCriteria.RESOURCE_ROUTE_ETA)
.profile(DirectionsCriteria.PROFILE_DRIVING)
.overview(DirectionsCriteria.OVERVIEW_FULL)
.destination(endPointLocal)
.build()
.enqueueCall(object : Callback<DirectionsResponse> {
override fun onResponse(call: Call<DirectionsResponse>, response: Response<DirectionsResponse>) {
//handle response
}
override fun onFailure(call: Call<DirectionsResponse>, t: Throwable) {
t.printStackTrace()
}
})
Request Parameters
Mandatory Parameter
-
origin(Point): pass the origin point
-
destination(Point): pass the destination point
Optional Parameter
-
profile(String): Below are the available profile:
- DirectionsCriteria.PROFILE_DRIVING (Default):Meant for car routing
- DirectionsCriteria.PROFILE_WALKING: Meant for pedestrian routing. Routing with this profile is restricted to route_adv only. region & rtype request parameters are not supported in pedestrian routing
- DirectionsCriteria.PROFILE_BIKING:Meant for two-wheeler routing. Routing with this profile is restricted to route_adv only. region & rtype request parameters are not supported in two-wheeler routing.
- DirectionsCriteria.PROFILE_TRUCKING:Meant for Truck routing. Routing with this profile is restricted to route_adv only. region & rtype request parameters are not supported in truck routing.
-
resource(String): Below are the available resource:
- DirectionsCriteria.RESOURCE_ROUTE (Default): to calculate a route & its duration without considering traffic conditions.
- DirectionsCriteria.RESOURCE_ROUTE_ETA get the updated duration of a route considering live traffic; Applicable for India only "region=ind" and "rtype=1" is not supported. This is different from route_traffic; since this doesn't search for a route considering traffic, it only applies delays to the default route.
- DirectionsCriteria.RESOURCE_ROUTE_TRAFFIC:
to search for routes considering live traffic; Applicable for India only “region=ind” and “rtype=1” is not supported
-
steps(Boolean):Return route steps for each route leg. Possible values are true/false. By default it will be used as false.
-
overView(String): Add overview geometry either full, simplified according to highest zoom level it could be display on, or not at all. Below are the available value:
- DirectionsCriteria.OVERVIEW_FULL
- DirectionsCriteria.OVERVIEW_FALSE
- DirectionsCriteria.OVERVIEW_SIMPLIFIED
-
excludes(String...): Additive list of road classes to avoid, order does not matter. Below are the available value:
- DirectionsCriteria.EXCLUDE_FERRY
- DirectionsCriteria.EXCLUDE_MOTORWAY
- DirectionsCriteria.EXCLUDE_TOLL
- DirectionsCriteria.EXCLUDE_TUNNEL
- DirectionsCriteria.EXCLUDE_RESTRICTED
-
addWaypoint(Point): pass single waypoint at a time
-
alternatives(Boolean): Search for alternative routes.
-
radiuses(double...): Limits the search to given radius in meters. For all way-points including start and end points.
-
geometries(String): This parameter used to change the route geometry format/density (influences overview and per step).Below are the available value:
- DirectionsCriteria.GEOMETRY_POLYLINE: with 5 digit precision
- DirectionsCriteria.GEOMETRY_POLYLINE6 (Default): with 6 digit precision
Response Codes {as HTTP response code}
Success:
- 200: To denote a successful API call.
- 204: To denote the API was a success but no results were found.
Client-Side Issues:
- 400: Bad Request, User made an error while creating a valid request.
- 401: Unauthorized, Developer’s key is not allowed to send a request with restricted parameters.
- 403: Forbidden, Developer’s key has hit its daily/hourly limit.
Server-Side Issues:
- 500: Internal Server Error, the request caused an error in our systems.
- 503: Service Unavailable, during our maintenance break or server downtimes.
Response Messages (as HTTP response message)
- 200: Success.
- 204: No matches were found for the provided query.
- 400: Something’s just not right with the request.
- 401: Access Denied.
- 403: Services for this key has been suspended due to daily/hourly transactions limit.
- 500: Something went wrong.
- 503: Maintenance Break.
Response Parameters
-
code() (String): if request is successful, response is .ok.. Else, see the service dependent and general status codes. In case of error, .NoRoute. code is supported (in addition to the general ones) which means .no route found..
-
routes()(List<DirectionsRoute>): A list of DirectionsRoute objects, each having potentially multiple via points
-
waypoints()(List<DirectionsWaypoint>): Array of DirectionsWaypoint objects representing all waypoints in order
DirectionsRoute Response result parameters:
-
distance() (Double): The distance travelled by the route; unit is meter.
-
duration() (Double): The estimated travel time; unit is second.
-
geometry() (String): returns the whole geometry of the route as per given parameter .geometries. default is encoded .polyline6. with 6 digit accuracy for positional coordinates.
-
legs() (List<RouteLeg>): The legs between the given waypoints, representing an array of RouteLeg between two waypoints.
Route Leg result parameters:
-
distance() (Double): The distance of travel to the subsequent legs, in meters
-
duration() (Double): The estimated travel time, in seconds
-
steps() (List<LegStep>): Return route steps for each route leg depending upon steps parameter.
LegStep result parameters:
-
distance() (double) :The distance of travel to the subsequent step, in meters
-
duration() (double): The estimated travel time, in seconds
-
geometry() (double): The un-simplified geometry of the route segment, depends on the given geometries parameter.
-
name() (String): The name of the way along which travel proceeds.
-
mode() (String): signifies the mode of transportation; driving as default.
-
maneuver() (StepManeuver): A StepManeuver object representing a maneuver
-
drivingSide() (String): .Left. (default) for India, Sri Lanka, Nepal, Bangladesh & Bhutan.
-
intersections() (List<StepIntersection>): A list of StepIntersection objects that are passed along the segment, the very first belonging to the StepManeuver
StepManeuver result parameters:
-
location()(Point): A Point describing the location of the turn
- bearingBefore() (Double): The clockwise angle from true north to the direction of travel immediately before the maneuver.
- bearingAfter() (Double): The clockwise angle from true north to the direction of travel immediately after the maneuver.
- type() (String): An optional string indicating the direction change of the maneuver.
- modifier() (String): A string indicating the type of maneuver. New identifiers might be introduced without API change. Types unknown to the client should be handled like the .turn. type, the existence of correct modifier values is guaranteed.
StepIntersection result parameters:
-
location() (Point): point describing the location of the turn.
-
bearings() (List<Integer>): A list of bearing values (e.g. [0,90,180,270]) thxat are available at the intersection. The bearings describe all available roads at the intersection.
-
classes() (List<String>): Categorised types of road segments e.g. Motorway
-
entry() (List<Boolean>): A list of entry flags, corresponding in a 1:1 relationship to the bearings. A value of true indicates that the respective road could be entered on a valid route. false indicates that the turn onto the respective road would violate a restriction.
-
in() (Integer): index into bearings/entry array. Used to calculate the bearing just before the turn. Namely, the clockwise angle from true north to the direction of travel immediately before the maneuver/passing the intersection. Bearings are given relative to the intersection. To get the bearing in the direction of driving, the bearing has to be rotated by a value of 180. The value is not supplied for depart maneuvers.
-
out() (Integer): index into the bearings/entry array. Used to extract the bearing just after the turn. Namely, The clockwise angle from true north to the direction of travel immediately after the maneuver/passing the intersection. The value is not supplied for arrive maneuvers.
-
lanes() (List<IntersectionLanes>Array of IntersectionLanes objects that denote the available turn lanes at the intersection. If no lane information is available for an intersection, the lanes property will not be present.):
- valid()(Boolean): verifying lane info.
- indications() (List<String>): Indicating a sign of directions like Straight, Slight Left, Right, etc.
DirectionsWaypoint Response result parameters:
-
name() (String): Name of the street the coordinate snapped to.
-
location() (Point): Point describing the snapped location of the waypoint.
Driving Distance Matrix API
Adding driving directions API would help to add predicted travel time & duration from a given origin point to a number of points. The Driving Distance Matrix API provides driving distance and estimated time to go from a start point to multiple destination points, based on recommended routes from MapmyIndia Maps and traffic flow conditions
Get driving time and distance between a center point and up to 10 destination points using MapmyIndia Maps Distance API.
MapmyIndiaDistanceMatrix.builder()
.profile(DirectionsCriteria.PROFILE_DRIVING)
.resource(DirectionsCriteria.RESOURCE_DISTANCE)
.coordinate(Point.fromLngLat(80.502113, 8.916787))
.coordinate(Point.fromLngLat(28.5505073, 77.2689367))
.build()
.enqueueCall(new Callback<DistanceResponse>() {
@Override
public void onResponse(Call<DistanceResponse> call, Response<DistanceResponse> response) {
//handle response
}
@Override
public void onFailure(Call<DistanceResponse> call, Throwable t) {
t.printStackTrace();
}
});
MapmyIndiaDistanceMatrix.builder()
.profile(DirectionsCriteria.PROFILE_DRIVING)
.resource(DirectionsCriteria.RESOURCE_DISTANCE)
.coordinate(Point.fromLngLat(80.502113, 8.916787))
.coordinate(Point.fromLngLat(28.5505073, 77.2689367))
.build()
.enqueueCall(object : Callback<DistanceResponse> {
override fun onResponse(call: Call<DistanceResponse>, response: Response<DistanceResponse>) {
//handle response
}
override fun onFailure(call: Call<DistanceResponse>, t: Throwable) {
t.printStackTrace()
}
})
Request Parameters
Manadatory Parameter
-
Coordinates(List<Point>): A List full of {@link Point}s which define the points to perform the matrix first location being center location.
Optional Parameter
-
profile(String) : Only supports DirectionsCriteria.PROFILE_DRIVING.
-
resource(Strng): Below are the available value:
- DirectionsCriteria.RESOURCE_DISTANCE (Default): to calculate the route & duration without considering traffic conditions.
- DirectionsCriteria.RESOURCE_DISTANCE_ETA: to get the updated duration considering live traffic; Applicable for India only “region=ind” and “rtype=1” is not supported. This is different from distance_matrix_traffic; since this doesn't search for a route considering traffic, it only applies delays to the default route.
- DirectionsCriteria.RESOURCE_DISTANCE_TRAFFIC: to search for routes considering live traffic; Applicable for India only “region=ind” and “rtype=1” is not supported
Response Code (as HTTP response code)
Success:
- 200: To denote a successful API call.
- 204: To denote the API was a success but no results were found.
Client-Side Issues:
- 400: Bad Request, User made an error while creating a valid request.
- 401: Unauthorized, Developer’s key is not allowed to send a request with restricted parameters.
- 403: Forbidden, Developer’s key has hit its daily/hourly limit.
Server-Side Issues:
- 500: Internal Server Error, the request caused an error in our systems.
- 503: Service Unavailable, during our maintenance break or server downtimes.
Response Messages (as HTTP response message)
- 200: Success.
- 204: No matches were found for the provided query.
- 400: Something’s just not right with the request.
- 401: Access Denied.
- 403: Services for this key has been suspended due to daily/hourly transactions limit.
- 500: Something went wrong.
- 503: Maintenance Break.
Response Parameters
-
responseCode(Long): Response codes of the api.
-
version(String): Version of the Api.
-
results(DistanceResults): Array of results, each consisting of the following parameters
DistanceResults Response Result Parameters
-
code : if the request was successful, code is ok.
-
durations(List<Double[]>): Duration in seconds for source to source (default 0), 1st, 2nd, 3rd secondary locations... from source.
-
distances(List<Double[]>): Distance in meters for source to source (default 0), 1st, 2nd, 3rd secondary locations... from source.
Feedback API
If you want to send feedback for search and selection user made you can use this api and it will improve your search result.
MapmyIndiaFeedback.builder()
.typedKeyword("Map")
.eLoc("mmi000")
.index(1)
.longitude(77.0)
.latitude(28.0)
.userName(userName)
.appVersion(BuildConfig.VERSION_NAME)
.build().enqueueCall(new Callback<Void>() {
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
//Success
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
t.printStackTrace();
}
});
MapmyIndiaFeedback.builder()
.typedKeyword("Map")
.eLoc("mmi000")
.index(1)
.longitude(77.0)
.latitude(28.0)
.userName(userName)
.appVersion(BuildConfig.VERSION_NAME)
.build().enqueueCall(object : Callback<Void?> {
override fun onResponse(call: Call<Void?>, response: Response<Void?>) {
//Success
}
override fun onFailure(call: Call<Void?>, t: Throwable) {
t.printStackTrace()
}
})
Request Parameters
Manadatory Parameter
-
typedKeyword (String) : The string that was searched. Must be 2 characters or more.
-
eLoc (String) : eLoc of the location that was selected. Must be exactly 6 characters.
-
index (Integer) : the index of the selected object that was returned from the search.
-
userName (String) : the username of the user that’s logged in.
-
appVersion (String) : the version of the app that was used to make the request.
Optional Parameter
-
longitude (Double) : the longitude of the location from where the search is made. The longitude must be a double value, must not start with 0.
-
latitude (Double) : the latitude of the location from where the search is made. The latitude must be a double value, must not start with 0 and must not be larger than the longitude.
-
locationName (String ) : name of the location that was selected.
Response Code (as HTTP response code)
Success:
- 201: To denote that the feedback was successfully created.
Client-Side Issues:
- 400: Bad Request, User made an error while creating a valid request.
- 401: Unauthorized, Developer’s key is not allowed to send a request with restricted parameters.
- 403: Forbidden, Developer’s key has hit its daily/hourly limit.
Server-Side Issues:
- 500: Internal Server Error, the request caused an error in our systems.
- 503: Service Unavailable, during our maintenance break or server downtimes.
Response Messages (as HTTP response message)
- 201: Feedback submitted.
- 400: Something’s just not right with the request.
- 401: Access Denied.
- 403: Services for this key has been suspended due to daily/hourly transactions limit.
- 500: Something went wrong.
- 503: Maintenance Break.
Response Parameters
The response of this API would be empty. Success would be denoted by the response codes and error would be denoted with the response codes.
Place Autocomplete Widget
Add PlaceAutocomplete Widget
There are two ways to implement PlaceAutocomplete widget:
- Using PlaceAutocompleteFragment
- Using PlaceAutocompleteActivity
PlaceAutocompleteFragment
Add PlaceAutocompleteFragment in your activity
PlaceAutocompleteFragment placeAutocompleteFragment = PlaceAutocompleteFragment.newInstance();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, placeAutocompleteFragment, PlaceAutocompleteFragment.class.getSimpleName())
.commit();
//OR
PlaceAutocompleteFragment placeAutocompleteFragment = PlaceAutocompleteFragment.newInstance(placeOptions);
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, placeAutocompleteFragment, PlaceAutocompleteFragment.class.getSimpleName())
.commit();
val placeAutocompleteFragment: PlaceAutocompleteFragment = PlaceAutocompleteFragment.newInstance(placeOptions)
supportFragmentManager.beginTransaction().add(R.id.fragment_container, placeAutocompleteFragment, PlaceAutocompleteFragment::class.java.simpleName)
.commit()
//OR
val placeAutocompleteFragment: PlaceAutocompleteFragment = PlaceAutocompleteFragment.newInstance()
supportFragmentManager.beginTransaction().add(R.id.fragment_container, placeAutocompleteFragment, PlaceAutocompleteFragment::class.java.simpleName)
.commit()
You can use PlaceOptions to set the properties of the widget:
-
location(Point): set location around which your search will appear
-
filter(String): this parameter helps you restrict the result either by mentioning a bounded area or to certain eloc (6 digit code to any poi, locality, city, etc.), below mentioned are the both types:
-
filter = bounds: lat1, lng1; lat2, lng2 (latitude, longitude) {e.g. filter("bounds: 28.598882, 77.212407; 28.467375, 77.353513")
-
filter = cop: {eloc} (string) {e.g. filter("cop:YMCZ0J")
-
historyCount(Integer): Maximum number of history results appear
-
zoom(Double): takes the zoom level of the current scope of the map (min: 4, max: 18).
-
saveHistory(Boolean): If it sets to true it shows the history selected data
-
pod(String): 1. it takes in the place type code which helps in restricting the results to certain chosen type.Below mentioned are the codes for the pod
- AutoSuggestCriteria.POD_SUB_LOCALITY
- AutoSuggestCriteria.POD_LOCALITY
- AutoSuggestCriteria.POD_CITY
- AutoSuggestCriteria.POD_VILLAGE
- AutoSuggestCriteria.POD_SUB_DISTRICT
- AutoSuggestCriteria.POD_DISTRICT
- AutoSuggestCriteria.POD_STATE
- AutoSuggestCriteria.POD_SUB_SUB_LOCALITY
-
tokenizeAddress(Boolean): provides the different address attributes in a structured object.
-
backgroundColor(int): to set the background color of the widget
-
toolbarColor(int): to set the toolbar color of the widget.
-
hint(String): To set the hint on the Search view of the widget.
Note: To set the view mode pass PlaceOptions.MODE_FULLSCREEN or PlaceOptions.MODE_CARDS in build(int) method of the PlaceOptions.Builder class
To set the selected place use PlaceSelectionListener interface:
placeAutocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(ELocation eLocation) {
// Select place
}
@Override
public void onCancel() {
//on click of back button
}
});
placeAutocompleteFragment.setOnPlaceSelectedListener(object : PlaceSelectionListener {
override fun onCancel() {
//on click of back button
}
override fun onPlaceSelected(eLocation: ELocation?) {
// Select place
}
})
PlaceAutocompleteActivity
Add PlaceAutocompleteActivity in your activity:
Intent placeAutocomplete = new PlaceAutocomplete.IntentBuilder()
.placeOptions(placeOptions)
.build(this);
startActivityForResult(placeAutocomplete, REQUEST_CODE);
val placeAutocompleteActivity: Intent = PlaceAutocomplete.IntentBuilder()
.placeOptions(placeOptions)
.build(this)
startActivityForResult(placeAutocompleteActivity, REQUEST_CODE)
To get the selected place:
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
if(data != null) {
ELocation eLocation = new Gson().fromJson(data.getStringExtra(PlaceConstants.RETURNING_ELOCATION_DATA), ELocation.class);
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode == REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
val eLocation :ELocation = Gson().fromJson(data?.getStringExtra(PlaceConstants.RETURNING_ELOCATION_DATA), ELocation::class.java)
}
}
}
MapmyIndia Safety Plugin
MapmyIndia Safety Plugin will alert a user who is in or near to a containment zone. If the app is running, a callback method will be called to get the containment zone information. Safety plugin will push a local notification when the user goes near to the containment zone or in a containment zone, which can be seen from the notification panel.
A few extra step you have to follow in order to integrate MapmyIndia Safety Plugin in your application.
Steps to Integrate SDK in an application.
1. Add following lines to your application build.gradle:
dependencies {
classpath 'com.google.gms:google-services:4.3.3'
}
2. Initialize plugin
MapmyIndiaSafetyPlugin
.getInstance()
.initialize(new IAuthListener() {
@Override
public void onSuccess() {
// After successful authentication onSuccess() will be called.
}
@Override
public void onError(String reason, String errorIdentifier, String errorDescription) {
// reason gives the error type.
// errorIdentifier gives information about error code.
// errorDescription gives a message for a particular error.
}
});
MapmyIndiaSafetyPlugin.getInstance().initialize(object : IAuthListener {
override fun onSuccess() {
// After successful authentication onSuccess() will be called.
}
override fun onError(reason: String, errorIdentifier: String, errorDescription: String) {
// reason gives the error type.
// errorIdentifier gives information about error code.
// errorDescription gives a message for a particular error
}
})
3. Start plugin
MapmyIndiaSafetyPlugin
.getInstance()
.startSafetyPlugin(new ISafetyListener() {
@Override
public void onResult(ContainmentZoneInfo zoneInfo) {
// onResult will return a ContainmentZoneInfo object.
//zoneInfo.isInsideContainmentZone() --True if user stays inside the containment zone else false.
//zoneInfo.getDistanceToNearestZone() --Distance in meters to the nearest containment zone.
//zoneInfo.getMapLink() --Map link for containment zone.
//zoneInfo.getDistrictName() --Name of the district.
//zoneInfo.getZoneType() -- District Zone current type like red, orange and green zone.
}
@Override
public void onError(String reason, String errorIdentifier, String errorDescription) {
// reason gives the error type.
// errorIdentifier gives information about error code.
// error description gives a message for a particular error.
}
});
MapmyIndiaSafetyPlugin.getInstance().startSafetyPlugin(object : ISafetyListener {
override fun onResult(zoneInfo: ContainmentZoneInfo) {
//zoneInfo.isInsideContainmentZone --True if user stays inside the containment zone else false.
//zoneInfo.distanceToNearestZone --Distance in meters to the nearest containment zone.
// zoneInfo.mapLink --Map link for containment zone.
//zoneInfo.districtName --Name of the district.
//zoneInfo.zoneType -- District Zone current type like red, orange and green zone.
}
override fun onError(reason: String, errorIdentifier: String, errorDescription: String) {
Timber.e("OnError:" + reason + "errorIdentifier:- " + errorIdentifier)
}
})
4. Stop Safety plugin
MapmyIndiaSafetyPlugin.getInstance().stopSafetyPlugin();
MapmyIndiaSafetyPlugin.getInstance().stopSafetyPlugin();
5. Get Current Location Safety
// Get the corona safety information for the current location by calling following method.
MapmyIndiaSafetyPlugin
.getInstance()
.getCurrentLocationSafety(new ISafetyListener() {
@Override
public void onResult(ContainmentZoneInfo zoneInfo) {
// onResult will return a ContainmentZoneInfo object.
//zoneInfo.isInsideContainmentZone() --True if user stays inside the containment zone else false.
//zoneInfo.getDistanceToNearestZone() --Distance in meters to the nearest containment zone.
//zoneInfo.getMapLink() --Map link for containment zone.
//zoneInfo.getDistrictName() --Name of the district.
//zoneInfo.getZoneType() -- District Zone current type like red, orange and green zone.
}
@Override
public void onError(String reason, String errorIdentifier, String errorDescription) {
// reason gives the error type.
// errorIdentifier gives information about error code.
// error description gives a message for a particular error.
}
});
MapmyIndiaSafetyPlugin.getInstance().getCurrentLocationSafety(object : ISafetyListener {
override fun onResult(zoneInfo: ContainmentZoneInfo) {
// onResult will return a ContainmentZoneInfo object.
//zoneInfo.isInsideContainmentZone --True if user stays inside the containment zone else false.
//zoneInfo.distanceToNearestZone --Distance in meters to the nearest containment zone.
//zoneInfo.mapLink --Map link for containment zone.
//zoneInfo.districtName --Name of the district.
//zoneInfo.zoneType -- District Zone current type like red, orange and green zone.
}
override fun onError(reason: String, errorIdentifier: String, errorDescription: String) {
// reason gives the error type.
// errorIdentifier gives information about error code.
// error description gives a message for a particular error.
}
})
ContainmentZoneInfo Result Parameters:-
-
isInsideContainmentZone (boolean) - True if user stays inside the containment zone else false.
-
containmentZoneName (String)- Name of the containment zone.
-
mapLink (String) - Map link for containment zone.
-
distanceToNearestZone (Long) - Distance to the nearest containment zone.
-
districtName (String) - Name of the district.
-
zoneType (String) - District Zone current type like red, orange and green zone.
Error Description:-
- 204: No matches were found for the provided query.
- 400: Bad request.
- 401: unauthorized request. Access to API is forbidden.
- 500: Something went wrong.
- 503: Maintenance Break
MapmyIndia Interactive Layer Plugin
Introduction
In the current scenario, where social distancing is paramount, technology is playing a key role in maintaining daily communication and information transfer. MapmyIndia is serving individuals, companies and the government alike, to spread critical information related to COVID-19 through deeply informative, useful and free-to-integrate geo-visualized COVID-19 Layers in your application.
Simply plug these easy-to-integrate and COVID-19 Layers into your applications, and offer a seamless information experience to your users.
Get Interactive Layers
To get all interactive layers:
mapmyIndiaMap.getInteractiveLayer(new MapboxMap.InteractiveLayerLoadingListener() {
@Override
public void onLayersLoaded(List<InteractiveLayer> list) {
}
});
mapmyIndiaMap?.getInteractiveLayer(object: MapboxMap.InteractiveLayerLoadingListener {
override fun onLayersLoaded(list: List<InteractiveLayer>?) {
}
})
Show/ Hide Interactive Layers
To show Interactive Layers:
mapmyIndiaMap.showInteractiveLayer(interactiveLayer);
mapmyIndiaMap?.showInteractiveLayer(interactiveLayer)
To hide Interactive Layers:
mapmyIndiaMap.hideInteractiveLayer(interactiveLayer);
mapmyIndiaMap?.hideInteractiveLayer(interactiveLayer)
Enable/ Disable Infowindow
To Enable/Disable info window on click of Interactive Layer
mapmyIndiaMap.showInteractiveLayerInfoWindow(false);
mapmyIndiaMap?.showInteractiveLayerInfoWindow(false)
Get Interactive Layer Details
To get the Interactive Layer Detail when clicked on Layer
mapmyIndiaMap.setOnInteractiveLayerClickListener(new MapboxMap.OnInteractiveLayerClickListener() {
@Override
public void onInteractiveLayerClicked(InteractiveItemDetails interactiveItemDetails) {
}
});
mapmyIndiaMap?.setOnInteractiveLayerClickListener(object : MapboxMap.OnInteractiveLayerClickListener {
override fun onInteractiveLayerClicked(interactiveItemDetails: InteractiveItemDetails?) {
}
})
MapmyIndia GeoFence View
Introduction
A ready to use UI Widget to create/edit GeoFence in an Android application.
Add GeoFence View to your application
You can add GeoFence view in two ways
- Using XML
- Using Java
Using XML
<com.mapmyindia.sdk.geofence.ui.views.GeoFenceView
android:id="@+id/geo_fence_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
We can set the following properties:
-
mapmyIndia_geoFence_circleButtonDrawable: To change the circle Button Drawable
-
mapmyIndia_geoFence_polygonButtonDrawable: To change the polygon selector button drawable
-
mapmyIndia_geoFence_circleFillColor: To change Circle Fill colors
-
mapmyIndia_geoFence_circleFillOutlineColor: To change circle Outline color
-
mapmyIndia_geoFence_circleCenterDrawable: To change the image of the center of circle
-
mapmyIndia_geoFence_handToolDrawable: To change action button icon which is visible when polygon is selected
-
mapmyIndia_geoFence_polygonMidPointDrawable: To change midpoint icon of the polygon boundaries
-
mapmyIndia_geoFence_polygonEdgeDrawable: To change polygon corners icon
-
mapmyIndia_geoFence_polygonIntersectionDrawable: To change polygon intersection point icon of polygon
-
mapmyIndia_geoFence_polygonFillColor: To change fill color of polygon
-
mapmyIndia_geoFence_polygonFillOutlineColor: To change outline color of polygon
-
mapmyIndia_geoFence_seekBarThumbDrawable: To change seekbar thumb icon
-
mapmyIndia_geoFence_seekBarProgressPrimaryColor: To change seekbar Progress bar primary color
-
mapmyIndia_geoFence_seekBarProgressSecondaryColor: To change seekbar Progress bar secondary color
-
mapmyIndia_geoFence_seekBarProgressRadius: To change seekbar corner radius
-
mapmyIndia_geoFence_deleteButtonDrawable: To change drawable of Delete button icon
-
mapmyIndia_geoFence_showSeekbar: If its value is false than it hides the seekbar and if its true than it show seekbar
-
mapmyIndia_geoFence_showToolView: If its value is false than it hides the geofence shape toggle buttons and if its true than it show geofence shape toggle buttons
-
mapmyIndia_geoFence_showActionButton: If its value is false than it hides the polygon draw enable/disable button and if its true than it show polygon draw enable/disable button
-
mapmyIndia_geoFence_showUI: If its value is false than it hide all control buttons and if its true than it show all control buttons
-
mapmyIndia_geoFence_showDeleteButton: If its value is false than it hides polygon delete button.
-
mapmyIndia_geoFence_polygonDrawingBackgroundColor: To change the color of Polygon drawing board color.
-
mapmyIndia_geoFence_showPolygonMidPointIcon: To hide polygon mid points icon
-
mapmyIndia_geoFence_polygonOutlineWidth: To set the polygon outline width
-
mapmyIndia_geoFence_circleOutlineWidth: To change the circle outline width
-
mapmyIndia_geoFence_polygonDrawingLineColor: To set the polygon sketch drawing line.
-
mapmyIndia_geoFence_draggingLineColor: To change the dragging line of Polygon edges and circle radius changing line.
-
mapmyIndia_geoFence_minRadius: To set minimum radius of circle.
-
mapmyIndia_geoFence_maxRadius: To set maximum radius of circle
-
mapmyIndia_geoFence_radiusInterval: To set the step size of radius changing
-
mapmyIndia_geoFence_showPolygonCentreIcon: To show/hide centre point of the Polygon
-
mapmyIndia_geoFence_polygonCentreDrawable: To set the drawable for centre point of the Polygon
Using Java
//To create with default ui and styles
geoFenceView = GeoFenceView(this)
//Or If you want to change the properties of view
geoFenceView = GeoFenceView(this, GeoFenceOptions.builder().showUI(false).build())
GeoFenceOptions has following methods to change the Properties:
-
cicleButtonDrawable(int): To change the circle Button drawable
-
polygonButtonDrawable(int): To change the polygon selector button drawable
-
circleFillColor(int): To change Circle Fill colors
-
circleFillOutlineColor(int): To change circle Outline color
-
circleCentreDrawable(int): To change the image of the center of circle
-
actionButtonDrawable(int): To change action button icon which is visible when polygon is selected
-
polygonMidPointDrawable(int): To change midpoint icon of the polygon boundaries
-
polygonEdgeDrawable(int): To change polygon corners icon
-
polygonIntersectionDrawable(int): To change polygon intersection point icon of polygon
-
polygonFillColor(int): To change fill color of polygon
-
polygonFillOutlineColor(int): To change outline color of polygon
-
seekbarThumbDrawable(int): To change seekbar thumb icon
-
seekbarPrimaryColor(int): To change seekbar Progress bar primary color
-
seekbarSecondaryColor(int): To change seekbar Progress bar secondary color
-
seekbarCornerRadius(int): To change seekbar corner radius
-
deleteButtonDrawable(int): To change drawable of Delete button icon
-
showSeekBar(boolean): If its value is false than it hides the seekbar and if its true than it show seekbar
-
showToolsButton(boolean): If its value is false than it hides the geofence shape toggle buttons and if its true than it show geofence shape toggle buttons
-
showActionButton(boolean): If its value is false than it hides the polygon draw enable/disable button and if its true than it show polygon draw enable/disable button
-
showUI(boolean): If its value is false than it hide all control buttons and if its true than it show all control buttons
-
showDeleteButton(boolean): If its value is false than it hides polygon delete button
-
polygonDrawingBackgroundColor(int): To change the color of Polygon drawing board color
-
showPolygonMidPointIcon(boolean): To hide polygon mid points icon
-
polygonOutlineWidth(Float): To set the polygon outline width
-
circleOutlineWidth(Float): To change the circle outline width
-
polygonDrawingLineColor(int): To set the polygon sketch drawing line
-
draggingLineColor(int): To change the dragging line of Polygon edges and circle radius changing line
-
minRadius(int): To set minimum radius of circle
-
maxRadius(int): To set maximum radius of circle
-
radiusInterval(int): To set the step size of radius changing
-
showPolygonCentreIcon(boolean): To show/hide centre point of the Polygon
-
polygonCentreDrawable(int): To set the drawable for centre point of the Polygon
Initialise geofence view
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
geoFenceView = findViewById<GeoFenceView>(R.id.geo_fence_view)
geoFenceView.onCreate(savedInstanceState)
geoFenceView.setGeoFenceViewCallback(this)
val geoFence = GeoFence()
geoFence.isPolygon = false
geoFence.circleCenter = LatLng(25.4358, 81.8463)
geoFence.circleRadius = 200
geoFenceView.geoFence = geoFence
}
override fun onResume() {
super.onResume()
geoFenceView.onResume()
}
override fun onStop() {
super.onStop()
geoFenceView.onStop()
}
override fun onStart() {
super.onStart()
geoFenceView.onStart()
}
override fun onLowMemory() {
super.onLowMemory()
geoFenceView.onLowMemory()
}
override fun onDestroy() {
super.onDestroy()
geoFenceView.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
geoFenceView.onSaveInstanceState(outState)
}
Callbacks getting from GeoFence View
Implement from GeoFenceViewCallback interface
-
void onGeoFenceReady(MapboxMap mapmyIndiaMap): When map is loaded successfully
-
void geoFenceType(boolean polygon): When toggle between geofence type
-
void onCircleRadiusChanging(int radius): When radius of the circle changes
-
void onUpdateGeoFence(GeoFence geoFence): On update geofence data
-
void hasIntersectionPoints(): When Polygon is intersecting
To change the circle Radius
On circle radius changing:
geoFenceView.onRadiusChange(progress)
On circle radius change finish
geoFenceView.radiusChangeFinish(seekBar?.progress!!)
Toggle draw polygon enable/disable
geoFenceView.enablePolygonDrawing(isChecked)
Toggle Geofence type
To draw circle Geofence
geoFenceView.drawCircleGeoFence()
To draw polygon Geofence
geoFenceView.drawPolygonGeofence()
Restrict number of points in a polygon
geofenceView.setMaxAllowedEdgesInAPolygon(12);
Callback when user tries to add more than restricted points in a polygon
geoFenceView.setOnPolygonReachedMaxPointListener(new OnPolygonReachedMaxPointListener() {
@Override
public void onReachedMaxPoint() {
//show a message to the user
}
})
Auto correct self intersecting polygon
geofenceView.simplifyWhenIntersectingPolygonDetected(true);
get center of plotted polygon
geofence.getPolygonCentre()
get Polygon points in clockwise/anti-clockwise directions
geoFenceView.convertPointsToClockWise(Orientation.CLOCKWISE);
To set Camera Padding for zoom on change geofence
geoFenceView.setCameraPadding(left, top, right, bottom);
To disable zoom on change geofence
geoFenceView.shouldAllowAutoZoom(false)