MapmyIndia Map Android SDK

Getting Started

It is recommended that you use Android Studio as your IDE for development. MapmyIndia Maps SDK for Android supports Android API version 10 and above. You can have a look at the map and features you will get in your own app by using the MapmyIndia Maps app for Android. The SDK handles map tiles download 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 plans 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
  • Copy the SDK jar file to project libs/ folder
  • Add the following permissions to your AndroidManifest.xml file
  • Add Gson library to your project: "compile 'com.google.code.gson:gson:2.3'"
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  • Add your API keys to the SDK
Make the following function calls in the Application Class -
LicenceManager.getInstance().setRestAPIKey("your_rest_api_key");
LicenceManager.getInstance().setMapSDKKey("your_java_script_key");
public class DemoApplication extends Application {

   @Override
   public void onCreate() {
       super.onCreate();
       LicenceManager.getInstance().setRestAPIKey("your_rest_api_key");
       LicenceManager.getInstance().setMapSDKKey("your_java_script_key");
   }
}
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

Follow these steps to load a MapmyIndia Map in your project –

  • Layout
    Create main.xml layout as res/layout/main.xml so it has com.mmi.MapmyIndiaMapView element:
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="match_parent" 
android:layout_height="match_parent">
<com.mmi.MapmyIndiaMapView
android:id="@+id/map" 
android:layout_width="match_parent" 
android:layout_height="match_parent" />
</LinearLayout>
  • Create the main activity (MainActivity.java):
public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
//Add a Map View to your XML layout
       MapmyIndiaMapView  mapMyIndiaMapView = (MapmyIndiaMapView)  findViewById(R.id.map);
        MapView mMapView = mapMyIndiaMapView.getMapView();


      //if you want to create map view Instance D dynamically 
       MapmyIndiaMapView  mapMyIndiaMapView = new MapmyIndiaMapView (this);
       MapView mMapView = mapMyIndiaMapView.getMapView();
 setContentView(mapMyIndiaMapView);
    }

}

If you want to use MapView with Fragment, use the following

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Dynamically
MapmyIndiaMapView mapmyIndiaMapView=new MapmyIndiaMapView(inflater.getContext());

MapView mMapView =mapmyIndiaMapView.getMapView();

return mapmyIndiaMapView;

//from layout

View view = inflater.inflate(R.layout.mapview, container, false);
MapView mMapView = ((MapmyIndiaMapView) view.findViewById(R.id.mapview)).getMapView();
return view;
}
  • Set Map Center
GeoPoint geoPoint= new GeoPoint(48.8583, 2,2944);
mMapView.setCenter(geoPoint);

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 zoom to change zoom level as well as double tap to zoom in.
You can disable zoom gestures by calling mMapView.setMultiTouchControls(false). This is independent of calling mMapView.setZoomLevel(int) to zoom in or out.

mMapView.setMapListener(new MapListener() {
    @Override
    public boolean onScroll(ScrollEvent event) {
                return false;
    }   @Override
public boolean onZoom(ZoomEvent event) {  
//this method captures the zoom event by the user.
return false;
} });

Current Location

Get the current user location using the GpsLocationProvider class.

UserLocationOverlay mLocationOverlay;
this.mLocationOverlay = new UserLocationOverlay(new GpsLocationProvider(getActivity()), mMapView);
mLocationOverlay.setCurrentLocationResId(R.drawable.ic_launcher);
mLocationOverlay.enableMyLocation();
mMapView.getOverlays().add(this.mLocationOverlay);
mMapView.invalidate();

Scroll Events

The map can be panned by simply dragging it around with a finger.

mMapView.setMapListener(new MapListener() {
    @Override
    public boolean onScroll(ScrollEvent event) {
//this method captures the on scroll event. 
         return false;
    }     @Override
public boolean onZoom(ZoomEvent event) {  
//this method captures the zoom event 
return false;
} });

Map Events

The SDK allows you to listen to certain events on the map. For example-

Zoom and Scroll Events

mMapView.setMapListener(new MapListener() {
    @Override
    public boolean onScroll(ScrollEvent event) {
                return false;
    }

    @Override
    public boolean onZoom(ZoomEvent event) {  
//this method captures the zoom event by the user.
        return false;
    }
});

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 –

MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(getActivity(), new MapEventsReceiver(){
  @Override
  public boolean singleTapConfirmedHelper(GeoPoint p) {
      return true;
  }
  @Override
  public boolean longPressHelper(GeoPoint p) {
      return true;
  }
});
mMapView.getOverlays().add(mapEventsOverlay);
mMapView.invalidate();

Map Overlays

The code samples that are part of the SDK detail out the usage of all the following features. It’s recommended that you browse the samples before integrating the SDK with your project. Feel free to reuse the code in the samples for your application.

Markers

Add a Marker

Add markers to the map by following these steps –

