Adding Multiple Map Layers – Hide Show layer using Leaflet js

This article is about how you can make visible and invisible your layer with the help of checkbox on any base map. The base layer used here is OSM (Open street map), which is open source freely available map. With layers at the same time you can open up multiple data at once and make analysis in view by looking over the overlay layers. Here we will check in Adding Multiple Map Layers – Hide Show layer using leaflet js. You may look over Getting started with leaflet js if you are very new to Leaflet and mapping library.

Adding Multiple Map Layers – Hide Show layer using Leaflet js

Showing multiple layers and making it interactive with hide and show functionality we need checkbox. So, To show two checkboxes on any HTML page the following lines are given. Here checkboxes are taken inside a division, which is denoted by tag <div> and checkboxes take input from user so they define in tag <input>. Every element of HTML can have an id, here we assign for div it is division and for checkboxes it is subunits and places. Outside the tag of checkbox we write name of the checkbox here subunits and places have used.

Some styling is required when it comes to visualisation. In this article the division containing check boxes is shown in the topmost right location. For styling the html element we need to use CSS (cascade sheet style). Using CSS we can define position, background colour font size etc. The z-index property specifies the stack order of an element as two divisions are being used in this article. An element with greater stack order is always in front of an element with a lower stack order. The division of map has lower z index then division of checkboxes.

<body>
<div id=”division” style=”position: absolute; background-color: white; width: 10%; height:10%; float: right; margin: 0.5cm 0cm 0cm 36cm; z-index:999;”>
<input type=”checkbox” id=”subunits” style=”font-size: larger”>Subunits<br>
<input type=”checkbox” id=”places” style=”font-size: larger” > Places
</div>
</body>

Using HTML and CSS we only define how the elements are going to look on the browser. How they will work it is define by the JavaScript or jQuery. Here JQuery has used for checkboxes to work.

Basic syntax is: $(selector).action()

  • A $ sign to define/access jQuery
  • A (selector) to query HTML elements
  • A jQuery action() to be performed on the element.

Here how the code looks like for Adding Multiple Map Layers – Hide Show layer using leaflet js

Before going through code in adding and hide – show multiple layer using leaflet, you should be having a good knowledge of adding point, line and polygon layer using leaflet js along with parsing geojson or topojson layer using leaflet js if you want to add topojson data layers.

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. Here user needs to click on the checkbox to add and hide the layer from OSM. So selector is id of checkbox and action is click() method. In the method we define the function to add or hide the layer. 

$(“#subunits”).click(function() {
if (this.checked) {
console.log(“checked!”);
geo.addTo(newMap);
} else {
console.log(“unchecked!”);
newMap.removeLayer(geo); }; });
In similar way places are added on the map with following lines of code.
$(“#places”).click(function() {
if (this.checked) {
console.log(“checked!”);
var places = topojson.feature(uk,uk.objects.places);
geoP=L.geoJSON(places).addTo(newMap);
} else {
console.log(“unchecked!”);
newMap.removeLayer(geoP);
};
});

Here is how the output will look like for Adding Multiple Map Layers – Hide Show layer using Leaflet js:

Adding Multiple Map Layers - Hide Show layer using Leaflet js
Adding Multiple Map Layers – Hide Show layer using Leaflet js

If else statement shows that if checkbox is clicked and returns checked status then layer is added to map and checked can be seen on console. Else checkbox will return unchecked status then unchecked will be written on console and added layer will be removed from map.

Here addTo() and removeLayer() methods are from leaflet javascript library, which adds and removes layer from map. To see the console on browser right click on browser and click to inspect option.

Hope this article might help you in Adding Multiple Map Layer using Leaflet js library. If you are facing any problem in implementing, then do comment below with the problem text you are facing. So that we can discuss over it.

Create beautiful dynamic Legend map – Leafletjs TopoJson

