Blog

Shp to KML KMZ – Convert Shapefile to Keyhole Markup Language

Shapefile Shp to KML KMZ Convert. Many times you may want to render your shapefile directly in Google Map and check the view. Or you may want to convert the shapefile shp to KML so that it becomes easy to program with Google Map API. You can also check the file with Google Earth by loading KML converted from Shapefile.

KML is keyhole markup language file format, used to display geographic data on earth browser such as google earth and ArcGIS Explorer etc. This is XML tag-based structure. It is a highly portable single file that can contain all of a layer or map’s elements, such as feature geometry, imagery, symbology, descriptions, attributes, imagery, and other related content. Similarly .kmz  is spatial format, which is a compressed or zipped file of KML extension. In GIS vector and raster data formats are saved differently where as KML composed of including elements as line point polygon and imagery. While shapefile is a Vector file, comprised of three files i.e .shp, .shx and .dbf extension.

Checkout Online tool To convert Shapefile to KML or KMZ

KML File Format To Know Before Converting from Shapefile or SHP

Before taking a look on Converting Shapefile to KML or KMZ file, lets first look over how KML file look like. This is essential as if kml file is corrupted then conversion is not possible. And if you know file format, you can correct the same as we can edit the kml in text editor. If you already know the file format of KML, you may skip this step and look directly for Convert Shapefile shp to KML using ogr2ogr tool. Every geographic element such as point line or polygon is specified by different tags.

SHP to KML Conversion IGIS Map Tool

shp to kml

  • You can directly upload from your database or from Google drive or else from dropbox.

shp to kml

  • We are using google drive.  Once file upload is complete, select the output format. We tap on KML for output.

shp to kml

  • Click on Convert file button.

shp to kml

  • Here is your Converted Shp to Kml file. Tap on published button.

Download World Shapefile for project

Point Data KML file format – shp to kml

It contains geographic location, title and description as latitude and longitude.

<Placemark>
 <name>Simple placemark</name>
 <description>Attached to the ground. Intelligently places itself
 at the height of the underlying terrain.</description>
 <Point>
 <coordinates>-122.0822035425683,37.42228990140251,0</coordinates>
 </Point>
 </Placemark>

Line Data KML file format – shp to kml

Using style tag you can specify the color and width for lines.

<Style id="yellowLineGreenPoly">
 <LineStyle>
 <color>7f00ffff</color>
 <width>4</width>
 </LineStyle>
 <PolyStyle>
 <color>7f00ff00</color>
 </PolyStyle>
 </Style>
 <Placemark>
 <name>Absolute Extruded</name>
 <description>Transparent green wall with yellow outlines</description>
 <styleUrl>#yellowLineGreenPoly</styleUrl>
 <LineString>
 <extrude>1</extrude>
 <tessellate>1</tessellate>
 <altitudeMode>absolute</altitudeMode>
 <coordinates> -112.2550785337791,36.07954952145647,2357
 -112.2549277039738,36.08117083492122,2357
 -112.2552505069063,36.08260761307279,2357
 -112.2564540158376,36.08395660588506,2357
 -112.2580238976449,36.08511401044813,2357
 -112.2595218489022,36.08584355239394,2357
 -112.2608216347552,36.08612634548589,2357
 -112.262073428656,36.08626019085147,2357
 -112.2633204928495,36.08621519860091,2357
 -112.2644963846444,36.08627897945274,2357
 -112.2656969554589,36.08649599090644,2357
 </coordinates>
 </LineString>
 </Placemark>

The <tessellate> tag breaks the line up into smaller chunks, and the <extrude> tag extends the line down to the ground.

Polygon Data KML file format – shp to kml

<Placemark>
 <name>The Pentagon</name>
 <Polygon>
 <extrude>1</extrude>
 <altitudeMode>relativeToGround</altitudeMode>
 <outerBoundaryIs>
 <LinearRing>
 <coordinates>
 -77.05788457660967,38.87253259892824,100
 -77.05465973756702,38.87291016281703,100
 -77.05315536854791,38.87053267794386,100
 -77.05552622493516,38.868757801256,100
 -77.05844056290393,38.86996206506943,100
 -77.05788457660967,38.87253259892824,100
 </coordinates>
 </LinearRing>
 </outerBoundaryIs>
 <innerBoundaryIs>
 <LinearRing>
 <coordinates>
 -77.05668055019126,38.87154239798456,100
 -77.05542625960818,38.87167890344077,100
 -77.05485125901024,38.87076535397792,100
 -77.05577677433152,38.87008686581446,100
 -77.05691162017543,38.87054446963351,100
 -77.05668055019126,38.87154239798456,100
 </coordinates>
 </LinearRing>
 </innerBoundaryIs>
 </Polygon>
 </Placemark>

