Import Shapefile in Postgresql – shp2pgsql

Import Shapefile in Postgresql directly by command line tool. Shapefile is a data vector file, which stores GeoSpatial Data. PostGreSql Database support Spatial or GIS data. As shapefile is just a representation of Geo Data, while postgresql is database which support many GIS functionalities as like finding nearest neighbour, distance calculation from one point to another etc. This makes developer to think for importing the shapefile data in postgresql and view attributes. Similarly you may also check for exporting shapefile from postgresql database.

Prior to import Shapefile in Postgresql, we first need to install postgresql and PostGIS. Also for running a command line tool to import shapefile you should check if shp2pgsql is available in your system and is installed.  What does shp2pgsql command does? shp2pgsql is a command line tool, which helps in to convert or import single or multiple shapefiles into postgresql or postgis database tables.

If you are linux or ubuntu system, you can check the same by running shp2pgsql command in terminal after navigating to “/usr/lib/postgresql” path. If shp2pgsql is not installed, you should first download the same from the authentic website and then try to follow out the steps provided below.

Import Shapefile in Postgresql

For inserting shapefile to postgis, we first need to have one shapefile. If you don’t have any such shapefile, you may download the shapefile for free as suggested in the linked post. For instance to demonstrate import shapefile in postgresql, I have downloaded United state administrative boundary shape file. Now this unzip the folder. You can choose any other shape file which contain atleast this 3 files i.e .dbf , .shp, and .shx.

Creating database and table in postgresql before inserting the shapefile

Creating Database

Now to import shape file you first need to create database and table. Now lets create one database using given command as:

sudo -u postgres createdb -O DATABASE_USER DATABASE_NAME

now test created database is working properly by executing the given command

psql -h localhost -U DATABASE_USER DATABASE_NAME

for the given command output should be

psql (9.6.2)

SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)

Create Table

Now create the table, you need to write. The structure of table should be in this format, which should have a geom as Geometry column atleast.

CREATE TABLE TABLE_name(gid integer, code smallint, name varchar(32), shape_leng numeric, shape_area numeric,  geom geometry);

Here is one such sample

CREATE TABLE nybb(gid integer,code smallint, name varchar(32),shape_leng numeric,shape_area numeric,geom geometry)

shp2pgsql command to import shapefile

Now you are ready to add you shapefile. Just navigate yourself to unzipped folder and execute the given command

shp2pgsql -I -s 2263 SHAPEFILE.shp DATATABLE | psql -U DATABASE_USER -d DATABASE_NAME

for example :

shp2pgsql -I -s 2263 nybb.shp nybb | psql -U hello -d gisdata

here 2263 is spatial reference system or coordinate system of the shape file.

Nybb.shp is the shapefile, nybb is the database table name, hello is the database user which is replace byDATABASE_USER and gisdata is the database.

Know the details of shapefile inserted in postgresql or postgis

Lets get connect with postgresql database. Command for the following as shown:

psql -h localhost -U DATABASE_USER DATABASE_NAME

This will navigate you in database you created. Now to know the attributes details of the table you can run following query:

select * from TABLE_NAME

This will show all rows and column in table format. While I have faced few problems while importing shapefile and checking the shapefile table in postgresql. Lets now look over the problem and solution for the same, if you are also facing the same.

Problems and solution encountered in implementing Import shapefile in postgresql

Problem 1 : While running query or fetching shapefile table in postgresql I got the following error:

psql: FATAL: Peer authentication failed for user “postgres”

Solution 1 : For solving this you need to open and edit pg_hba.conf, where you need to replace all peer with md5.

Md5: The password-based authentication methods are md5 and password. These methods operate similarly except for the way that the password is send across the connection, namely MD5-hashed and clear-text respectively.

If you are at all concerned about password “sniffing” attacks then md5 is preferred. Plain password should always be avoided if possible. However, md5 cannot be used with the db_user_namespace feature.

Peer: The peer authentication method works by obtaining the client’s operating system user name from the kernel and using it as the allowed database user name (with optional user name mapping). This method is only support on local connections.

Problem 2: Unable to open nybb.shp or nybb.SHP or nybb.shp: dbf file (.dbf) can not be open.

Solution : You may also face problem as state above.

To solve this, you must take care that you should add shapefile in a zip folder or in the folder where your shapefile is kept.

I hope this post might helped you in easily uploading or import shapefile in postgresql. If you still find any problem in doing so, do comment below with the problem, so that we can discuss and look together over the solution.

Export shapefile from postgreSQL – pgsql2shp – Command line or Php