In this article we are going to add legends to choropleth map with topojson Data using leaflet. Legends are the element of map that provides information about map with the help of symbols. Here symbol can be colour, shapes, figures etc. The choropleth map gives information using colours. Lets play around with : Create beautiful Legend map – leafletjs topojson. If you are very new to Leafletjs then before going through this article you should look over to Getting started with Leafletjs article and how to render topojson with leaflet js.

Dynamic Legend map – Leafletjs TopoJson

Lets get started with code. For this first we need to create a method getColor(d). The method takes “d” as parameter, which takes a specific value from topojson data, and then returns the colour value (in form of colour) after comparison. For instance, if d is greater than 5000 then return red color i.e ‘#FF0000’ otherwise return blue colour i.e ‘#0000ff’. Here colour codes are given in hexadecimal value you can give RGB value or colour name.  We will create this function as:

function getColor(d) {
return d > 5000000 ? ‘#7a0177’ :
d > 200000? ‘#BD0026’ :
d > 80000? ‘#E31A1C’ :
d > 10000? ‘#FC4E2A’ :
d > 5000 ? ‘#FD8D3C’ :
d > 500 ? ‘#FEB24C’ :
d > 0 ? ‘#FED976’ :
‘#FFEDA0’;
}

Now to show the legend section on map, we need to create a division with the help of DomUtil and add that to the map. Here a variable name legend is created which is positioned to bottom right. The style “position: ‘bottomright’ “ is done using CSS.  L.control is a base class for implementing map controls from leaflet javascript library. This handles positioning. All other controls extend from this class.

var legend = L.control({position: ‘bottomright’});

The above function i.e getColor() will be called once we add Legends on Map. for that we need to create an event of adding legends on map.  onAdd() method, which is from leaflet’s control class returns the container DOM element for the control and add listeners on relevant map events. Here it takes value as function that returns HTML element (div) as like: 

legend.onAdd = function (map) { } 

Then DomUtil class has used.  But what is DOM (data object model), connects web pages to scripts. It is object oriented representation of web pages, which can be modified with scripting language like javaScript. DomUtil works with Dom tree. Here create() method has used which is from leaflet’s DomUtil class. This method returns a HTML element and takes parameter as tag name and class name. Tag name to create that element on document and class name style that element. Here HTML element is division and two classes are given as info and legend. An array name grades is created with value given by getColor(d) method.

var div = L.DomUtil.create(‘div’, ‘info legend’),
grades = [0,500,5000,10000,80000,200000,5000000];

To add field and colour in legend on map, a for loop has written. This shows variable i has initial value as zero and condition is as, “if variable i is less than length of array grades then loop will run and after one cycle increment will take place”.

HTML element div has styled inside loop having background colour values from getColor() method and &ndash is HTML entities used for typography.

for (var i = 0; i < grades.length; i++) {
div.innerHTML += ‘<i style=”background:’ + getColor(grades[i] + 1) + ‘”></i> ‘ + grades[i] + (grades[i + 1] ? ‘&ndash;’ + grades[i + 1] + ‘<br>’ : ‘+’);
}
return div;
};

The following statement adds the legends on map i.e:

legend.addTo(newMap);

As in create() method we have used info and legend class and that classes are designed inside style HTML tag i.e as :

<style>
.info {
padding: 6px 8px;
font: 14px/16px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255,255,255,0.8);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
border-radius: 5px;
}
.legend {
background-color: “black”;
line-height: 25px;
color: #555;
width: auto;
}
.legend i {
width: 18px;
height: 18px;
float: left;
margin-right: 8px;
opacity: 0.7;
}
</style>

Here is how the output will look like. I had taken UK topojson file. If you have shapefile to geojson or kml file, you may look over to an article to convert shapefile to TopoJson or Geojson to Topojson Conversion. If you have Kml file then you can convert the kml file to Shapefile and then to TopoJson file.

dynamic Legend map - Leafletjs TopoJson
dynamic Legend map – Leafletjs TopoJson