There are many option tags in KML.

Convert Shapefile SHP to KML KMZ

In this article we will have a look on how shapefile can be converted in KML. For conversion ogr2ogr command has used which should be written on terminal (command promt). You need to install ogr2ogr tool, which is open source tool and can be installed in Windows, Ubuntu, Mac or any other linux system.

Note that for converting shapefile to KML you must have shp along with shx file and dbf file. As shx file contains the positional index of the feature geometry whereas shp format contains geometry itself and dbf contains the data associated with the feature.

Command Format for using ogr2ogr tool to convert to kml :

---- ogr2ogr -f KML outputfilename.kml inputfilename.shp

Here is an example command line, to show how i had use ogr2ogr tool to convert the shp to kml file.

convert-shapefile to kml/kmz

Similarly you can convert shapefile to KML using QGIS tool.

Convert SHP to KML or KMZ using coding-

To convert in KMZ format you can just change the extension of output file from .kml to .kmz format. The option -f (output file format) remain same for both.

In PHP you can use this command using shell_exec() method. Here a function is created in which shapefile and Output file name is taken from user.

public function shptokml($shpfilepath,$output){
 $query= "ogr2ogr -f KML $output.kml $shpfilepath ";
 shell_exec($query);
 }

Similarly for KMZ, you can have a function as given below-

public function shptokmz($shpfilepath,$output) {
 $query="ogr2ogr -f KML output.kmz $shpfilepath";
 shell_exec($query);
 }

The converted output will contain all attribute details with their geographic location in latitude longitude form.

convert-shapefile to kml/kmz

Note-

KML only supports EPSG: 4326 i.e. +proj=longlat +datum=WGS84 . So you can not change the coordinate system of KML. But you can change the coordinate system of shapefile before converting it in KML.

Similarly you may also look for converting shapefile to GeoJSON, Shapefile to Topojson, Shapefile to Geopackage, Shapefile to Postgresql, shapefile to CSV etc. Also you can look for reverse convert the same i.e from KML to shapefile using QGIS or ogr2ogr tool.

Hope you enjoyed this article and successfully converted shapefile into KML. If you find any difficulty during execution of this article please let us know by commenting below in the box provided.

Convert Shapefile to GeoPackage – GPKG

GeoPackage is an open, standards-based, platform-independent, portable, self-describing, compact format for transferring geospatial information. Whereas shapefile is collection of geometry with attribute detail. Here in this article, we will check how to convert Shapefile to GeoPackage or GPKG GIS format.

Online Tool To Convert Shapefile to GeoPackage file

The GeoPackage Encoding Standard describes a set of conventions for storing the following within an SQLite database:

1. Vector features
2. Tile matrix sets of imagery and raster maps at various scales
3. Attributes (non-spatial data)
4. Extension

Convert Shapefile to GeoPackage - GPKG
Convert Shapefile to GeoPackage – GPKG

You can open the gpkg (GeoPackage) file in QGIS software and see some of the general properties of gpkg (GeoPackage) file-

1. Storage type of this layer
–> GPKG
2. Description of this provider
–> OGR data provider (compiled against GDAL/OGR library version 2.2.2, running against GDAL/OGR library version 2.2.2)
3. Source for this layer
–> /var/www/html/PHP_pgrouting/public/outputllll.gpkg
4. Geometry type of the features in this layer
–> Line
5. The number of features in this layer
–> 19148
6. Capabilities of this layer
–> Add Features, Delete Features, Change Attribute Values, Add Attributes, Delete Attributes, Fast Access to Features at ID, Change Geometries, Presimplify Geometries, Presimplify Geometries with Validity Check
7. Extents
–> In layer spatial reference system units
xMin,yMin 68.4982,7.92528 : xMax,yMax 97.3348,35.5013
8. Layer Spatial Reference System
–> +proj=longlat +datum=WGS84 +no_defs

Convert Shapefile to GeoPackage – GPKG  using OGR2OGR-

The command has some options, which can be seen by typing ogr2ogr in terminal. If this gives you error that means you don’t have ogr2ogr utility in your system. To install that you can follow the statements given below-