Is your GIS data stored in postgreSQL Database? Are you looking to export that postgreSQL data in shapefile and further use in different way. It is directly possible with Pgsql2shp command which is directly available with postgreSQL system. In this article you will directly understand the way to export Shapefile from postgreSQL with pgsql2shp tool.

Pgsql2shp (postgis to shapefile dumper) is command that provides shapefile and takes query as input. The geometry column should be present when running the postgis query.
You need to download zip file to run pgsql2shp. You can download pgsql2shp tool from any authentic website for mac, ubuntu or linux system or windows.

Similarly you can import the shapefile in postgresql using the command line tool shp2pgsql. 

Export shapefile from postgreSQL – pgsql2shp

Here we will check pgsql2shp tool that can be used either with command line or with php language. Similarly you may connect to postgresql with server side language and use pgsql2shp.

With Command line – Export shapefile from postgreSQL

After downloading the tool file, navigate from command line to that particular folder. You may type this command to get the help description and options of the tool —

pgsql2shp

Export shapefile from postgreSQL - pgsql2shp

The general syntax for the command pgsql2shp is:

pgsql2shp [options] database [schema.]table
pgsql2shp [options] database query

To export a full table from postgis to shapefile:

pgsql2shp  -u <username> -h <hostname> -P <password> -p 5434 -u postgres -f <file path to save shape file> <table_name>

To export a query data from postgis to shapefile

pgsql2shp -f <file path to save shape file> -u <username> -h <hostname> -P <password> <database Name> “query to be executed”

There are many option,which are listed below-
OPTIONS
The command line options are:

-f <filename>
Write the output to a particular filename.

-h <host>
The database host to connect to.

-p <port>
The port to connect to on the database host.

-P <password>
The password to use when connecting to the database.

-u <user>
The username to use when connecting to the database.

-g <geometry column>
In the case of tables with multiple geometry columns, the
geometry column to use when writing the shape file.

-b Use a binary cursor. When used on pre-1.0.0 PostGIS versions
this will reduce the likelihood of coordinate drift due to
conversion to and from WKT format. Coordinate drifts will not
occur with PostGIS 1.0.0 and newer versions. It will be slightly
faster, but might fail if any NON-geometry column lacks a cast
to text.

-r Raw mode. Do not drop the gid field, or escape column names.

-d For backward compatibility: write a 3-dimensional shape file
when dumping from old (pre-1.0.0) postgis databases (the default
is to write a 2-dimensional shape file in that case). Starting
from postgis-1.0.0+, dimensions are fully encoded.

-k Keep identifiers case (don’t uppercase field names).

-m <filename>
Specify a file containing a set of mappings of (long) column
names to 10 character DBF column names. The content of the file
is one or more lines of two names separated by white space and
no trailing or leading space:

-? Display version and usage information.

With programming language – Export shapefile from postgreSQL

We have used codeigniter to execute the query and export the postgis data to shapefile. The scenario is very simple. We have a Road shapefile of a country, where we want to find the distance between two cities or points and render the same on map. For this, we have used pgr_dijkstra() alogrithm and find the shortest path. The shortest path output is collected as shapefile and rerendered on map. There are many ways to render the shortest path, just to understand pgsql2shp we used this one.

Here queries are written in PHP, where $start and $end  are the variable here. We have written query to take starting and ending point for finding shortest path. 

This command is normally executed in terminal as written above, but we can execute it in code shell_exec() method from PHP.

$start = $this->db->query(“SELECT source FROM network1 ORDER BY geom <-> ST_SetSRID(ST_Point ($dlong1,$dlat1),4326) LIMIT 1”)->result();
$end= $this->db->query(“SELECT source FROM network1 ORDER BY geom <-> ST_SetSRID(ST_Point ($dlong2,$dlat2),4326) LIMIT 1″)->result();
$start1= $start[0]->source;
$end1= $end[0]->source;
$query=”‘Select gid as id, source, target, st_length(geom::geography)/1000 as cost from network1′”;

$command= ‘pgsql2shp -f “/var/www/html/PHP_pgrouting/public/shpfolder/try_new.shp” -h localhost -u user -P “pass1” postgres “select seq,id1,id2,cost,geom from pgr_dijkstra(‘.$query.’,’.$start1.’,’.$end1.’,false, false) as di JOIN network1 pt ON (di.id2 = pt.gid)”‘;

echo shell_exec($command);

This will produce a shapefile, where we have rendered the same as you can see in the output.

Export shapefile from postgreSQL - pgsql2shp
Export shapefile from postgreSQL – pgsql2shp