This will finally make you to create dynamic legends with leafletjs library in Mapping system. I hope article helped you. If you find any problem in creating dynamic legends, do comment below in the box provided, we will discuss and solve the issue.

Read Parse Render TopoJSON file – Leaflet js

This article shows how to render topojson file data on OSM map with the help of d3 and Leaflet javascript library in the browser. Leaflet js is an open source small library to create interactive map. You may look over Getting Started with Leaflet js. TopoJSON is one of the GIS data structure which stores geographic data in JSON format. You can easily convert Shapefile to TopoJSON or convert GeoJSON to TopoJSON file. Rather than representing geometries discretely, geometries in TopoJSON files are stitched together from shared line segments called arcs. TopoJSON eliminates redundancy, allowing related geometries to be stored efficiently in the same file. A single TopoJSON file can contain multiple feature collections without duplication. Or, a TopoJSON file can efficiently represent both polygons (for fill) and boundaries (for stroke) as two feature collections that share the same arc mesh. You might be thinking why Topojson. Because TopoJSON files are almost 80% smaller than their GeoJSON equivalents.

Read Parse Render TopoJSON file – Leaflet js

Your html code will start with the DOCTYPE as :

<!DOCTYPE html>
<meta charset=”utf-8″>
<div id=”map” style=”width: 1000px; height: 1000px;”></div>

The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in. The charset attribute specifies the character encoding for the HTML document. Div tag denotes division or a selection in document. Here it is a container for map with id as map, width and height as 1000px.

To use any library in document you first need to add that library into your document. The script tag contains the scripts which is leaflet and d3 javascrpit library. This library can be downloaded from http://leafletjs.com/download.html or you can add the given links as follows:

<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<link rel=”stylesheet” href=”https://unpkg.com/leaflet@1.0.3/dist/leaflet.css” />
<script src=”https://unpkg.com/leaflet@1.0.3/dist/leaflet.js”></script>
<script src=”https://d3js.org/d3.v3.min.js” charset=”utf-8″></script>
<script src=”https://d3js.org/topojson.v1.min.js”></script>

Now to add OSM (Open street map) in division we create a variable named as newMap. Here L.map represents object of map class takes Html element as parameter. Setview is a method that set the center and zoom level according to given parameters.

var newMap = L.map(‘map’).setView([38.9188702,-77.0708398],6);

The tileLayer represents object of tileLayer class that takes URL of data. Here we have given OSM tiles in parameter. In attribution key you need to define the contribution of data source. You are free to copy, distribute, transmit and adapt OSM data, as long as you credit OpenStreetMap and its contributors. For this you need to add http://osm.org/copyright into your document. Method addto() adds the layer to the given map.

L.tileLayer(‘http://{s}.tile.osm.org/{z}/{x}/{y}.png’, {
attribution: ‘&copy; <a href=”http://osm.org/copyright”>OpenStreetMap</a> contributors’
}).addTo(newMap);

Here d3 (data driven document) is a javascript library for manipulating document that visualizes data with HTML, CSS and SVG. Json() is a function that gets Topojson file. Here uk.json is a topojson data. The topojson.feature() function converts the geojson data into topojson data format. L.geoJson creates a GeoJSON layer, accepts an object in GeoJSON format to display on the map.

d3.json(“uk.json”, function(error, uk) {
var places = topojson.feature(uk,uk.objects.places);
var geo=L.geoJSON(places).addTo(newMap);
newMap.fitBounds(geo.getBounds());
});

As data is now added to the map by using addTo() method. Now to get the area covered by topojson file on the map or directly pan to the area where this data has rendered you can use the methods getBounds() and fitBounds(). The getBounds() method returns the geographical bounds visible in the current map view. Here this method is used with geoJSON layer to get its bounds or diagonal corner coordinates. The fitBounds() sets a map view that contains the given geographical bounds with the maximum zoom level possible.