If Ogr2ogr utility is available, you will see the following result.

The command is given as-

–> ogr2ogr -f GPKG outp_gpkg.gpkg India_raods.shp

The command contains Utility name, option for file format, name for format, output file with .gpkg extension and input shape file.

To install ogr2ogr utility-
Convert Shapefile to GeoPackage - GPKG
Convert Shapefile to GeoPackage – GPKG

To check  if ogr2ogr utility is working properly or not-

Convert- Shapefile to GPKG- GeoPackage

Online Tool To Convert Shapefile to GeoPackage file

PHP Code to Convert Shapefile to GeoPackage – GPKG-

Using shell_exec() method, you can run the command in PHP. This return output as string.

public function shptogpkg($shpfilepath,$output) {
$query=”ogr2ogr -f GPKG $output.gpkg $shpfilepath.shp”;
shell_exec($query);
}

The output file can be open in QGIS software. I have converted Road File of one such country. Here is the output look in QGIS tool after Converting Shapefile to GeoPackage.

Convert Shapefile to GeoPackage - GPKG

Change Coordinate system of Output-

Many of times, we need the output file in other coordinate system. For this we can use options of ogr2ogr utility. It has

-a_srs srs_def:

Assign an output SRS

-t_srs srs_def:

Reproject/transform to this SRS on output

-s_srs srs_def:

Override source SRS

So using these option we can get the data in required coordinate system. So for this you can write the query as-

—> ogr2ogr -f GPKG -s_srs EPSG:4326 -t_srs EPSG:32643 Output_file_name.gpkg Input_file_name.shp

Here define old EPSG (European Petroleum Survey Group) in -s_srs option and new in -t_srs option.

You may also Check Shapefile to GeoJSON, Shapefile to KML, Shapefile to TopoJSON, etc conversion.

Let me know if you find any problem in converting Shapefile to GeoPackage file, by commenting below in the box provided.

Earthquake Map – Create EarthQuake Map GIS

An earthquake (also known as a quake, tremor or temblor) is the shaking of the surface of the Earth, resulting from the sudden release of energy in the Earth’s lithosphere that creates seismic waves. Earthquakes can range in size from those that are so weak that they cannot be felt to those violent enough to toss people around and destroy whole cities. The seismic or seismic activity of an area refers to the frequency, type and size of earthquakes experienced over a period of time.

Earthquake is a nature’s most unpredictable and one of her most devastating natural disasters. When high intensity earthquakes strike they can cause thousands of deaths and billions of dollars in damaged property. For decades, experts have studied major earthquakes; most have focused on fatalities and destruction in terms of the primary effects, the shaking unleashed.
At the Earth’s surface, earthquakes manifest themselves by shaking and sometimes displacement of the ground. When the epicenter of a large earthquake is located offshore, the seabed may be displaced sufficiently to cause a tsunami. Earthquakes can also trigger landslides, and occasionally volcanic activity.

Worldwide, at least 133 earthquakes occurred in 2011, during which people died, were injured or lost their homes or which caused immense damage to property.
The intensity value of earthquake is divided in 9 parts as given below

Earthquake Map

About Demo-

Earthquake information of Padang, Indonesia is shown using raster Geo-tiff file. Padang is the capital of the province of West Sumatra in Indonesia. The intensity of earthquake on map can be represent by color variation from dark to light shade. Here dark shade shows high shocks and light color medium and low shocks. These intensity value can be extract from layer using Grey band information.

Data Preparation:

This demo shows the raster overlay on map with the help of Leaflet JavaScript library. Here raster data is in Geo Tiff format and is published on Geo server. For this demo we have downloaded data from http://geonode.inasafe.org/layers/geonode:padang_eq_2009_wgs84 website. It is a raster data containing single Grey band. In this demo we render raster data on map and shown the value of earthquake intensity using pop-up on marker.

Raster data on GeoServer and styling:

GeoServer is an open source server for sharing geospatial data in both vector and raster format. It is designed to host major data sources, which can easily render on maps.
To Download and install GeoServer please follow the last article. Then login to the GeoServer and publish data on the Geoserver and get the link from layer preview section. You can visit the articles to know how to publish and style the GeoTiff file on Geoserver.

Render Raster on Map:

Before rendering tiles on map, you need to create a division in html that will contain map. You also can set its view by providing center latitude and longitude with zoom level.

