MapmyIndia Interactive Map API

Introduction

The Interactive Maps JavaScript API based on Leaflet JS helps render interactive MapmyIndia Maps that you have used on MapmyIndia Maps on your desktop or mobile browser. Leaflet is the leading open-source JavaScript library for mobile-friendly interactive maps. Weighing just about 33 KB of JS, it has all the mapping features most developers ever need. MapmyIndia Interactive Map API is designed with simplicity, performance and usability in mind. It is a collection of classes and functions that can be used to implement a host of map features, broadly described here under:

Features:
  • Zoom: Pan-able map of India with 14 zoom levels, 18 being the highest (most detailed) and 4 being the lowest (country level) map display.
  • Overlays: The map is the key for any sort of transit and understanding this, we at MapmyIndia provide quick default overlays to reduce the boiler plate code for your code base.
    • Map Markers (Pushpins): Point to any location using default pushpin behaviours and provide it your own style to make it look more tailored for your application. Note: Have a look at the Plug-ins section to find out what makes it cooler.
    • Info Windows (Pop-ups): On a Map Clicking is a native behaviour understanding this, we provide out of the box info windows such that if a pushpin is clicked an info window pops up open and you can show your content related to that location there. You can style it to make it behave as required for your UI to be magnificent.
    • Polylines: Connect any two points or even more with out of the box MapmyIndia polylines dedicated to high customizability and performance to suit your use cases. Note: Have a look at the plug-ins we provide to make your polylines have an edge up and suit your use cases in a more integrated manner.
    • Polygons: Show a region in a spotlight with a polygon and show various localized data based on it.
    • Circles: Show instant radial areas of inter
  • Controls: because we understand the use cases with a map we provide the below out of the box controls that can be turned off or on based on your requirement and because we care, we provide you to override our controls outlook by providing your own styles or CSS so that you can move them or customize them completely. Controls include:
    • Zoom Bar: (appears by default at the centre on the right side). Helps to provide zoom in and zoom out functionality to the map by default.
    • Map Layer Control: Allows to change the map view from Road to hybrid and visive. Also allows to show traffic layer on map.
    • Current Location Control: Scopes the Map to the viewer’s current location.
      Note:
      The location settings must be turned on and must allow the site to fetch the location for this control to work.
    • The Search Control: With MapmyIndia’s interactive map API you get MapmyIndia quick search built in out of the box. The search control is placed in the top left corner by default although you can style it or move it as per your UI. This control provides quick search via a name, address, eLoc (or Place_Id) with built in autosuggest.

Please Note: MapmyIndia may extend and enhance functionality for its interactive map API in future, which will be clearly documented in this section, and which will be available through the MapmyIndia.Map class and MapmyIndia.* set of classes generally.

Getting Started

Now that you’re all caught up with the features let’s get down right to them and look at how can you integrate our Interactive Map to your Website from scratch.

Initializing the Map

The easiest way to start loading maps in a web page is with a “Hello World” sample code, you can download or view a working “Hello World” sample from the links above:

Follow the below steps to integrate MapmyIndia interactive Maps into your existing code base or even a File -> New Project.

  • Declare application as HTML5:
define <!DOCTYPE html> on top of your HTML.
  • Integrate India's best interactive maps from MapmyIndia into your browser application by simply including MapmyIndia's interactive map API in your script source in the head section.
<script src="https://apis.mapmyindia.com/advancedmaps/v1/{your API key}/map_load?v=01."></script>
  • Define a style in the head section to load in your CSS.
<style> html, body, #map {margin: 0;padding: 0;width: 100%;height: 100%;} </style>
  • Define a div object in the body tag of the HTML where you want the MapmyIndia Map to show up.
<div id="map"></div>;
  • Initialize a MapmyIndia Map by simply calling new MapmyIndia.Map() in the JavaScript and passing it at the minimum, the div object in which you want the map populated. (All other parameters are optional.)
var map=new MapmyIndia.Map("map",{ center:[28.61, 77.23],zoomControl: true,hybrid:true });
  • Load the map.

Adding Your First Marker

The easiest way to start loading maps in a web page is with a “Hello World” sample code, you can download or view a working “Hello World” sample from the links above:

The true hello world in case of a map scenario is plotting a pushpin that says hello world on click. So, to add a marker to the map, simply add the line of code below to the JavaScript:

L.marker([28.61, 77.23]).addTo(map);