“var places = topojson.feature(uk,uk.objects.places);” command has used which shows the places (geometry primitive as points) on the map.

Read Parse Render TopoJSON file
Read Parse Render TopoJSON file

If var subunits = topojson.feature(uk, uk.objects.subunits); command you use then it will show the subunits (geometry primitive as polygon) on the map.

Read Parse Render TopoJSON file
Read Parse Render TopoJSON file

That is all about read, parse, render Topojson file with Leaflet js. You may also look in to rendering point, polyline and polygon geojson file with leaflet js. If you find any problem in Rendering TopoJSON file then do comment below, I would love to help you in providing solution.

Convert Shapefile to TopoJSON

ESRI shapefile are the binary vector data storage format for storing the location, shape, and attributes of geographic features. It is stored as a set of related files and contains one feature class. Whereas TopoJSON (topological geospatial data) is an extension of GeoJSON that encodes topology. The necessity of conversion is to reduce the size of data. While using Shapefile, you have to take care of all its mandatory files such as .shp, .shx, .dbf, .prj etc. Whereas GeoJSON and TopoJSON formats are single file formats.

There are many online and desktop application based solutions to do this conversion. But the method everyone looking forward is an easy way to convert a file to a preferred format. In this article we will see how easy is IGISMAP for the conversion process. Following are the methods to convert Shapefile to TopoJSON using IGISMAP Converter tool.

Use Online Converter Tool – Shapefile to TopoJSON MapOG

IGISMAP (Now MAPOG) to Convert Shapefile to TopoJSON

Go to MAPOG Converter Tool, after logging in with your registered email and password. If you are a new user, click the Sign Up button in the Login popup and register to IGISMAP by filling the details.

There are three main steps for using GIS Converter:

  • Upload the data
  • Choose the format to which it should be converted
  • Download the converted file.

Step one is to upload your Shapefile which you want to convert. You can upload the file from your system or select from the Recent Files.

Converter Tool - Upload Shapefile
Upload Shapefile

Here we using the Shapefile of India state level boundaries with demographic information. You can find this data in IGISMAP GIS Data Collection –

Step two is to select choose the output format of the converted file, in this case its TopoJSON. You can also set the Coordinate Reference System of your preference. As a default CRS will set to WGS 84 (World) [EPSG:4326]. Click on the Convert File button.

Converter Tool - TopoJSON as Output Format
Select TopoJSON as Output Format

Your Shapefile will then get converted to TopoJSON file after a few seconds and will be published in the map canvas. You can download the TopoJSON file of New York state boundary by clicking the Download Converted File button.

Download and Publish TopoJSON File
Download and Publish TopoJSON File

You can also choose to style the layer or continue with further conversion process by clicking the Convert Another File button.

Converted Files section from the dashboard contains the list of the details of all the conversion done in your account, providing both input and output data available for download their corresponding formats.

IGIS Map Converter Tool provides many benefits other then just conversion of data. This tool provides us to generate this published map in PDF or as image format.

Info GIS Map supports most of the commonly used GIS or AutoCAD files like Shapefile SHP, KML, KMZ, CSV, TopoJSON, GeoJSON, GML, DXF, GeoTIFF, NetCDF, GRIB, HDF5, OSM, PBF, and many more raster and vector files, along with that it support more than 4000 Coordinate Reference System.

Here are other two ways to convert shapefile to topojson

Use Online Converter Tool – Shapefile to TopoJSON MapOG

Offline Method : Convert Shapefile to topojson through GDAL and then through geo2topo tool npm:

To convert shape file to topojson format offline you need to download GDAL and Node.js.  First step is to convert shapefile to geojson data format, which is done by using ogr2ogr command available in GDAL package. After successful installation check ogr2ogr availability by typing ogr2ogr in command prompt or by typing dir that will show all available directories.

convert shapefile to topojson

Now you can convert shapefile to geojson data format by using given command

  • Ogr2ogr –f Geojson file_name.json input.shp