import com.mmi.layers.Marker;
Marker marker= new Marker(mMapView);
marker.setPosition(geoPoint);
marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
mMapView.getOverlays().add(marker);
mMapView.invalidate();

Remove a Marker

marker.remove(mMapView);

Customize a Marker

BasicInfoWindow infoWindow = new BasicInfoWindow(R.layout.tooltip, mMapView);
//infowindow gets displayed when you click on the marker.
infoWindow.setTipColor(getResources().getColor(R.color.base_color));
Marker marker = new Marker(mMapView);
marker.setTitle("Title(if any)");
marker.setDescription("Description(if any)");
marker.setSubDescription("Sub-Description(if any)");

Change default marker icon

marker.setIcon(R.drawable.yourIcon);

Marker Opacity

marker.setAlpha(float);

Info Windows

Add an info window that opens after a marker tap with the following lines of code –

BasicInfoWindow infoWindow = new BasicInfoWindow(R.layout.tooltip, mMapView); 
infoWindow.setTipColor(getResources().getColor(R.color.base_color)); 
Marker marker = new Marker(mMapView); 
marker.setTitle(title); 
marker.setDescription(description); 
marker.setSubDescription(subdescription); 
marker.setPosition(geoPoint); 
marker.setInfoWindow(infoWindow); 
mMapView.getOverlays().add(marker);
mMapView.invalidate();

Tooltips

You can customize the default tooltip by editing the tooltip.xml file in the layout folder of demo app or by copying the code snippet below. Do not change the ID values.

tooltip.xml

<?xml version="1.0" encoding="UTF-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
    android:orientation="vertical">

   <LinearLayout
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:background="@color/base_color"
       android:orientation="vertical"
       android:padding="5dp">

       <TextView
           android:id="@+id/tooltip_title"
           android:layout_width="wrap_content"
           android:layout_height="0dp"
           android:layout_gravity="left"
           android:layout_weight="1"
           android:maxEms="17"
           android:textColor="@android:color/white"
           android:textSize="18sp" />

       <TextView
           android:id="@+id/tooltip_description"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:maxEms="17"
           android:textColor="@android:color/white"
           android:textSize="14sp"
           android:visibility="gone" />

       <TextView
           android:id="@+id/tooltip_sub_description"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:maxEms="17"
           android:textColor="@android:color/white"
           android:textSize="12sp"
      />

   </LinearLayout>

   <com.mmi.view.TipView
       android:id="@+id/tip_view"
       android:layout_width="fill_parent"
       android:layout_height="10dp" />
       </LinearLayout>

Marker Clustering

Add a cluster of markers that automatically expands and collapses using the following code –

MarkerClusterer markerClusterer = new MarkerClusterer(getActivity()); 
markerClusterer.setColor(getResources().getColor(R.color.green_color)); 
markerClusterer.mAnchorV = Marker.ANCHOR_CENTER; 
markerClusterer.mTextAnchorV = Marker.ANCHOR_CENTER; 
markerClusterer.setTextSize(12); 
ArrayList<GeoPoint> points = new ArrayList<>(); 
for (MarkerModel markerModel : markerModels) {//for MarkerModel please refer demo application 
  Marker marker = new Marker(mMapView); 
  marker.setTitle(markerModel.getTitle()); 
  marker.setDescription(markerModel.getDescription()); 
  marker.setIcon(getResources().getDrawable(R.drawable.marker_selected)); 
  marker.setPosition(markerModel.getGeoPoint()); 
 
 marker.setInfoWindow(null);// in case you dont want anything to get displayed when marker tapped 
  marker.setRelatedObject(markerModel); 
  markerClusterer.add(marker); 
  points.add(markerModel.getGeoPoint()); 
} 
mMapView.setBounds(points); 
mMapView.getOverlays().add(markerClusterer);
mMapView.invalidate();

Polylines

Add a Polyline

You can draw polylines to represent routes and other contiguous straight lines on the map

ArrayList geoPoints = new ArrayList<>();
PathOverlay pathOverlay = new PathOverlay(getActivity()); 
pathOverlay.setColor(getResources().getColor(R.color.base_color)); 
pathOverlay.setWidth(10); 
pathOverlay.setPoints(geoPoints); 
mMapView.getOverlays().add(pathOverlay);
mMapView.invalidate();

Remove a Polyline

mMapView.getOverlays().remove(pathOverlay);

Customize a Polyline

pathOverlay.setDescription("hi polyline");
pathOverlay.setTitle("set_title");
pathOverlay.setSubDescription("set_subDescription");
pathOverlay.setInfoWindow(yourInfoWindow);
pathOverlay.setImageUrl("Urlstring");

Polygons

Add a Polygon

Polygon polygon = new Polygon(getActivity());
polygon.setPoints(geoPoints);
polygon.setFillColor(Color.BLUE);
mMapView.getOverlays().add(polygon);
mMapView.invalidate();