I hope this article might have helped you in convert and export shapefile from postgreSQL with pgsql2shp tool. If you find any problem in implementing the steps, let me know via comment, so that we can solve the same.

Embed Google map with 2 or more Markers for Web pages

Embed Google map with 2 or more Markers in html or for Web pages. Embedding a Google map in html is direct method, where you can directly find the link from Google Maps. Embedding map iframe links are useful in business websites, or locate branches location which can be directly featured and accessed through ones websites.

Embedding Google Map doesn’t means a whole HTML file or long scripts or using Google Map API. Instead it is just <iframe> tag. This means that it is not a image on a web page or application, but instead an interactive map which can be zoomed in or out and drag accordingly. On your website, you can embed a map, Street View image, driving directions, or search into your website or blog. On your computer, phone, or tablet you can share a location or map with others over email, Google+, Facebook, Twitter, or text.

Steps to Embed Google map with 2 or more Markers for Web pages

Step 1: Navigate yourself to https://www.google.com/maps link.

Step 2: sign in with Google account.

Embed Google map with 2 or more Markers for Web pages
Embed Google map with 2 or more Markers for Web pages

Step 3: Click option menu and Navigate to Your places-> maps-> create a map in bottom. A new window will open in new tab.

Step 4: Now Click on Untitled Map, Write a title and description then hit to save button.

Step 5: You have two ways to add markers on map:

A.) You can directly choose marker option and place them on map, wherever you need.


B.) You can specify the location by providing location address.

After adding markers on map you must save the locations.

Step 6: Repeat step 5 to add multiple markers.

Step 7: Now click to share option and set the privacy setting to “public on web” or you can choose people who can view and access the map.

Then save the details and click to done.

Step 8: Then Click to option menu on title window and hit to embed on my site.

This will provide you a link containing <iframe> tag. By using this code you can easily Embed Google map with 2 or more Markers for Web pages.

Election Map Benefits List – Types of GIS Election Map Create

As map is a one of great tool for analysis purpose, and so is useful for analysing the information of election by creating map. Election, is one of the most important activity that took place in country or state or at sub state level. In this post we will check Election Map Benefits List and Types of people who will get benefits by election map. With Election Maps, many types of people can take benefits in doing their research and analysis in few minutes i.e

  • Politician – Can analyse the map and prepare their speech, use for further targeting the people, look over the possibility of their winning etc.
  • Public or People – Can visualize the election map and find out where are the development made by which parties or politician, where are the poll booths located etcs.
  • Election commission
  • News or Media people – For creating different kind of news and providing the info to public

In addition to supporting elections on the front end, GIS or Map can support many business processes of elections management including address validation, polling place siting and optimisation, routing of elections volunteers and personnel, mapping of voter turnout for planning and decision support, development of precinct maps, redistricting, and generation of real-time election results.

Following are some analysis report which can be generated by Election Map:

  • We can have the previous year information about party, winning candidate, runner up candidate, vote counts and how much amount they spent on election process etc.
  • We also can have their other details of candidate such as qualification, criminal records or caste etc.

Election Map Benefits List

  1. By analyzing the previous record we actually can predict the result for upcoming elections.
  2. The most exciting feature we get while using the map is that we can track the winning and runner up candidate in each state or city at same time.
  3. We can check real time vote count every signal minute.
  4. Comparison is easy with other parties and with other state.
  5. Easy way to find out polling places with proper direction and also the nearest one.
  6. Map can be used to display the numbers of men and women who serve on appropriations parties.
  7. As if we have map with detailed data then we can even apply various filters such as distinguish area for winning or runner up candidate in men or women, caste wise, party wise or state wise etc.
  8. Using GIS, we can even target the person, who are registered voters but don’t vote regularly.

Other Benefits of Election Map

  • Improved transparency
  • Easy access to information
  • List of registered voter and coordinators and managing it
  • Checking voting irregularity
  • Easy access to polling location

Providing all the facility we must take care that data should not be misuse. This data can be used by political parties, consultants, researchers, media professions and other organization.

Types of Election Map created:

Here we have researched and found out few election map generated recently in following websites like :

From NDTV:

Election Map Benefits List

From Times:

Election Map Benefits List
Election Map Benefits List

From DNA

Election Map Benefits List

What you think about Election Map? How more useful the election map can be? And what kind of data you want to analyse and generate from Election Map. Hope you find this article helpful. Do comment below to discuss more about the type of Election Map and benefits. If you are looking to create one such Map, do contact us, we are one of the best agency to create one such interactive map.

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.