var map = L.map(‘map’).setView([-1.03705, 99.64336],8);
var searchLayer ;
L.tileLayer(‘http://{s}.tile.osm.org/{z}/{x}/{y}.png’, {
attribution: ‘&copy; <a href=”http://osm.org/copyright”>OpenStreetMap</a> contributors’
}).addTo(map);

To render this data on map, we need to get the data from GeoServer, which can be done by using leaflet javascript library. In the Leaflet library we have Leaflet-WMS plugin.
What is WMS service: WMS (web map service), is a way of publishing maps. This format is similar to map tiles. A WMS image is defined by the coordinates.

For styling purpose we have used geoserver styling option, where you can style your data according to your attributes or bands etc.

NamedLayer – name of the layer.

<FeatureTypeStyle>
<Rule>
<Name> RUle style </Name>
<Title>Opaque Raster</Title>
<Abstract>A raster with 100% opacity</Abstract>
<RasterSymbolizer>
<Opacity>1.0</Opacity>
<ChannelSelection>
<GrayChannel>
<SourceChannelName>1</SourceChannelName>
</GrayChannel>
</ChannelSelection>
<ColorMap extended=”true”>
<ColorMapEntry color=”#00FA08″ quantity=”0″/>
<ColorMapEntry color=”#F6FA00″ quantity=”2″/>
<ColorMapEntry color=”#FA9F00″ quantity=”3″/>
<ColorMapEntry color=”#FA4C00″ quantity=”6″ />
<ColorMapEntry color=”#A21612″ quantity=”9″/>
</ColorMap>
</RasterSymbolizer>
</Rule>
</FeatureTypeStyle>

L.tileLayer.wms:

It provides a simple interface for loading tiles from a WMS service. This facility is given in Leaflet javascript library we just need to add its plugin. Here we also need to provide layer name, format of layer and make transparent as true.

var raster = L.tileLayer.wms(‘http://139.59.42.235:8080/geoserver/portfolio/wms?’, {
layers: ‘padang_eq_2009_wgs84’,
format: ‘image/png’,
transparent: true
}).addTo(map);

Intensity of earthquake is denoted by color ramp. To know the value of earthquake intensity at particular location, we can place the marker and can read the popup. Delete button is given to delete all markers.

function showGetFeatureInfo(latlng, layer){
var prop = layer.features[0].properties;
var mark=L.marker([latlng.lat,latlng.lng]).addTo(map);
var gray=prop[‘GRAY_INDEX’];
mark.bindPopup(“Earthquake Value: “+gray.toString());
}

Convert Shapefile to CSV

Sometimes shapefile becomes bulky to carry from one place to another. As it contains various files as .shp, .prj, .shx, .dbf etc. On the other side CSV contains every detail in one file. So CSV can be considered as a good option when you don’t need to render data on map as polygon or polyline or point. There are various options to create CSV from a shapefile either offline or online.

CSV is comma separated value file which is one of the alternative method for storing spatial data in spreadsheet format. You can also upload the Excel file and convert it into spatial data via QGIS tool. There are also other online tools available which can directly convert the Shapefile to CSV. We will show you how easy and useful is IGISMAP for the conversion process. Following are the methods to convert Shapefile to CSV using IGISMAP Converter tool.

IGISMAP (now MAPOG) to Convert Shapefile to CSV

Go to MapOG Converter Tool Shapefile to CSV, 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 KML file of California state boundary.

Step two is to select choose the output format of the converted file, in this case its CSV. 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 - CSV as Output Format
Select CSV as Output Format

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

Download and Publish CSV File
Download and Publish CSV File

The output CSV file is generated with location information represented in WKT format under the field named ‘WKT’.

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

Shapefile to CSV conversion – OFF-Line (command line) Tool

For using off-line command in your system you need to install ogr2ogr. There is very simple command to convert shapefile to csv file if you dont want to install a bulky GIS tool like QGIS or ArcGIS.

I am giving a way to install GDAL on ubuntu, while the process is almost similar to install the GDAL tool in Windows, Mac or other Linux system.

For installing GDAL for Ubuntu please follow the given commands.

Shapefile to CSV conversion
Shapefile to CSV conversion

After installing you can check the availability of ogr2ogr by typing ogr2ogr on terminal.

Shapefile to CSV conversion

After that you can follow the command to convert the shapefile to csv (comma separated value format file)

–> ogr2ogr -f CSV output_file_name.csv input_shp_name.shp -lco GEOMETRY=AS_WKT

The same work can be done in code-igniter or using PHP. For that you need to execute this command in shell_exec() method, which takes the command in string format and returns the output in string.