Where,
L is the global Leaflet singleton (class/object),
28.61, 77.23 is the latitude and longitude of the location of the pushpin aka marker,
map is the defined global instance of the initialized MapmyIndia interactive Map.

Please Note: -Once you initialize a MapmyIndia Map, you can access all Leaflet functionalities through the, 'L' and passing it the 'map' variable to initialize the leaflet into
- MapmyIndia Map. More documentation on Leaflet and plugins are available at leafletjs.org.
*All Leaflet functionality will work with MapmyIndia Interactive Map API. - The code shown will display a map centred on New Delhi, India. You need to obtain an API key by signing up for API usage to view a demo or use the sample code.


Knowing Properties and Functions

You can interact with properties of the Map we provide to suite your case scenarios and add additional customizability to your Map layer and the features it may have to offer on the flipside, functions are a quick go to in case of an event. We’ll talk about events in just a bit. So, let’s get down right to them,

In the JavaScript of Map Initialization section of getting started you would have seen

var map=new MapmyIndia.Map("map",{ center:[28.61, 77.23],zoomControl: true,hybrid:true });

In the above code the center, zoomControl and hybrid are map properties. You can handle your Map Viewing mode using these properties.

Functions on the other hand help to provide desired results for the Map. Below is the Table of some common methods you might need to know to get a jump start on things while working with Interactive Maps.

S.No Function Name Action Returns
1 getZoom() Returns the current zoom level of the map view Number
2 getCenter() Returns the geographical center of the map view LatLng
3 panTo(<LatLng> latlng, <Pan options> options?) Pans the map to a given center. -
4 setView(LatLng latlng) Sets the view of the Map to the provided Point -
5 fitBounds(latLngBounds bounds) Scopes the Map to provided bounds -
6 zoomIn() Zooms in the Map -
7 zoomOut() Zooms out the Map -
8 setZoom() Sets the Zoom level of the Map -
9 getBounds() Gets the Bounds of the current viewing section of the Map LatLngBounds

So, in a joist, map functions like normal programming language functions provide a way or a procedure to get interact with Map and provide with substantial data.

Now that we know a little bit about properties and functions and how they interact let’s look at events and how do they fit in to this picture that will allow you to get the desired result.

Using Events

Events are basically Call-backs provided by UI elements or your own custom code base that tell you that something needs to be done. The most commonly used events or Call-backs are as below:

S.No Event Name Type of Event When is it Fired
1 resize  ResizeEvent Fired when the map is resized.
2 load  Event Fired when the map is initialized (when its center and zoom are set for the first time).
3 zoom  Event Fired repeatedly during any change in zoom level, including zoom and fly animations.
4 move  Event Fired repeatedly during any movement of the map, including pan and fly animations.
5 click  MouseEvent Fired when the user clicks (or taps) the map.
6 dblclick  MouseEvent Fired when the user double-clicks (or double-taps) the map.
7 mousedown  MouseEvent Fired when the user pushes the mouse button on the map.
8 mouseup  MouseEvent Fired when the user releases the mouse button on the map.
9 mouseover  MouseEvent Fired when the mouse enters the map.
10 mouseout  MouseEvent Fired when the mouse leaves the map.
11 contextmenu MouseEvent Fired when the user pushes the right mouse button on the map, prevents default browser context menu from showing if there are listeners on this event. Also, fired on mobile when the user holds a single touch for a second (also called long press).
12 keypress  KeyboardEvent Fired when the user presses a key from the keyboard while the map is focused.

Please Note: The above-mentioned events are just a small portion of the all supported events, but to get a jump start at things we think these would get you a long way without losing the sight of your final goal.
For more information on events and the list of all the events supported you can have a quick look at the events supported by leaflets in the leaflet documentations and we support all features and functions provided by leaflet.

That being said, let’s have a quick look on how to handle events for a mouse click. Let’s get started:
So after Map Initialization in your JavaScript code, (the map variable if following the getting started sample) you need to register for a click event of the map to listen or get a call-back each time the event happens. To do so add the below code to your JavaScript code:

map.on("click", function (e) { var pt = e.latlng; //event returns lat lng of clicked point //Do your related operation here });

As from the above code,
-map is the global variable of the initialized map. See the Initializing of the Map section in the Getting Started Module for more details.
-click is the name of the event we want to register to, to subscribe to other events simply replace the click with any other event name from the above table or the leaflet documentation.
-e are the arguments that are passed in to the event which contain information regarding the event. In this case, it contains the Latitude and Longitude of the point on map that was clicked

For a detailed implementation of events and them interacting with the properties and functions have a look at the sample code or a demo or even download a sample code from the links above.

Now that you’re all started up, next we’ll have a look at things from a more functionality point of view.

Overlays and Controls

We’ve got you up to speed with all the basics you might be needing to implement your own Interactive Map leveraging MapmyIndia’s Interactive Map API. Now let’s look at what all can you add on to your interactive map to make it tailor made for your use cases.

Markers

Markers are effortless way of pointing to a location, so getting right to it, you can go ahead and add markers that we provide out of the box but just in case you want to add your own, we’ve got that covered for you as well. There are 3 main categories of markers that you can add namely,
- Stock Marker: The one you get out of the box using our interactive maps API and you can select from a lot of choices.
- Custom Marker: Just in case you want to provide your own markers, we’ve handled that for you as well.
- HTML Marker: In case you don’t want to add in an image you can use HTML to create a marker and then plot it on the map as well.

First, let’s have a look at how to add a stock marker and then we’ll build from there. So, by leveraging the events discussed above let’s try to create a Marker at the dblclick event of the Map, let’s get started:

So after Map initialization as shown above write up a function using the guidelines discussed above to add a single Marker, something like below:

function addMarker(position, title, draggable) { // position must be instance of L.LatLng that replaces current WGS position of this object. Will always return current WGS position. // define a marker with a default icon and optional parameters draggable and title var mk = new L.Marker(position, {draggable: draggable, title: title}); mk.bindPopup(title); //Now let’s add the marker to the Map map.addLayer(mk); //Although we’ll talk about a few things in the code segment in a moment //but let’s put it in here so that you have the full picture. //marker events: mk.on("click", function (e) { //your code about what you want to do on a marker click }); return mk; }

Now that you’ve written the JavaScript code for adding a new Marker let’s call this function in the dblclick event of the Map, something like below:

'map.on("dblclick", function (e) { var title = "Text marker sample!"; marker.push(addMarker(e.latlng, title)); });

where,
marker is a global variable defined in the JavaScript as var marker = [ ]

Also, mk.bindPopup(title); from the code above is for pop-up window or info window, we’ll talk about them in just a moment first let’s wrap this section up

Please Note: The image shows a default Marker with indexing, The indexing is achieved via the CSS you can edit the CSS to make your marker gel with your UI. We’re just covering the basics here, so you’ll have to write your own indexing logic for reference please refer to the code sample provided in the links above but in the CSS you can add something like below:

.map_marker { position:relative;width:34px;height:48px } /*marker text span CSS*/ .my-div-span { position: absolute;left:1.5em;right: 1em;top:1.4em;bottom:2.5em;font-size:9px;font-weight:bold;width:1px;color:black; }

Now, before we move forward let’s quickly look at how to provide your own custom Marker (your own Image).
To do so, you can edit the addMarker() method to take in a custom image location instead of the default as done below:

function addMarker(position, icon, title, draggable) { // position must be instance of L.LatLng that replaces current WGS position of this object. Will always return current WGS position. // define a marker with a default icon and optional parameters draggable and title var mk = new L.Marker(position, { icon: icon, draggable: draggable, title: title}); mk.bindPopup(title); //Now let’s add the marker to the Map map.addLayer(mk); //Although we’ll talk about a few things in the code segment in a moment //but let’s put it in here so that you have the full picture. //marker events: mk.on("click", function (e) { //your code about what you want to do on a marker click }); return mk; }

Please Note: We’ve added the icon field in the parameters and passed it to the L.Marker
You need to now edit the dblclick event as below to pass in a custom marker:

map.on("dblclick", function (e) { var icon = L.icon( { iconUrl: full_path + '/images/MarkerIcon.png', iconRetinaUrl: full_path + '/images/MarkerIcon.png', iconSize: [30, 30], popupAnchor: [-3, -15] }); var title = "Custom marker sample!"; marker.push(addMarker(e.latlng, icon, title)); });

Please Note: We’ve considered some example paths you can put your own.

Now, that you have a basic understanding of Markers, Functions and Events let’s talk about Info Windows or Pop-Ups.


Info Windows

Info Windows are a convenient way of showing data about a marker or in simple words what that marker stands for. The Native behaviour of a user to know about any marker is to try and click on it to know what it’s all about and showing an info window would be the way to go about it:

Please Note: MapmyIndia interactive map supports a default info window that you can leverage but we want you to have an option to customize your info window to fit in with your UI and you can do so in the CSS.

Remember mk.bindPopup(title); from the adding a marker section? Well this quick code snippet binds your info window to your marker so when you click the marker the info window pops open.

We’ll go through the code snippets here and for a quick sample or a demo you can follow up with the links on top. Let’s get down right to it then.

You can declare an info window in your CSS and write up a quick function to generate data in that info window and on marker click event simple open that info window. Sounds simple? Let’s have a look,

var create_content = function (tittle, content) { var h = new Array(); h.push("<div>"); h.push("<div class=\"header\">"); h.push("<span>"); h.push(tittle); h.push("</span> "); h.push("</div>"); h.push("<div class=\"info_css\">"); h.push(content); h.push("</div>"); h.push("</div>"); return h.join(""); };

The above code simply generates an info window based on the tittle and content provided to it by pushing that data to the CSS. The info window is defined in the CSS as below:

.info_css { color:#000;text-decoration:none;background-color:#fff;width:270px;padding:5px;font-size: 12px; } div.header { position:relative;background-color:#191919;color:#fff;line-height:20px;font-size:13px; vertical-align:middle;padding:5px 35px 5px 5px; }

Please Note: The above is the CSS for just the custom info window you can easily customize it by giving it your own CSS. The Default info window does not need any CSS, you can have a quick look at the default info window from the code sample in the links above.

Now that we’ve covered the CSS and the way the info window is generated let see how does that change the code where we define out Marker, Remember the code from Adding a Marker Segment? And mk.bindPopup(title); code snippet?

Now we can replace this by the below code:

var content = create_content("An Info Window", "An example of a richer info window."); mk.bindPopup(content);

and in the mk.click event add the below code:

mk.openPopup();

This will open the info window attached to the marker.

In this section we went through what are info windows, how can we provide our own style to them, how can we modify the existing add a marker code to work with a info windows as well and lastly how to open up an info window on click event.

Info windows are just a small part of what we can use show our data in a map scenario we deal with more routes than textual data. Let’s have a look at polylines that help us to better represent the route data.


Polylines

Polylines are a way of showing movement or transit on a map. We at MapmyIndia understand the ways you can leverage the features offered by a map and one among them is a Polyline. So, let’s get to it.

Polylines are continuous lines consisting of one or more line segments (preferably a geopath). To add a polyline, initialize map as shown in the previous sections and then create a data set. What is a data set? The Data set is the collection of points (latitude and longitude) over which you want the polyline to be drawn. Let’s have a look.

var pts = [ new L.LatLng(center.lat - 150 / 10000, center.lng - 150 / 10000), new L.LatLng(center.lat + 0 / 10000, center.lng - 50 / 10000), new L.LatLng(center.lat + 50 / 10000, center.lng - 100 / 10000), new L.LatLng(center.lat + 70 / 10000, center.lng + 50 / 10000), new L.LatLng(center.lat - 70 / 10000, center.lng + 100 / 10000) ];

Now that we have a small data set ready, let’s get out polyline ready.

var polylineParam = { weight: 4, // The thickness of the polyline opacity: 0.5 //The opacity of the polyline colour };

now let’s generate the polyline

var poly = new L.Polyline(pts1, polylineParam);

Well in the above three code snippets, we’ve generated a data set for the polyline, then defined the basic outlook of the polyline using the polylineParam and then generated a polyline which takes in the data set and the basic outlook of the polyline. Now we’ll just add it to our map.

map.addLayer(poly);

and now you have a working map that shows transit using polylines.

Please Note: We’ve hard coded the data set for the polyline but in real case scenarios you’ll need to get the data set on the fly or from a service and then you can leverage the events and functions we’ve learnt about to plot the polyline. Also, this is a very basic implementation of a polyline you might need to beautify your polyline or add transitions for your UI to look marvellous. Look at the plug-ins section to see about the plug-ins we offer to make your UI stand out.

The polyline is just the beginning but sometimes you’ll need to mark a territory to properly showcase your information. In such cases a polyline might not be the perfect fit but Polygons and Circles will be the apt choice. Let’s have a look at them.

Polygons

Polygons are a way of showing a territory. In cases where you want to showcase data over an area, polygons are your best pick. You can use them to show Geozones as well.

To get started with Polygons initialize the Map as shown in the above sections and then in your JavaScript code follow the below code snippets.

It’s very like generating a polyline, the basic steps remain the same, create a Data set, generate a polygon and add it to the map. Let’s see how:

pts = [ new L.LatLng(centre.lat - 10 / 1000, centre.lng - 10 / 1000), new L.LatLng(centre.lat + 0 / 1000, centre.lng - 10 / 1000), new L.LatLng(centre.lat + 10 / 1000, centre.lng - 20 / 1000), new L.LatLng(centre.lat + 0 / 1000, centre.lng - 20 / 1000), new L.LatLng(centre.lat + 5 / 1000, centre.lng - 5 / 1000), new L.LatLng(centre.lat + 15 / 1000, centre.lng - 15 / 1000), new L.LatLng(centre.lat + 15 / 1000, centre.lng + 15 / 1000), new L.LatLng(centre.lat + 0 / 1000, centre.lng + 0 / 1000), new L.LatLng(centre.lat + 10 / 1000, centre.lng + 20 / 1000), new L.LatLng(centre.lat - 15 / 1000, centre.lng + 20 / 1000), new L.LatLng(centre.lat - 10 / 1000, centre.lng + 0 / 1000) ];

The above code creates a data set of all the points the polygon needs to be marking.

function createPolygon(pts) { p1 = new L.polygon(pts, {color: "green", draggable: true});/**creates a polygon with colour: green*/ //Let’s listen to the click event to show a quick pop up as well. p1.on("click", function (e) { //Binding the popup to the polygon p1.bindPopup("Hello Polygon").openPopup(); }); //Now simply add the polygon to the map. map.addLayer(p1); });

So, from the above code we’ve figured out how to use out of the box controls, events and basic functions to add a polygon to the map. But what if we want the user to interact with the map and draw a polygon himself? Because in real cases we would either get a polygon data from a service or a user would draw it to inform of his area of interest.

To suit this case, we provide a polygon drawer control out of the box through which the user can interact and draw a polygon for himself. Let’s look at how can you use this polygon drawer.

L.NewPolygonControl = L.EditControl.extend ({ options: { position: 'topleft', callback: map.editTools.startPolygon, kind: 'polygon', html: 'Poly' } });

Please Note: You can see a detailed implementation of the control and it’s CSS along with HTML in the code sample we provide from the link on the top or if you want to see it in action you can do so from the see live demo link from the top.

Now that we’ve covered polygons let’s have a look at Circles which provide another way of showcasing territory.

Circles

Circles are way of marking a territory without too much interaction by the user. A circle only has two important values:

  • The Centre point of the circle (in this case it’ll be a latitude with a longitude).
  • The Radius of the circle.

With the two values, you can easily define a quick area of interest on a map. So, let’s take a quick look at it So in your JavaScript code, add a function which looks something like below:

function showCircle() { lat = 28.6129; lon = 77.2311; radius = 500; marker.setLatLng([lat, lon]); currentDiameter = L.circle([lat, lon], { color: 'pink', fillColor: '#FFC0CB', fillOpacity: 0.5, radius: radius }); currentDiameter.addTo(map); map.fitBounds(currentDiameter.getBounds()); }

In the above code, we simply set the radius and the centre point and we define the diameter properties. Then we just add the Diameter to the map.

Please Note: the map.fitBounds(currentDiameter.getBounds()); code snippet just ensures the map is scoped to the circular shape. You might recollect the getBounds() from the functions sections we discussed above.

And that’s all that’s there to it. You have all the basics you need to get started and fiddle around with things to make your own implementation leveraging MapmyIndia’s Interactive Maps API.

It’s not rocket science, right?
These are just the basics of all but to enhance your experience you might just not want the basics. Let’s have a look at the plug-ins we offer to make your users feel amazing and that in turn benefits you.

Plug-Ins

Now that we’ve handled all the basics along with some controls and overlays you can use to better use the map, we would like to show you how can you extend functionalities of these controls and overlays to make your user experience rich.

Plug-Ins are the best way to extend functionality. You can add custom behaviours for controls or make them interact with other components to achieve desired output. Let’s look at the basic implementation of the plug-in or rather how to “Plug-In a Plug-In”.

  • The Centre point of the circle (in this case it’ll be a latitude with a longitude).
  • The Radius of the circle.

With the two values, you can easily define a quick area of interest on a map. So, let’s take a quick look at it So in your JavaScript code, add a function which looks something like below:

Adding a Plug-In

To add any plug in to your project you necessarily need to add a reference to the CSS and the JS files. For each plug-in, the number of these files may vary depending upon the functionality the plug-in provides.

  • The link to the CSS file must be embedded in the <link> tag of your HTML.
  • The link to the JS file must be embedded in the <script> tag of your HTML.

Basic Cluster

The MapmyIndia basic cluster provides basic implementation of the leaflet’s cluster functionality. To set the basic cluster up below is the file composition:

  • CSS Files: the basic cluster uses two CSS files that need to be defined in the <link> tag of the HTML as defined in the adding a plug-in section.
  • JS Files: the basic cluster uses a single JS file that needs to be defined in the <script> tag of the HTML as defined in the adding a plug-in section.

Now that we’ve seen the file structures let’s consider setting up a basic cluster solution leveraging the concepts we’ve learned in the above sections.

Step I: Map Initialization
The basic step for all plug-ins is to have a working MapmyIndia map integrated project. The best part is nothing changes. You set up the map the same way we did before in the getting started section above. So, if you’re following through the documentation from the top you’ve already done it and if not, you too already have a project that’s leveraging the MapmyIndia Interactive Map. Just in case you’ve done a File > New project, then please refer to the getting started section to initialize the map and that shall bring you up to speed.

Step II: Setting up your Data
To plot a cluster, you need a collection of location points (latitudes, longitudes). Without this, one would never be able to plot anything on a map so getting right to it, in the sample code and the live demo, we’ve taken the map bounds to and performed operations on it to generate random points

var bounds = map.getBounds(); var map_sw = bounds.getSouthWest(); var map_ne = bounds.getNorthEast(); var lng_span = map_ne.lng - map_sw.lng; var lat_span = map_ne.lat - map_sw.lat; var markers = [];

and we’ve written up a neat function that provides us with random location points based on the two collections of latitudes and longitudes we’ve defined globally based on the map bounds.

var pt = new L.LatLng(map_sw.lat + Math.random() * lat_span, map_sw.lng + Math.random() * lng_span);

Please Note: In real world case scenarios you’ll probably be getting a collection of latitudes and longitudes from your location or data service that gives you data to be plotted. We’ve taken the above code just to generate random points.

Let’s look at initializing your cluster in the next section.

Step III: Initializing your cluster
So now that we have basic data we’ll create a cluster and pass in the collection of points to which the plug-in will process on and create the cluster for us.

var markerClusters = L.markerClusterGroup({chunkedLoading: true, maxClusterRadius: 100, disableClusteringAtZoom: 26, singleMarkerMode: false, addRegionToolTips: false});

In the above code of cluster initialization let’s look at what are the various properties doing:

  1. chunkedLoading : true (Boolean to split the addLayers processing in to small intervals so that the page does not freeze.)
  2. maxClusterRadius : 100 (The maximum radius that a cluster will cover from the central marker (in pixels). Default 80.)
  3. disableClusteringAtZoom : 16 (markers will not be clustered after the defined zoom level)
  4. singleMarkerMode : false (overrides the icon for all added markers to make them appear as a 1 size cluster.)
  5. addRegionToolTips : false (shows tool tips for regions when mouse hovered)

Step IV: Adding points to the Cluster and Cluster to the Map
Now, we simple pass in the collection of points we get from our data service to our markerClusters as below:

markerClusters.addLayers(markers); //where markers are defined as var markers = [ ]; of location points we created in the last section (pt)

and simple add the cluster layer to the map as below:

map.addLayer(markerClusters);

and that’s it. Now you have your basic cluster initialized and fully loaded.

Please Note: At any time to get the child markers in any cluster do a quick layer.getAllChildMarkers(); to get all child markers contained by a layer. This will return you a collection of markers.

Finally: Going one step further
You know what you can do? You can leverage the knowledge you gained from the above sections and apply it to the plug-in by creating an event to the markerCluster to get more out of your plug-ins. For e.g.

  1. clusterclick event will be raised on click of a cluster
  2. Clustermouseover event will be raised on hover of a mouse.

you can listen to these by defining them like below:

markerClusters.on('clustermouseover', function (a) { event_div.innerHTML = 'This cluster contains '+ a.layer.getAllChildMarkers().length + ' markers; click to view the markers'; });

Also, you can add or remove markers from any cluster if need be. As a matter of fact, you can add or remove an entire cluster layer if your use case scenario is such. To do so, please refer to the code sample provided in the link.

Please Note:
1. We’re just covering the basic implementation here. For a more detailed code snippet and explanation please refer to the code sample or the live demo from the links above.

2. There is a performance criteria attached to this plug-in. If you have less than 25K (25 thousand) markers and a light weight plug-in this will be an ideal pick but just in case there is a possibility that you’ll have more than 25K markers we would advise go for the MapmyIndia’s Advanced Cluster instead. That can handle enormous amount of data and that too with impressive performance. Let’s look at it next.

Advanced Cluster

In the previous section, we looked at a basic cluster implementation. The advantage of it is that is light weight but on the flipside, it’s a very basic implementation and does not provide much customizability and it can’t handle large data sets. To overcome the above, we’ve got Advanced Cluster. Also based on the leaflet implementation, the MapmyIndia Advanced cluster can handle large data sets with impressive performance. Alongside this, the advanced cluster also provides some cool tweaks that can suit your use case scenarios. Let’s go through the implementation.

To set the advanced cluster up below is the file composition:

  • CSS Files: the advanced cluster uses a single CSS files that need to be defined in the <link> tag of the HTML as defined in the adding a plug-in section.
  • JS Files: the advanced cluster uses a single JS file that needs to be defined in the <script> tag of the HTML as defined in the adding a plug-in section.

Now that we’ve seen the file structures let’s consider setting up an advanced cluster solution leveraging the concepts we’ve learned in the above sections.

Step I: Map Initialization
The basic step for all plug-ins is to have a working MapmyIndia map integrated project. The best part is nothing changes. You set up the map the same way we did before in the getting started section above. So, if you’re following through the documentation from the top you’ve already done it and if not, you too already have a project that’s leveraging the MapmyIndia Interactive Map. Just in case you’ve done a File > New project, then please refer to the getting started section to initialize the map and that shall bring you up to speed.

Step II: Initializing your cluster
First, we’ll create a cluster and pass in the collection of points to which the plug-in will process on and create the cluster for us. First things first let’s create a new instance of the PruneClusterForLeaflet.

var markerCluster = new PruneClusterForLeaflet();

Step III: Setting up your Data and Markers
To plot a cluster, you need a collection of location points (latitudes, longitudes). Without this, one would never be able to plot anything on a map so getting right to it, in the sample code and the live demo, we’ve taken a “size” variable that denotes the number of markers and then using a quick for loop we’re generating random marker points.

for (var i = 0; i < size; i++) { //create prune cluster marker var marker = new PruneCluster.Marker(center.lat + (Math.random() - 0.5) * Math.random() * 0.00001 * size, center.lng + (Math.random() - 0.5) * Math.random() * 0.00002 * size); //set custom data in marker.data object; marker.data.idx = i; //add marker in custom array markers.push(marker); //Register marker as a member of cluster group. markerCluster.RegisterMarker(marker); }

where centre is a variable we’ve defined to hold the map centre.
Please Note: in the above code we’re setting the marker data in the marker.data object. Where marker.data is the object and idx is the property we want marker.data to contain and we’ve given it a value. You can give it more properties e.g. marker.data.name = “Hello”;

Now that we’ve got our data ready and all the markers we need to define the markers outlook. This is a little different than the basic cluster we had seen above. In advanced cluster, we have another property that takes in a function that helps to set the size and the image of the marker or even register for events.

markerCluster.PrepareLeafletMarker = function (marker, data) { marker.setIcon(L.icon({ iconUrl: "images/location.png", iconSize: [21, 32] })); marker.bindTooltip("Marker no. " + data.idx); }

Please Note: In real world case scenarios you’ll probably be getting a collection of latitudes and longitudes from your location or data service that gives you data to be plotted. We’ve taken the above code just to generate random points.

Now you simply need to add the cluster to the map as a layer.

map.addLayer(markerCluster);

and do a quick scoping of the map to the cluster as below:

markerCluster.FitBounds();

and finally tell the plug-in to update the view with the below code:

markerCluster.ProcessView();

Please Note: the ProcessView() will be called each time the cluster updates or changes.

Finally: Going one step further
You might want to customize a few things here and there. Good for us we’ve got this covered for you as well. In this section, we’ll look at a few code snippets through which you can handle small UI changes. For a more illustrative change in the UI consider modifying the CSS.

var markerClusters = L.markerClusterGroup({chunkedLoading: true, maxClusterRadius: 100, disableClusteringAtZoom: 26, singleMarkerMode: false, addRegionToolTips: false});

In the above code of cluster initialization let’s look at what are the various properties doing:

  1. Showing Exact count vs Showing a rounded off count on the marker.
    markerCluster.Cluster.showExactCount = false; // (Default true.)

  2. Area of the cluster.
    markerCluster.Cluster.Size = 150; // (Higher number means more markers merged. Default 120)

  3. Spider Web layout on cluster open
var request = new XMLHttpRequest(); request.open("GET", "data/cluster.json", false); request.send(null); var json = JSON.parse(request.responseText); console.log(json.features[0].properties.num) f or (var a = 0; a < json.features.length; a++) { var x = json.features[a].geometry.coordinates[1]; var y = json.features[a].geometry.coordinates[0]; if (x > 0 && y > 0) { var marker = new PruneCluster.Marker(y, x, { popup: "Marker no. " + json.features[a].properties.num.toString() }); markers.push(marker); markerCluster.RegisterMarker(marker); } }

Please Note: For a more detailed code snippet follow the links provided above to see the sample code or see a live demo

Decorated Polyline

In the previous section, we looked at clusters and their implementations. There will be cases where in you would want to get more of your polylines. For such a case scenario, we provide Decorated Polyline and Canvas Flow layer. Canvas flow layer we’ll talk about in a moment but first let’s look at what is decorated polyline and how can you leverage it.

To set the decorated polyline up below is the file composition:

  • JS Files: the decorated polyline uses a single JS file that needs to be defined in the <script> tag of the HTML as defined in the adding a plug-in section.

Now that we’ve seen the file structures let’s consider setting up a decorated polyline solution leveraging the concepts we’ve learned in the above sections.

Step I: Map Initialization
The basic step for all plug-ins is to have a working MapmyIndia map integrated project. The best part is nothing changes. You set up the map the same way we did before in the getting started section above. So, if you’re following through the documentation from the top you’ve already done it and if not, you too already have a project that’s leveraging the MapmyIndia Interactive Map. Just in case you’ve done a File > New project, then please refer to the getting started section to initialize the map and that shall bring you up to speed.

Step II: Initializing your decorator
First, we’ll create a quick instance of the decorator that’ll oversee extending the capabilities of our polyline and add it to the map.

var decorator = L.polylineDecorator(yourCreatedPolyline).addTo(map);

Step III: Setting up your Data and Polyline
The core requirement of data for this plug-in is the polyline and the polyline needs a collection of latitudes and longitudes. Follow the instructions in the Polylines section of the Overlays and Controls section for information on how to provide data for a polyline and add a polyline to the Map. More importantly we’ll look at the marker and its animation in the next section.

Step IV: Markers and Animations
The key to this plug-in is the marker and its animation. So, to do so we define an interval and pass in a decorator pattern as below:

//offset and repeat can be each defined as a number,in pixels,or in percentage of the line's length,as a string interval = window.setInterval(function () { decorator.setPatterns([ { offset: offset + '%', //Offset value for first pattern symbol,from the start point of the line. Default is 0. repeat: 0, //repeat pattern at every x offset. 0 means no repeat. //Symbol type. symbol: L.Symbol.marker( { rotate: true, //move marker along the line. false value may cause the custom marker to shift away from a curved polyline. Default is false. markerOptions: { icon: L.icon( { iconUrl: 'images/car.png', iconAnchor: [w / 2, h / 2], //Handles the marker anchor point. For a correct anchor point [ImageWidth/2,ImageHeight/2] iconSize: [14, 33] }) } }) } ]); if ((offset += 0.03) > 100) //Sets offset. Smaller the value smoother the movement. offset = 0; }, 10); //Time in ms. Increases/decreases the speed of the marker movement on decrement/increment of 1 respectively. values should not be less than 1.

As in the code we set in all the parameters that provide an animation on a defined marker. We advise not fidgeting with the offset, instead to handle speed of the animation we recommend changing the timespan of the animation.

To draw an arrow marker instead of the marker image simply replace the code marked as “Symbol Type” by the following code:

symbol: L.Symbol.arrowHead( { pixelSize: 20, //Size of arrow image headAngle: 60, //Increases/decreases arrow angel. Default is 60. polygon: true, //if set to false an arrow is added else a triangle shape arrow is added. Default is true. pathOptions: { color: '#303030', //arrow color fillOpacity: 0, //0 for no fill weight: 4 // arrow line width } })

Finally: Going one step further Now let’s look at some quick customizing tips.

  1. To change the speed of the marker we recommend changing the timespan and not touching with offset.
  2. The repeat property helps to create multiple markers on the same path with the same behaviours with every offset.

Please Note: For a more detailed code snippet follow the links provided above to see the sample code or see a live demo