Create Heat map showing average household income – leaflet js GIS

First of all we must know what heat map is? A Heat Map is a way of representing the density or intensity value of point data by assigning a colour gradient to a raster where the cell colour is based on clustering of points or an intensity value. In this article i.e to Create Heat map showing average household income. If you are not familiar with Leaflet then you may also look over Getting started with Leaflet js and all other leaflet js tutorial article page.

Create Heat map showing average household income – leaflet js GIS

Firstly we will initialise the container and add Open street map. As data is in JSON array format, to extract each value a for loop is applied. Here UsIncome is the data containing name, latitude, longitude and income value of each county of US.

for (var i = 0; i < UsIncome.length; i++) {
var a = UsIncome[i];
var name=a[0];
var income=a[3];
}

As average household income has used as intensity value. A function getMax() gets the maximum value of  property from array.

var maximum;
function getMax(arr, prop) {
for (var i=0 ; i<UsIncome.length ; i++) {
if (!maximum || parseInt(UsIncome[i][prop]) > parseInt(maximum[prop]))
maximum = UsIncome[i];
}
return maximum;
}

Now to use heatLayer or create heat map you need to add plugin either by downloading from https://github.com/pa7/heatmap.js/releases or adding script in your document. The map() method creates a new array with the results of calling a function for every array element addressPoints is an array of latitude and longitude.

L.heatLayer(latlngs, options)

Constructs a heatmap layer given an array of points and an object with the following options:

minOpacity – the minimum opacity the heat will start at
maxZoom – zoom level where the points reach maximum intensity (as intensity scales with zoom), equals maxZoom of the map by default
max – maximum point intensity, 1.0 by default
radius – radius of each “point” of the heatmap, 25 by default
blur – amount of blur, 15 by default
gradient – color gradient config, e.g. {0.4: ‘blue’, 0.65: ‘lime’, 1: ‘red’}

addressPoints = UsIncome.map(function (p) { return [p[1], p[2]]; });
var a=L.heatLayer(addressPoints,{max: getMax(UsIncome,’Median Annual Household Income’), minOpacity: 0.05,
maxZoom: 18,
radius: 25,
blur: 15,
gradient: {
0.2: ‘green’,
0.60: ‘yellow’,
1.0: ‘red’},maxZoom:14}).addTo(map);

In the last markers are added with opacity 0.01 to make it invisible. BindTooltip has similar use as hover, shows popup when mouse is on marker.

var marker = L.circle(locations, { opacity: 0.01 }).bindTooltip(income+”,”+name , {className: ‘myCSSClass’}).addTo(map);
}

Here’s how the heat map created with leaflet js would look like :

Create Heat map showing average household income
Create Heat map showing average household income

You may also check the working example here:

http://www.igismap.com/portfolio/climate/ : climate US Heat Map

Heat map considered as best when it comes to visualization of information on map. Large amount of data can easily be visualized on map. It has various uses

  • Pollution level in any country
  • Crime rate
  • Population in any area
  • Hottest and coolest city
  • Traffic information
  • Different water level

I hope this may help you in developing and creating a heat map in leaflet js. If you find any problem in creating one such example do let us know by commenting below.

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.

Add different base map layers using leaflet js

Leaflet is  small open source Javascript library to create a customised mapping solution. Leaflet plugin supports many types of map layer. In this article we have map layers as Google map, Open street map, Stamen map, Here map and Bing map layer. What is plugin? Plugin is software that is installed onto a program, enabling it to perform additional features. Similarly here we can download library or access API or can add its link in our document. Lets find how to add different base map layer using leafletjs. If you are new to Leaflet you may look over a simple article explaining details about leaflet along with getting started and describing method to add GeoJSON layer in leaflet as point, polyline or polygon.

Different base map layers using leaflet js:

Google Map Base Layer using LeafletJs:

To add Google map with leaflet in your document you need to add the links:

<link rel=”stylesheet” href=”http://cdn.leafletjs.com/leaflet-0.3.1/leaflet.css” />
<script src=”http://cdn.leafletjs.com/leaflet-0.3.1/leaflet.js”></script>
<script src=”http://maps.google.com/maps/api/js?v=3.2&sensor=false”></script>
<script src=”http://matchingnotes.com/javascripts/leaflet-google.js”></script>

The first two links are for leaflet JavaScript library and last two for Google map. Leaflet plugin that enables the use of Google Map tiles. To download Google API you can visit https://gist.github.com/crofty/2197042 . Then add the <div> HTML tag as a container for map and set the centre and zoom level. After this you are allowed to use Google() function by which you can add map to your document.

      var googleLayer = new L.Google(‘ROADMAP’);