–>  $shpToCSV=”ogr2ogr -f CSV $out.csv $shp.shp -lco GEOMETRY=AS_WKT”;
–>  shell_exec($shpToCSV);

These statements are written in PHP. $ signifies the variable. Here input and output is taken from user and command is written in double quotes to convert in string. Then it is given to shell_exec() method.

Shapefile to CSV conversion – With QGIS Open source Software

If you don’t need to install any library or run online tools as you already have installed GIS software. You can convert shapefile in CSV using GIS software also. You just need to open the shapefile as vector layer and save it as CSV. For adding the vector layer tyou need to go to Layer->add vector layer and browse the shapefile. After the right click on shapefile title and save it as csv. you can also save some selected part.

Shapefile to CSV conversion

You may also look on other Conversion of Files like Shapefile to KML or Shapefile to GeoJSON or GeoJSON to TopoJSON etc.

In this way you can convert shapefile in CSV format. Hope you find tutorial of shapefile to CSV conversion is helpful for you. If you find any problem in converting GIS data in CSV format, do comment below with the problem statement. Also if you know any other tool for converting shapefile, do provide your suggestion in the provided box below.

Split Sub Divide polygon layer using QGIS – Shapefile, kml, GeoJson

Sub divide or split polygon in multiple parts. QGIS is a special spatial tool, which easily operate with GIS data files such as shapefile, kml or geojson. You might find many cases, where you need to split up polygon or diivde polygon in different parts. For instance, lets suppose we have  administrative boundary shapefile of US and have an image file of sub administrative part, and we need an output shapefile of sub administrative part. For making this possible we need to divide or split up the polygon with the tool.  Here in this article, we are splitting up the existing polygon shapefile data file.

You can also try Online Split Tool To split the polygon in equal parts with MAPOG

Pre Requisite for Split Sub Divide polygon layer using QGIS

I will use digitizing tool plug-in to split the polygon into multiple polygons. I have already written about digitize in QGIS, but to be specific to split of polygon this article would demonstrate you in more detail. Following are the pre requirement to perform split operation:

1.) QGIS Software as tool

2.) Polygon Shapefile as Data

3.) Installed plugin Digitizing tools : This plug-in can be install by navigate yourself to plug-in tab->Manage and install plug-in->Digitizing Tool->install.

Split or Sub Divide polygon layer using QGIS

Split Sub Divide polygon layer using QGIS : Steps

For example we need to subdivide the below polygon in two different polygons:

Split or Sub Divide polygon layer using QGIS
Split or Sub Divide polygon layer using QGIS

To achieve our target we need to implement following steps:

1. Add your polygon shape file to canvas.

2. For spliting up polygon we first need to convert polygon shapefile to polyline shapefile. To convert polygon to polyline, QGIS provides a direct way to do the same. Just select Vector tab from the menu, and navigate to Geometry tools options and Select Polygon to line, as shown in figure:

Split or Sub Divide polygon layer using QGIS

Select the polygon layer and run this tool. the output layer will be line Shapefile as shown below.

Split or Sub Divide polygon layer using QGIS

3. Now we need to Edit the output line shapefile.  This can be done by enabling editing option. Then draw the line in the way you want to split your polygon data.

Split or Sub Divide polygon layer using QGIS
Split or Sub Divide polygon layer using QGIS

At the time of adding lines you need to join vertices for proper topology for that you can use the snapping tool.

Split or Sub Divide polygon layer using QGIS

4. Now line and polygon files are available. Now turn on both layers in canvas and select polygon shape file, then the line. Then enable editing for polygon shapefile you will see the digitizing tools in toolbar.

Split or Sub Divide polygon layer using QGIS
Split or Sub Divide polygon layer using QGIS

After that select “Split selected feature with selected line from another layer” tool. Note that the polygon and line both should be selected to run this tool.

Split or Sub Divide polygon layer using QGIS

5. Repeat this step to make more divisions. The output file would be as shown below

Split or Sub Divide polygon layer using QGIS
Split or Sub Divide polygon layer using QGIS

7. Now correct attribute table as all the split polygons will have same entries in attribute table.

In this way you can split the polygon into multiple polygon entity. If you find any problem in Split Sub Divide polygon – Shapefile, kml, GeoJson data, then do comment below with the problem statement, so that we can look for solution together. Or if you know any other method to split the polygon do let us know by commenting below in the box provided.

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.