Here –f option is used to shows the file format, which shows output file format is geojson. GDAL takes name of output file prior to input file.

Convert geojson to topojson:

Now to convert geojson data to topojson data format you have to download node.js which is available https://nodejs.org/en/ here. After successful installation you need to check npm availability using command

  • npm –check.
convert shapefile to topojson

If not available use

  • npm install -g npm-check

After this you need to install topojson-server for conversion of data that can be done by using

  • npm install topojson-server command

Now all setup is ready

Use geo2topo command to convert geojson data to topojson data

  • geo2topo –o geo.json topo.json

Here –o option is used to give the output. If command doesn’t run and gives error as no such file or directory. Then specify full path for file for both input and output. The older versions were having topojson as a command to convert geojson data format to topojson data format. Topojson is named as geo2topo command in new version.

Convert Shapefile to TopoJSON – Online Method

Mapshaper is an online tool that converts shape file to topojson data format directly. You only need to drag the shape file to http://mapshaper.org/ site. Then use export option to convert this data into topojson format. In Mapshaper there are many option are available to simplify the geometry, which you can explore.

convert shapefile to topojson
convert shapefile to topojson

You may also look over converting kml to shapefile and shapefile to kml conversion.

I hope this article helped you in converting the file from Shapefile to TopoJSON. If you find any problem in performing operation do let me know by commenting below.

Convert GeoJSON to TopoJSON – GIS

Convert GeoJSON to TopoJSON. GeoJSON is an open standard format designed for representing simple geographical features, along with their non-spatial attributes, based on JavaScript Object Notation. The need of conversion is to reduce the size of data, so that rendering of data on browser can be made faster. TopoJSON (topological geospatial data) is an extension of GeoJSON that encodes topology. Here we have explored two methods for conversion of GeoJSON to TopoJSON (i.e. online and offline).

Use Online Converter Tool – Geojson to TopoJSON MapOG

Offline Method to Convert GeoJSON to TopoJSON:

You can directly convert GeoJSON to TopoJSON with the help of topojoson-server node package manager. For using this package you need to first install node js in your system (can be installed in windows, linux based operating system or Mac).

If you have Shapefile or KML file, then you can refere this articles i.e convert kml to shapefile, convert shapefile to GeoJSON and converting shapefile to kml, so that you can generate new GeoJSON file out of other GIS format files.

Convert GeoJSON to TopoJSON – NPM method

NPM (Node Package Manager) is a command-line utility that aids in package installation, version management, and dependency management or can be considered npm as a tool that helps to install another tools like topojson-server.

For this method you need to download node.js which is available https://nodejs.org/en/ here. After successful installation you need to check npm availability using command

  • npm –check.

If not available use

  • npm install -g npm-check

convert geojson to topojson
convert geojson to topojson

After this you need to install topojson-server for conversion of data that can be done by using

  • npm install -g topojson-server

Now all setup is ready

Use geo2topo command to convert geojson data to topojson data

  • geo2topo –o geo.json topo.json

Where geo.json is the geojson file i.e input file and topo.json is the file we are creating with the name topo as topo.json file i.e output file.

Here –o is output. If command doesn’t run and gives error as no such file or directory. Then specify full path for file for both input and output. It is recommended that you run this command from the same directory where geo.json file is stored.

If you don’t have any input files ready or any geojson or shapefile then you can download free GIS data fromat for testing this article.

Online method: Convert GeoJson to TopoJson

This is the simple and fast method. For the conversion you just need to drag the geojson file in http://mapshaper.org/ site. Then use export option to convert this data into topojson format. Map shaper website render and convert the file in the browser itself, but it you might face problem while converting a big geojson file. 

I hope that this methods listed above to convert geojson to topojson would have helped you in achieving result. If you find any problem or know any other method to perform this operation and want to share with us, then do let us know by commenting below, in the box provided.