map.addLayer(googleLayer);

Stamen Map Layer using leafletjs:

To show this map on browser you need to use the leaflet and stamen API. The leaflet JavaScript library you can download from http://leafletjs.com/download.html or can add the two links as shown above. To use stamen API add the given link in head tag of your html document.

<script type=”text/javascript” src=”http://maps.stamen.com/js/tile.stamen.js?v1.2.3″></script>

or you can download the zip file from https://github.com/stamen/maps.stamen.com.

To show map on browser a container is required which is given by <div> HTML tag and its styling can be done in CSS.

html  : <div id=”map”></div>

css : #map { position: absolute; top:0; bottom:0; right:0; left:0; }

Now to add division with leaflet and set its latitude longitude of centre, map() and setView() methods have used.

javascript : var map = L.map(‘map’).setView([39, -97.5], 4);

As we have used stamen API in document so now we can use its method StamenTileLayer() to use stamen map.

javascript :

var stamenLayer = new L.StamenTileLayer(“watercolor”);
map.addLayer(stamenLayer);

There are other types of map also available like terrain, toner and watercolor world widely. Some maps like Burning map or mars map etc. can be used with webGL.

Add different base map layers using leaflet js
stamen design map using leaflet js

Add Here Map Layer using leaflet:

To add Here Map in your document you don’t need to download API or add any link. But you need API id and code which is available https://developer.here.com you can register and get the API id and code to start coding. As we are using this with leaflet, its library has to be link with our document then a container should be present to attach map. After getting API id and code you can run this statement

var layer = L.tileLayer(“http://1.base.maps.cit.api.here.com/maptile/2.1/maptile/newest/normal.day/{z}/{x}/{y}/256/png8?app_id=OO3n6HayrdDH6DhkxRgG&app_code=MZQ6Zn6zc1s5Psz92GMMxw”).addTo(map);

The line shows that you need to add the Map tile then API id and code.

Add different base map layers using leaflet js -here map using leaflet js
here map using leaflet js

Add Bing Map base Layer :

For adding Bing map we have downloaded Leaflet-Bing-Layer.js file and place it with downloaded leaflet library. To download Leaflet-Bing-Layer.js file you can visit https://github.com/digidem/leaflet-bing-layer here. Now we can add the Leaflet-Bing-Layer by using this <script src=”leaflet-bing-layer.js”></script>

To any Bing map you need to have a key which is available https://www.bingmapsportal.com/Application

Bing map depends on Promises which needs a polyfill for older browsers by adding this script to your html <head>:

<script src=”https://cdn.polyfill.io/v2/polyfill.min.js?features=Promise”></script>

After having that key, take it into a variable and add a map container in your code with centre and zoom level. Now you can use the bing() method present inside the tileLayer class then add key as parameter.

var BING_KEY = ‘AvxUyTMNAOEAsT4pw2SiUhwIBxrNJxwfjHTCNN64QWIjmiRbAr1HZWANY6U2Tg3’
var map = L.map(‘map’).setView([51.505, -0.09], 13)
var bingLayer = L.tileLayer.bing(BING_KEY).addTo(map)

Finally use addTo() to add map to the container.

ESRI ArcGis Map Layer:

To use ESRI ArcGIS map you can download plugin from https://esri.github.io/esri-leaflet/download or can add this link into your document

<script src=https://unpkg.com/esri-leaflet@2.1.1/dist/esri-leaflet.js”</script>. 

After adding and styling container you can use L.esri.basemapLayer(‘Streets’) this command. Here street is parameter, there are some other parameter too that you can use in place of street. The parameters are “Streets”, “Topographic”, “Oceans”, “OceansLabels”, “NationalGeographic”, “Gray”, “GrayLabels”, “DarkGray”, “DarkGrayLabels”, “Imagery”, “ImageryLabels”, “ImageryTransportation”, “ShadedRelief”, “ShadedReliefLabels”, “Terrain”, “TerrainLabels” or “USATopo”. After that addTo() method is used to add map to the container.

L.esri.basemapLayer(‘Streets’).addTo(map);

Add different base map layers using leaflet js - esri map using leaflet js
esri map using leaflet js

There are many mapping service company which provide base layer either for free or for some cost. Leaflet provide a convenient method to add different base map layers. I hope this article helped you in rendering base map layer. If you find any difficulty in implementing the same, do let us know by commenting below.

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.