Search

External libraries

Accessing the search functions in MapmyIndia Map SDK requires Google's GSON library. You must include it as a dependency.

Proguard

Using proguard? You must include following lines in proguard configuration file if you are using search functions in SDK.

-keepattributes Signature
-keepattributes *Annotation*
-keepattributes EnclosingMethod
-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.stream.** { *; }


-keep class com.mmi.apis.distance.** {
    <fields>;
    <methods>;
}

-keep class com.mmi.apis.place.geocoder.** {
    <fields>;
    <methods>;
}

-keep class com.mmi.apis.place.reversegeocode.** {
    <fields>;
    <methods>;
}

-keep class com.mmi.apis.place.** {
    <fields>;
    <methods>;
}



-keep class com.mmi.apis.routing.** {
    <fields>;
    <methods>;
}
-keep class com.mmi.apis.place.autosuggest.** {
    <fields>;
    <methods>;
}
-keep class com.mmi.apis.place.details.** {
    <fields>;
    <methods>;
}
-keep class com.mmi.apis.place.nearby.** {
    <fields>;
    <methods>;
}

The following search services are available as part of the SDK bundled by default –

Geocoding

You can read more on MapmyIndia’s Geocoding API here. To geocode an address, create an instance of GeocodeManager class and call the getPlace method –

GeocodeManager geocodeManager=new GeocodeManager();
geocodeManager.getPlace(searchText, new GeocodeListener() {
   @Override
   public void onResult(int code, ArrayList<Place> places) {
                    //code:0 success, 1 exception, 2 no result
                  // list of places in response to given search String


   }
});

Reverse Geocoding

You can find address for a point on the map by using the MapmyIndia Maps Reverse Geocoding API. Pass the GeoPoint to the ReverseGeocodeManager class –

ReverseGeocodeManager  reverseGeocodeManager=new ReverseGeocodeManager().;
reverseGeocodeManager getPlace(geoPoint, new ReverseGeocodeListener() {
   @Override
   public void onResult(int code, Place place) {
        //code:0 success, 1 exception, 2 no result
      // place in response to given GeoPoint

   }
});

Driving Directions

Use the MapmyIndia Maps Routing API to get driving directions between any two places in India including multiple via points.

DirectionManager  directionManager =new DirectionManager().;
//Set Type of Route
public void setRouteType(RouteType routeType) 
- RouteType.QUICKEST (default) 

-  RouteType.SHORTEST

//Avoid Tolls, Ferries etc.
public void setAvoid(Avoid avoid) 
- Avoid.TOLL_ROADS (default) 
-  Avoid.FERRIES
-  Avoid.UNPAVED_ROADS
-  Avoid.HIGHWAYS

//Select Vehicle Type
public void setVehicleType(VehicleType vehicleType)
VehicleType.PASSENGER
VehicleType.TAXI

//Get Alternate Routes. Applicable only if no via point is selected
public void setAllowedAlternate(boolean allowedAlternate)

//Get full text advice for the route
public void setAdvises(Advises mAdvises)
Advises.YES
Advises.NO (default)

//Get Route
directionManager getDirections(startPoint, endPoint, viaPoints, new DirectionListener() {
   @Override
   public void onResult(int code, final ArrayList<Trip> trips) {
       
 //code:0 success, 1 exception, 2 no result
     // array of Trip class. a trip represents a Route

       }
   
});

Distance

Get driving time and distance between a center point and up to 10 destination points using MapmyIndia Maps Distance API.

DistanceManager  distanceManager =new DistanceManager();


//Get distance
 distanceManager.getDistance(centerPoint, points, new DirectionListener() {
   @Override
   public void onResult(int code, final ArrayList<Distance> distances) {
       
        //code:0 success, 1 exception, 2 no result

     // distances : arrayList of Distance data

       }
   
});

DistanceManager class provides three methods-

To set type of route

public void setRouteType(RouteType routeType)
//Possible input
RouteType.QUICKEST (default)
RouteType.SHORTEST

If user wants to avoid toll, ferries etc.

public void setAvoid(Avoid avoid
//Possible input
Avoid.TOLL_ROADS (default) 
Avoid.FERRIES
Avoid.UNPAVED_ROADS 
Avoid.HIGHWAYS

Select Vehicle type for travel -

public void setVehicleType(VehicleType vehicleType)
//Possible input
VehicleType.PASSENGER
VehicleType.TAXI

Nearby Places​

To find nearby places to a point, create an instance of NearbyManager class and call the getNearbyPlaces method with your search criteria

NearbyManager nearbyManager = new NearbyManager();
nearbyManager.getNearbyPlaces(category, keywords, point, 1, new NearbyListener() {
@Override
 public void onResult(int code, final ArrayList places) {
  //code:0 success, 1 exception, 2 no result
   // list of places in response to given search criteria
  }
   });

Place Details​

To get suggestion on a given string, create an instance of AutoSuggestManager class and call the getSuggestions method with your search string

AutoSuggestManager autoSuggestManager =new AutoSuggestManager();
autoSuggestManager.getSuggestions(searchText, new AutoSuggestListener() {
@Override
  public void onResult(int code, ArrayList places) {
   //code:0 success, 1 exception, 2 no result
   // response in array of AutoSuggest class
  }
   },true);

​AutoSuggest

To find nearby places to a point, create an instance of NearbyManager class and call the getNearbyPlaces method with your search criteria

NearbyManager nearbyManager = new NearbyManager();
nearbyManager.getNearbyPlaces(category, keywords, point, 1, new NearbyListener() {
@Override
 public void onResult(int code, final ArrayList places) {
  //code:0 success, 1 exception, 2 no result
   // list of places in response to given search criteria
  }
   });

MapmyIndia Beacon

MapmyIndia Beacon SDK is primarily used for developing location-aware applications. This will help the user to review where your device has been. Location send frequency in the Beacon SDK depends on the selected profile.
3 different pre-defined profiles are :

  1. Vehicle : Very frequent polling i.e. in every 5 seconds.
  2. People : Relaxed polling i.e. in every 15 minutes or 900 seconds.
  3. Hybrid : Mixed polling i.e. in every 5 minutes or 300 seconds.

Please note, use of the profiles depends upon the desired requirement. For example if distance needs to be measured, then suggested profile is vehicle. Although due to frequent GPS and GPRS use, battery of the device may drain out quicker in vehicle profile.

Getting Started

It is recommended that you use Android Studio as your IDE for development. MapmyIndia Beacon SDK for Android supports Android API version 10 and above. You can send location information from your app by using the MapmyIndia Beacon SDK. The SDK provides control features in terms starting and stopping the Beacon service.

MapmyIndia Intouch API key can be obtained from your API dashboard. This key will enable you to access different components of Beacon SDK.

Note : Beacon SDK will work on those devices which have GSM module i.e a valid IMEI number.

Data Management​

Currently if the location module of the device is not able to get any location from GPS or Cell network then no position is reported from the device.

API Usage​

Your MapmyIndia Beacon SDK usage needs a set of license keys and is governed by the API terms and conditions.

Setup your project:
Follow these steps to add the SDK to your project –
  • Create a new project in Android Studio
  • Copy the SDK jar file to project libs/ folder
  • Add the following permissions to your AndroidManifest.xml file.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

and following in application tag

<service android:name="com.mmi.beacon.service.BeaconTrackerService"/>
<receiver android:name="com.mmi.beacon.receiver.NetworkChangeReceiver" />
<intent-filter/>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="com.mmi.beacon.LOGGER"/>
 <action android:name="android.intent.action.BOOT_COMPLETED" />
 <action android:name="android.intent.action.QUICKBOOT_POWERON" />
 <intent-filter/>
 <receiver/>

Add your API keys to the SDK
Make the following function calls in the Application Class -

LicenceManager.getInstance().setMapmyIndiaBeaconToken(Your_token);
public class DemoApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
LicenceManager.getInstance().setMapmyIndiaBeaconToken(Your_token);
}
}

Note: You should not use the MapmyIndia Beacon SDK without these function calls. You will find your keys in your API Dashboard.

Class: MapmyIndiaBeacon
Steps to integrate:

1. Need to register device with “RegisterDeviceListener”

MapmyIndiaBeacon.getInstance(getActivity()).registerDevice(resultCode,deviceName,listener);

On successful registration you will receive a callback in “onRegistration(trackingCode)”.
If registration is failed,
public void onError(int resultCode, int errorCode, String message)” will be called.
resultCode” is same what you pass while calling “registerDevice”.
List of “errorCode

public static int INTERNET_ERROR = 1001;
public static int INVALID_TOKEN_ERROR = 1002;
public static int DEVICE_NOT_FOUND_ERROR = 1003;
public static int OTHER_ERROR = 1004;

List of “message” for errors.

public static String MSG_INVALID_TOKEN_ERROR = "Invalid token";
public static String MSG_OTHER_ERROR = "Something went wrong";

2. Once successful, user can call “startBeacon” function as follows

MapmyIndiaBeacon.getInstance(getActivity()).startBeacon(MapmyIndiaBeacon.TrackingProfile.PEOPLE);
Possible values of “startBeacon” parameters
MapmyIndiaBeacon.TrackingProfile.PEOPLE
MapmyIndiaBeacon.TrackingProfile.HYBRID
MapmyIndiaBeacon.TrackingProfile.VEHICLE
3. User can call “stopBeacon” function as follows
MapmyIndiaBeacon.getInstance(getActivity()).stopBeacon();