Install PostGIS and PostgreSQL in Linux Ubuntu 16.4

In this post we are going to talk about How to install PostGIS and PostgreSQL in ubuntu 16.4 (LTS) or Linux system. As we know geographic information system (GIS) is a system designed to capture, store, manipulate, manage, and present spatial or geographic data. And PostGIS adds support for geographic objects allowing location queries to be run in SQL database. As PostGIS is a spatial database extender for PostgreSQL object-relational database. So without wasting time, Let’s start the post to know How to install PostGIS and PostgreSQL in your system.

Intro to PostGIS and PostgreSQL – Install

What is PostGIS?

PostGIS is an open source software program that adds support for geographic objects to the PostgreSQL object-relational database. PostGIS follows the Simple Features for SQL specification from the Open Geospatial Consortium (OGC).

Technically PostGIS was implemented as a PostgreSQL’s extension. And There are a large number of software products that can use PostGIS as a database backend.

The PostGIS implementation is based on “light-weight” geometries and indexes optimized to reduce disk and memory footprint. Using light-weight geometries helps servers increase the amount of data migrated up from physical disk storage into RAM, improving query performance substantially.

PostGIS is registered as “implements the specified standard” for “Simple Features for SQL” by the OGC. PostGIS has not been certified as compliant by the OGC.

What is PostgreSQL?

PostgreSQL, often simply Postgres, is an object-relational database management system (ORDBMS) with an emphasis on extensibility and standards compliance. As a database server, its primary functions are to store data securely and return that data in response to requests from other software applications. It can handle workloads ranging from small single-machine applications to large Internet-facing applications (or for data warehousing) with many concurrent users; on macOS Server, PostgreSQL is the default database and it is also available for Microsoft Windows and Linux (supplied in most distributions). PostgreSQL is a powerful, open source object-relational database system and It runs on all major operating systems.

It is fully ACID compliant, has full support for foreign keys, joins, views, triggers, and stored procedures (in multiple languages)
PostgreSQL supports compound, unique, partial, and functional indexes which can use any of its B-tree, R-tree, hash, or GiST storage methods. GiST(Generalized Search Tree) serves as a foundation for many public projects that use PostgreSQL such a OpenFTS and PostGIS. And as I described above PostGIS is a project which adds support for geographic objects in PostgreSQL, allowing it to be used as a spatial database for geographic information systems (GIS), much like ESRI’s SDE or Oracle’s Spatial extension.

Install PostGIS and PostgreSQL

Installation of PostGIS and PostgreSQL is much simpler then you think. PostgreSQL is available in all Ubuntu versions by default. However, Ubuntu “snapshots” a specific version of PostgreSQL that is then supported throughout the lifetime of that Ubuntu version. Other versions of PostgreSQL are available through the PostgreSQL apt repository.
The PostgreSQL apt repository supports LTS versions of Ubuntu (14.04 and 16.04) on amd64, i386 and ppc64el architectures as well as select non-LTS versions(17.04). While not fully supported, the packages often work on other non-LTS versions as well, by using the closest LTS version available.
The following describes how to install Postgresql 9.6, PostGIS 2.3, pgRouting 2.3, PGAdmin on Ubuntu version 16.04. It is assumed to also work on Linux Mint, Lubuntu, and Xubuntu.
Run these in terminal:

  • Verifying version of ubuntu
    sudo lsb_release -a
  • Add Repository to sources.list

    For xenial (16.4.2 LTS)

    sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt xenial-pgdg main" >> /etc/apt/sources.list'
  • Adding keys
    wget --quiet -O - http://apt.postgresql.org/pub/repos/apt/ACCC4CF8.asc | sudo apt-key add - 
    sudo apt-get update
  • Installation

    The following will install postgresql 9.6, PostGIS 2.3, PGAdmin4, pgRouting 2.3 and additional supplied modules including the adminpack extension:

    sudo apt-get install postgresql-9.6
    
    sudo apt-get install postgresql-9.6-postgis-2.3 postgresql-contrib-9.6
    
    postgresql-9.6-postgis-scripts
    
    #to get the commandline tools shp2pgsql, raster2pgsql you need to do this
    sudo apt-get install postgis
  • To get pgRouting
    # Install pgRouting 2.3 package
    sudo apt-get install postgresql-9.6-pgrouting

Now we have successfully installed PostgreSQL and PostGIS into the system and pgAdmin lets you create everything using user interface. You don’t need to remember queries to create tables sequence etc. But I am still showing how to create the database from command line .

You may look over full pgRouting postgresql post in detail.

  • Enable Adminpack

    While in terminal, log in to the psql console as postgres user:

    sudo -u postgres psql
    CREATE EXTENSION adminpack;

    Never install PostGIS in the postgres database, create a user database You can also enable the PostGIS extension here (or with the GUI as described below):

    sudo -u postgres psql
    CREATE DATABASE gisdb;\connect gisdb;
    
    CREATE SCHEMA postgis;
    
    ALTER DATABASE gisdb SET search_path=public, postgis, contrib;
    
    \connect gisdb; 
     -- this is to force new search path to take effect
    
    CREATE EXTENSION postgis SCHEMA postgis;
    
    SELECT postgis_full_version();

    should give you output something like this:

                           postgis_full_version
    -----------------------------------------------------------------------
    POSTGIS="2.4.3 r16312" PGSQL="96" GEOS="3.5.0-CAPI-1.9.0 r4084" PROJ="Rel. 4.9.2, 08 September 2015" GDAL="GDAL 1.11.3, released 2015/09/16" LIBXML="2.9.3" LIBJSON="0.11.99" LIBPROTOBUF="1.2.1" RASTER
    (1 row)
  • Install pgRouting – postgis and postgresql

    CREATE  EXTENSION pgrouting;
    SELECT * FROM pgr_version();

    should give you:

    version |  tag   |   hash    | branch | boost
    --------+--------+-----------+--------+--------
      2.5.2 | v2.5.2 | 60585f1f7 | master | 1.58.0
    (1 row)
  • Exit the psql console:
    \q

    This is how we can make database and create schema in command line .

Now let’s see how we can do it in pgAdmin :

PgAdmin – Install PostGIS and PostgreSQL

PostgreSQL has a number of administrative front-ends. The primary one is psql a command-line tool for entering SQL queries. Another popular PostgreSQL front-end is the free and open source graphical to pgAdmin. All queries done in pgAdmin can also be done on the command line with psql.

  • Find pgAdmin and start it up.

    Install PostGIS and PostgreSQL
    Install PostGIS and PostgreSQL
  • If this is the first time you have run pgAdmin, you should have a server entry for PostGIS (localhost:5432) already configured in pgAdmin. Double click the entry, and enter anything you like at the password prompt to connect to the database.
    The PostGIS database has been installed with unrestricted access for local users (users connecting from the same machine as the database is running). That means that it will accept any word you provide. If you need to connect from a remote computer, the password for the PostgreSQL user has been set to PostgreSQL.

Creating a Database

  •  Open the Databases tree item and have a look at the available databases. The PostgreSQL database is the user database for the default PostgreSQL user and is not too interesting to us.
  • Right-click on the Databases item and select New Database.
    Install PostGIS and PostgreSQL
  • Fill in the New Database form as shown below and click OK.
     Name   |  nyc     |
     -------+----------+
     Owner  | postgres |

    Install PostGIS and PostgreSQL
    Install PostGIS and PostgreSQL
  • Select the new nyc database and open it up to display the tree of objects. You’ll see the public schema.
    Install PostGIS and PostgreSQL
  • Click on the SQL query button indicated below (or go to Tools > Query Tool).Install PostGIS and PostgreSQL
  • Enter the following query into the query text field to load the PostGIS spatial extension:
    CREATE EXTENSION postgis;
  • Click the Play button in the toolbar (or press F5) to “Execute the query.”
  • Now confirm that PostGIS is installed by running a PostGIS function:
    SELECT postgis_full_version();

You have successfully created a PostgreSQL database with PostGIS!! Let us know by commenting below if you have faced any problem in Install PostGIS and PostgreSQL. Or comment below with the trick you have applied to install postgis.

PGrouting PostGIS Postgresql – No need for Google routing

Do you have all road data with you and want to creating routing from that according to your algorithm? Needs an alternative to Google Map API, when having your own road datasets? PGrouting with PostGresSql can help you out by doing that. Here in this post we will look for PGRouting PostGreSql implementation steps by steps and finding the direction with PGRouting. Connection between PostGres and QGIS and query data and see the result in QGIS Desktop.

Prerequisite for PGrouting PostGIS Postgresql:

  • Installed QGIS and installed PostGreSql
  • Basic Knowledge of PostGreSQL
  • Basic knowledge with QGIS Desktop
  • Road Map Shapefile

Here we will consider Road Map Shapefile, on which we will query and get the routing. In this article we will see how we can query the road network shapefile to find out the shortest path. The results can be seen in QGIS Desktop software. Here postGIS is used to generate road network. In this tutorial we have id of each route, which is used to query the shortest route. You will understand more easily once you read this article throughly. Here PGrouting has used to find out the shortest path.

Install Postgresql PostGIS PGRouting:

Its installation is simple process include few steps (written an article for linux based system). Here are few points for installing postgresql PGRouting:

# Create the file /etc/apt/sources.list.d/pgdg.list, and add a line for the repository

--> sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ CODENAME-pgdg main" > /etc/apt/sources.list.d/pgdg.list'

The codename can find by using given command

 --> lsb_release -cs

Output:

 Codename xanial

Then replace this codename in command.

# Import the repository key, update the package lists

--> sudo apt-get install wget ca-certificates
 --> wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
 --> sudo apt-get update

# Install PGrouting based on your postgresql Installation:

--> sudo apt-get install postgresql-9.6-pgrouting

To be up to date with changes and improvements follow the given command

--> sudo apt-get update & sudo apt-get upgrade

PGRouting PostGreSql PostGIS Shortest Path Steps:

In this article we are using postgres 9.6, PostGIS 2.4.2 and Pgrouting 2.5.2. It is better to check versions for all required software as query syntax change with version. Firstly create a database.

1. Create database in PostGreSql for PGRouting:

You can create a database in Ubuntu terminal. For that you need to follow the given command-

 --> sudo -u postgres createdb -O DATABASE_USER DATABASE_NAME

where -U username, Createdb is command which create new postgresql database, -O output file name, last two options are Database user-name and name for database. For more option in psql visit https://www.postgresql.org/docs/9.0/static/app-psql.html link.

2. Add shape file in postgresql pgrouting database:

If you are using pgAdmin3 then you can open the database by providing user name and password.

In Database you can add shapefile by clicking option PostGIS shape file and DBF loader. Here first off define the user-name with proper password and database name. Then add shape file and import it.

You can use this link to import or upload Shapefile in PostGreSql database.

Now refresh the database and expand public-> tables option you see the shape file’s attribute table.

3. Add Source and target column in attribute table:

The given command will add column in attribute table, named as source and target with integer data type. Here roads_table is the attribute table or imported shape file.

--> ALTER TABLE roads_table ADD COLUMN "source" integer;
--> ALTER TABLE roads_table ADD COLUMN "target" integer;

4. Create topology – PGRouting:

Here you must be aware of what is topology when working with spatial system. Topology is a set of rules and behaviours that model how points, lines, and polygons share coincident geometry.

Here creating topology means attaching nodes to every end point of route. This is done using method from pgrouting that is pgr_createTopology().
This takes table name, tolerance, geom field name and id as inputs.

--> SELECT pgr_createTopology('roads_table', 0.001, 'the_geom', 'id')

More detailed explanation is given below:

The topology creation function accepts the following parameters:

-> edge_table:

Text Network table name. (may contain the schema name AS well)

-> tolerance:

Float8 Snapping tolerance of disconnected edges. (in projection unit)

-> the_geom:

Text Geometry column name of the network table. Default value is the_geom.

-> Id:

Text Primary key column name of the network table. Default value is id.

-> Source:

Text Source column name of the network table. Default value is source.

-> Target:

Text Target column name of the network table. Default value is target.

-> rows_where:

Text Condition to SELECT a subset or rows. Default value is true to indicate all rows that where source or target have a null value, otherwise the condition is used.

-> Clean:

Boolean Clean any previous topology. Default value is false.

For more details: http://docs.pgrouting.org/2.2/en/src/topology/doc/pgr_createTopology.html

5. Create network table – PGrouting PostGIS Postgresql:

This table contains all information such as gid, length of routes, name of roads, source and target. Here source and target is taken from node table where as other information from attribute table. For this first we need to create node table.

In node table you have source as a start_id and target as end_id.

CREATE TABLE node AS
 SELECT row_number() OVER (ORDER BY foo.p)::integer AS id,
 foo.p AS the_geom
 FROM (
 SELECT DISTINCT roads_table.source AS p FROM roads_table
 UNION
 SELECT DISTINCT roads_table.target AS p FROM roads_table
 ) foo
 GROUP BY foo.p;

This explains that distinct values of source and target from roads_table table is selected and union operation has performed. Then number of rows are selected from this union table and saved them in node table.

CREATE TABLE network AS
 SELECT a.*, b.id as start_id, c.id as end_id
 FROM roads_table AS a
 JOIN node AS b ON a.source = b.the_geom
 JOIN node AS c ON a.target = c.the_geom;

This query explains that in network table b.id is named as start_id and c.id as end_id.

Now we will use pgr_dijkstra method from PGrouting PostGIS Postgresql

The minimal syntax is given

pgr_dijkstra(TEXT edges_sql, BIGINT start_vid, BIGINT end_vid)
 RETURNS SET OF (seq, path_seq, node, edge, cost, agg_cost) or EMPTY SET

This returns seq, path sequence, node, edge, cost, agg_cost fields.

Select seq, node, edge,cost, geom from pgr_dijkstra(
 'Select gid as id, source, target, st_length(geom) as cost from network', 3566,20051, false) as di
 JOIN network pt
 ON di.edge = pt.gid ;

Here we have joined network table to select geometry field. This all command would be running in SQL window in DB manager option in QGIS.

You can create a shape file as a result for query. For that you need to click on load as new layer option then provide geom as geometry option and edge as column with unique values and click load. The result layer will be added to canvas of QGIS.

PgRouting PostGIS PostGreSql using Latitude Longitude for source and destination:

You just need to change the last command in SQL window of QGIS software.

Select seq, node, edge,cost, geom, agg_cost from pgr_dijkstra(
 'Select gid as id, source, target, st_length(geom::geography)/1000 as cost from network',(SELECT source FROM network
 ORDER BY geom <-> ST_SetSRID(ST_Point
 (74.862413,24.476381),4326) LIMIT 1),
 (SELECT source FROM network
 ORDER BY geom <-> ST_SetSRID(ST_Point
 (75.857734,22.719588),4326) limit 1), false) as di
 JOIN network pt
 ON (di.edge = pt.gid);

This query explains that we are using pgr_dijkstra from pgrouting which takes sql_text,integer start_id, integer end_id and boolean type for directed route. If route is directed, give input as true otherwise false. Here in this article we have undirected route. As now in place of we want to give latitude and longitude so for that given query has executed.

SELECT source FROM network ORDER BY geom <-> ST_SetSRID(ST_Point (75.857734,22.719588),4326) limit 1

This part is little interesting, first of all we need to understand that always we provide latitude longitude of point(place), not of any line (road). So this point can be restaurant, stops, hotels or hospitals etc.

Now the very first task is to find out the nearest path from these points. For that we used <-> from postgis.

<-> — Returns the distance between two points.

Now we may have 2 or more path from selected point. So the shortest one should be selected from these path, For that we used order by command which arranges these path in ascending order and after that limit 1 command selects top most 1 row, which his nothing but the shortest path from source to path. Similar concept is applied on end point also.

Syntax of postgresql:

double precision <->( geometry A , geometry B );

The <-> operator returns the 2D distance between two geometries. Used in the “ORDER BY” clause provides index-assisted nearest-neighbor result sets. For PostgreSQL below 9.5 only gives centroid distance of bounding boxes and for PostgreSQL 9.5+, does true KNN (K nearest neighbor) distance search giving true distance between geometries, and distance sphere for geographies.

Syntax of postgresql:

geometry ST_SetSRID(geometry geom, integer srid); 
geometry ST_Point(float x_lon, float y_lat);

In ST_Point we give source and destination latitude longitude. Using ST_SetSRID Set the SRID on a geometry to a particular integer value. Here EPSG 4326 is used which is WGS84 datum. EPSG stands for European Petroleum Survey Group, They publish a database of coordinate system information. SELECT source FROM network this returns source id. Similarly got source id of end point. Then cost is set as length of route in kilometers. All these provided to pgr_dijsktra method and join network table to take geometry as output to show result in QGIS.

Output of PGrouting PostGIS Postgresql – No need for Google routing

Here is the output of route which is rendered with QGIS Desktop, where green color indicates the road network and red color display the shortest distance we get from A and B.

PGrouting PostGIS Postgresql - No need for Google routing
PGrouting PostGIS Postgresql – No need for Google routing

We got good results as distance from A to B is calculated as 368Km and on Google map it is 361 km. Similarly many points have tested and result vary from 6 to 8Km.

Did you tried PGRouting postgis postgresql? If you are facing any issue, do let us know by commenting below with the solution.

KML to GML – Convert Keyhole to Geography

Sometimes we need to convert KML to GML where the software supports GML language. But before converting Keyhole markup language to Geography markup language, you should know the basic structure of KML and GML. So that if the file is corrupted then before converting it you can correct it manually and process the same in any GIS converter software to work properly. If you already know structure of this files, then you can directly navigate to the main topic i.e kml to gml conversion of this page.

Here is the Online Converter Tool from KML To GML 

Know KML and GML data structure before converting kml to gml

WHAT IS KML (Keyhole Markup Language)? – KML (Keyhole Markup Language), is an XML grammar and file format for modeling and storing geographic features such as points, lines,images, and polygons for display in the Google Earth client.KML is based on GML, although it doesn’t formally import GML schemas. KML language is used by a variety of GIS and mapping applications and the specifications are freely available to the public and available to the user community without charge or restriction. The Google Earth client supports a number of display features for rich presentation of GIS data. All of the features supported by the Google Earth client are described in KML. The Google Earth client supports a number of two-dimensional geometric shapes for display in the 3D viewer.

<Schema name="roads" id="roads">
 <SimpleField name="MED_DESCRI" type="string"></SimpleField>
 <SimpleField name="RTT_DESCRI" type="string"></SimpleField>
 <SimpleField name="F_CODE_DES" type="string"></SimpleField>
 <SimpleField name="ISO" type="string"></SimpleField>
 <SimpleField name="ISOCOUNTRY" type="string"></SimpleField>
 <SimpleField name="Length_km" type="float"></SimpleField>
 <SimpleField name="Latitude" type="string"></SimpleField>
 </Schema>
 <Folder><name>roads</name>
 <Placemark>
 <Style><LineStyle><color>ff0000ff</color></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
 <ExtendedData><SchemaData schemaUrl="#roads">
 <SimpleData name="MED_DESCRI">Without Median</SimpleData>
 <SimpleData name="RTT_DESCRI">Secondary Route</SimpleData>
 <SimpleData name="F_CODE_DES">Road</SimpleData>
 <SimpleData name="ISO">IND</SimpleData>
 <SimpleData name="ISOCOUNTRY">US</SimpleData>
 <SimpleData name="Length_km">0.3</SimpleData>
 </SchemaData></ExtendedData>
 <LineString><coordinates>77.8277403975188,35.5012774951028 77.8257523065223,35.4995003281062</coordinates></LineString>
 </Placemark>

WHAT IS GML (Geography Markup Language)? GML (Geography Markup Language) is only concerned with the representation of the geographic data content. While GML is an effective means for transporting geographic information from one place to another we expect that it will also become an important means of storing geographic information as well.

<gml:boundedBy>
 <gml:Box>
 <gml:coord><gml:X>-164404.6900820375</gml:X><gml:Y>893749.1179630321</gml:Y></gml:coord>
 <gml:coord><gml:X>2727970.187011702</gml:X><gml:Y>3932312.865004988</gml:Y></gml:coord>
 </gml:Box>
 </gml:boundedBy>
 <gml:featureMember>
 <ogr:raods fid="raods.0">
 <ogr:geometryProperty><gml:LineString srsName="EPSG:32643"><gml:coordinates>756486.657418272,3932312.4133327 756311.93383727,3932110.06520674</gml:coordinates></gml:LineString></ogr:geometryProperty>
 <ogr:MED_DESCRI>Without Median</ogr:MED_DESCRI>
 <ogr:RTT_DESCRI>Secondary Route</ogr:RTT_DESCRI>
 <ogr:F_CODE_DES>Road</ogr:F_CODE_DES>
 <ogr:ISO>IND</ogr:ISO>
 <ogr:ISOCOUNTRY>US</ogr:ISOCOUNTRY>
 <ogr:Length_km>0.3</ogr:Length_km>
 <ogr:Latitude xsi:nil="true"/>
 </ogr:USraods>
 </gml:featureMember>
 <gml:featureMember>

Convert KML to GML using Ogr2ogr utility-

For using this utility you need to install GDAL OGR2OGR in your system. To  install this you can follow the given commands.

KML to GML - Convert Keyhole to Geography
KML to GML – Convert Keyhole to Geography

If you have already install ogr2ogr utility you can check by typing ogr2ogr in terminal.

KML to GML - Convert Keyhole to Geography

Now run the given command to convert from KML to GML-

--- ogr2ogr -f 'GML' Output_GML.gml Input_KML.kml

Changing Coordinate System of Output File kml to gml-

Sometimes we need different coordinate system. So to get different coordinate system from input you can follow this given command.

--- ogr2ogr -f 'GML' -t_srs EPSG:32643 -s_srs EPSG:4326 Output_GML.gml Input_KML.kml

Convert KML (KeyHole Markup Language) to GML (Geography Markup Language) Using PHP Code-

If you want the conversion using programing or don’t want to use terminal then this can also be done using PHP. You can create a function that defined this command as string and can give this string in shell_exec() method to execute. Shell_exec() actually execute the command and returns output as string.

public function kmltogml($kmlfilepath,$output,$srsno,$srsold){
 $query="ogr2ogr -f GML -t_srs EPSG:$srsno -s_srs EPSG:$srsold $output.gml $kmlfilepath";
 shell_exec($query);
 }

Generated output of kml to gml –

KML to GML - Convert Keyhole to Geography
KML to GML – Convert Keyhole to Geography

If you have any problem regrading this tutorial, please let us know via comments  in provided comments box.

Embed HTML Google Map

It is not a whole HTML file or long scripts. It is just one HTML tags i.e  <iframe>,  to show map. On your computer, you can embed a map, Street View image, driving directions, or search of map 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. Lets see how to Embed HTML Google Map in your website.

There are three main part in iframe tag of google map which help us to set proper map.
1. Mode
2. API_key
3. parameter

Example of html iframe tag to embed html google map:

googlemaps : https://www.google.com/maps/embed/v1/MODE?key=YOUR_API_KEY &PARAMETER&w=600&h=450

Mode in google map link-

The mode section mainly consist place, directions, search, view, or streetview.

  • Place in google map link- Place displays a map of particular place or address, such as a landmark, famous building, geographic feature, or town.
  • Directions in google map link- mode displays the path between two or more specified points on the map, as well as the distance and travel time. Search- mode displays results for a search across the visible map region.
  • View- (streetview) mode returns a map with no markers or directions.

API_Key in Google Map to Embed html:

This is your free API key. You need to login to your mail account and navigate to

https://developers.google.com/maps/documentation/embed/get-api-key

link to get this API key.

Parameter in Google Map to embed html:

This includes some optional parameter which can be mode specified also.
The parameters are given as Center- To set this parameter you need to give comma separated latitude longitude value. This will set the map view in middle.

  • Zoom- To set Zoom level You need to give integer value from 0 to 21, where 0 defines the whole world view and 21 defines the building level zoomed view. This also depends on location selected and data availability of that location.
  • Map Type- there are two type of map roadmap or satellite. Region- defines the appropriate borders and labels to display, based on geo-political sensitivities.
  • Language- This set the language, which will be display on map tiles for User interface elements and labels available on map.

Other than these option we also have some option to set width and height of google map for html embed. We can also set frame border and style of that border. We can specify the allow full screen option to make map available on full window.

Steps to Embed HTML Google Map

Step 1:

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

Embed HTML Google Map

Step 2:

Sign in with Google account.

Step 3 to embed google map html:

click option menu and navigate to Your places-> maps-> create a map in bottom. A new window will open in new tab.

Embed HTML Google Map
Embed HTML Google Map

Step 4 to Embed HTML Google Map:

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

Embed HTML Google Map

Step 5:

You have two ways to add markers on map.

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

Embed HTML Google Map

2. You can specify the location by providing location or address. After adding markers on map you must save the locations.

Embed HTML Google Map

Step 6 to Embed HTML Google Map:

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.

Embed HTML Google Map

Step 7:

Then Click to option menu on title window and hit to embed on my site. This will provide you a link containing <iframe> tag. You can use this link any where you want.

Embed HTML Google Map
Embed HTML Google Map

You can use this iframe link in your web site to show your business location on map. Hope you enjoyed this tutorial.

There is much more for you as Embed Google map with 2 or more Markers for Web pages or any conversion as- shape file to KML and shapefile to GML etc.

If you face problem during implementation of this tutorial, please let us know via comments.

Publish Style Vector Dataset on GeoServer

GoeServer is one of the best server for storing Vector data. Geoserver is open source software and free to use. To know how to publish vector data and style it on Geoserver you can follow this tutorial. Before this you need to install Geoserver on your system for that read out our previous tutorial, install first GeoServer on Windows or Ubuntu operating system. You can also look for publish and style raster dataset in GeoServer.

GeoServer supports various Vector DataSet:

  • Shapefile
  • Directory of spatial files
  • Java Properties
  • GeoPackage
  • GML

Here we will use Shapefile as vector dataset as an example to publish and style in map in geoserver.

A shapefile stores non-topological geometry and attribute information for the spatial features in a data set. The geometry for a feature is stored as a shape comprising a set of vector coordinates whereas attribute information can be seen in the attribute table.

GeoServer has been optimized for serving large shapefile (GB size) with good speed. We need to publish shapefile and then using WMS service we can use data with high speed. The OGC Web Map Service (WMS) specification defines an HTTP interface for requesting georeferenced map images from a server.

How a shapefile can be published on geoserver is described below. The published and styled data will look something like image showed as feauregiven in the post . This geometry for shapefile is point and icon based styling has used.

Publish Style Vector Dataset on GeoServer

Publish Vector Data on GeoServer  – Host Shapefile SHP

We can publish many type of files on geoserver that can be in raster or vector format. In this tutorial we will see how we can publish shape file on GeoServer.

Start GeoServer application in your computer. It will run in command prompt then in web browser search localhost:8080/geoserver/web. Provide the Username and Password and click login to login as administrator of GeoServer.

Step 1 to publish vector data in geoserver:

First of all you need to login to GeoServer then create a workspace, which can be done by selecting workspace option on the right side of screen under data section. Add the new workspace give a name and URI. In information technology, a Uniform Resource Identifier (URI) is a string of characters used to identify a resource, which can be same as name and submit the information.

Publish Style Vector Dataset on GeoServer

Step 2:

Now add the store by selecting stores option under same section. Click Add new store and select shapefile or directory of spatial files. Under directory of spatial file add your work space and data source name. Under connection parameters browse your file location then click save option. After saving you will be able to publish the layer. Click publish option.

Publish Style Vector Dataset on GeoServer

Step 3 to publish vector data in geoserver:

after selecting publish option check the name of shape file. Under Coordinate Reference Systems heading check the coordinate system of your shape file. Under bounding boxes select Computes from SRS (spatial reference system) bound and in the next part select compute from native bound. Then save the information. After saving you will be able to see the shapefile name with your workspace and store name.

Publish Style Vector Dataset on GeoServer
Publish Style Vector Dataset on GeoServer

Step 4:

Now select the Layer Preview option under same section. And open your shape file using openLayer option in Command format column.

Publish Style Vector Dataset on GeoServer

As the layer is visible now you have a link in URL bar. You can add this link in QGIS using add WMS/WMTS layer and see the shape file.
Open QGIS and click the add WMS/WMTS layer option and then click new button to add new WMS layer.

Publish Style Vector Dataset on GeoServer
Publish Style Vector Dataset on GeoServer

Add the URL and click ok.

Publish Style Vector Dataset on GeoServer

Then connect the layer and add to display.

Shape file can contain point, line or polygon, which can be styled on geoServer. To style any feature on geoserver we required to add style name. This style can be customised. Some styling is already given in style option under Data section.

To add built in style to your shapefile follow the given steps-

Step 1:

First of all make sure your file has been added on server. Then open that layer using layer option in data section.

Step 2:

There will be 4 tabs as data, publishing, dimensions and tile caching. As on adding layer you already have visited data tab and set SRS coordinates. Now click publishing tab.

Publish Style Vector Dataset on GeoServer

In publishing tab find the WMS setting option, under that option check the Queryable checkbox and select style in default style dropdown.
There are styles for point, line, polygon and raster.
1. Burg: point
2. Dem: raster
3. Capitals: points
4. Roads: line
5. Lakes: polygon
6. Raster: raster
7. Point: point
8. Line: line
9. Polygon: polygon
10. Rain: raster
11. Population: raster
According to your shape file you can add the style and click to save.

Step 3 of style vector dataset in geoserver:

Now to check the styling click the layer preview option under same data section. Open as openLayer.

For more details you can visit http://docs.geoserver.org/latest/en/user/data/webadmin/layers.html website.

Styling Based on Attributes: Sometimes we need to style according to attributes. For example population greater than 5000, population equal to 5000 and population less than 5000 so we need some coding to define all these.

The Styled Layer Descriptor (SLD) Profile of the Web Map Service (WMS) Encoding Standard defines an encoding that extends the WMS standard to allow user-defined symbolization and colouring of geographic feature (vector data) and coverage data (raster data).

SLD (Styled Layer Descriptor ) has some elements in geoserver for vector dataset as :

The root element for an SLD is <StyledLayerDescriptor>. It contains a Layers and Styles elements which describe how a map is to be composed and styled.

  • <NamedLayer>: A reference to a named layer in the server catalogue
  • <UserLayer>: A layer defined in the style itself
  • <FeatureTypeStyle>: The FeatureTypeStyle element specifies the styling that is applied to a single feature type of a layer. It contains a list of rules which determine the symbology to be applied to each feature of a layer.
  • Under Rule element we specified filter with binary comparison operators PropertyIsEqualTo. Where property name is the attribute column you want to perform operation on and literal is the attribute value.
    <ogc:Filter>
    <ogc:PropertyIsEqualTo>
    <ogc:PropertyName>type</ogc:PropertyName>
    <ogc:Literal>balloonport</ogc:Literal>

In this article we have used Airport shape file, containing attributes as name and type of airports as point feature. So here we have styled this data based on type of airport.

  • PointSymbolizer: which styles features as points
  • LineSymbolizer: which styles features as lines
  • PolygonSymbolizer: which styles features as polygons
  • TextSymbolizer: which styles text labels for features
  • RasterSymbolizer: which styles raster coverages

<PointSymbolizer> in geoserver for vector dataset:

contains an optional <Geometry> element, and a required <Graphic> element specifying the point symbology. So as we want to change the point with icons so graphic element is used. <ExternalGraphic> element specifies an external image file to use as the symbol. Then using onlineResource define the path of graphic and format. The xlink:href attribute specifies the location of the image file. The value can be either a URL or a local pathname relative to the SLD directory. The value can contain CQL expressions delimited by ${ }. The attribute xlink:type=”simple” is also required. The graphic size can be by using size element. Then close all the elements by using “/”.

<PointSymbolizer>
 <Graphic>
 <ExternalGraphic>
 <OnlineResource xlink:type="simple" xlink:href="http://localhost:7080/akshay_ep/ep/05airports/airports/airballoon.png"/>
 <Format>image/png</Format>

Full length code

<StyledLayerDescriptor xmlns="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0.0" xsi:schemaLocation="http://www.opengis.net/sld StyledLayerDescriptor.xsd">
 <NamedLayer>
 <Name>Attribute-based point</Name>
 <UserStyle>
 <Title>GeoServer SLD Cook Book: Attribute-based point</Title>
 <FeatureTypeStyle>
 <Rule>
 <Name>balloonport</Name>
 <Title>balloonport</Title>
 <ogc:Filter>
 <ogc:PropertyIsEqualTo>
 <ogc:PropertyName>type</ogc:PropertyName>
 <ogc:Literal>balloonport</ogc:Literal>
 </ogc:PropertyIsEqualTo>
 </ogc:Filter>
 <PointSymbolizer>
 <Graphic>
 <ExternalGraphic>
 <OnlineResource xlink:type="simple" xlink:href="http://localhost:7080/akshay_ep/ep/05airports/airports/airballoon.png"/>
 <Format>image/png</Format>
 </ExternalGraphic>
 <Size>32</Size>
 </Graphic>
 </PointSymbolizer>
 </Rule>
 </FeatureTypeStyle>
 </UserStyle>
 </NamedLayer>
 </StyledLayerDescriptor>

To apply this code open the style option, add a new style and give name and workspace. After that select SLD ( Styled Layer Descriptor ) from format drop down and copy this code in editor. Validate apply and submit this.
After this open your shape file and repeat the steps described above. In the last open this layer as Openlayer from layer preview section.

Publish Style Raster Dataset On GeoServer

Publish Style Raster Dataset On GeoServer. Do you have raster data and want to host the data on geoserver and create a proper map with styling according to dataset? Well GeoServer gives you a direct and simple method to create a styled map. Before implementing steps to publish and sytle raster dataset on geoserver you need to install first GeoServer on Windows, mac or Ubuntu Pc or Server. If you are looking for publish and style vector dataset on geoserver, you can check this link.

Raster Dataset GeoServer coverage:

Coverage/raster data that geoserver can access are,

1. GeoTIFF (Tagged Image File Format with Geographic information)
2. GTOPO30
3. WorldImage
4. ImageMosaic
5. GeoPackage

In this article we will discuss how we can publish GeoTIFF (.tiff/.tfw format) data on server. The data for this article has been downloaded from the links provided in this article. The raster data contains 3 bands (red, blue, green) information. Here we will use GeoTiff data to demonstrating raster dataset to publish and style in GeoServer.

To publish Raster Dataset data – Steps –  Publish Style Raster Dataset

Here we will first publish the geotiff raster dataset in geoserver as an example:

Step 1:

First of all you need to login to GeoServer then create a workspace, which can be done by selecting workspace option on the right side of screen under data section. Add the new workspace give a name and URI. In information technology, a Uniform Resource Identifier (URI) is a string of characters used to identify a resource, which can be same as name and submit the information.

Publish Style Raster Dataset On GeoServer

Step 2 of Publish Raster Dataset on GeoServer:

Now add the store by selecting stores option under same section. Click Add new store and select GeoTIFF option in Raster Data Sources list.

Publish and Style Raster Dataset On GeoServer
Publish and Style Raster Dataset On GeoServer

Under this option add the workspace, you created and give data source name. Provide the description about your data. Now browse the GeoTIFF file to add and publish this data.

Step 3:

Check the Coordinate Reference Systems and the Bounding Boxes fields are properly set and click on Save.

Step 4 of publish raster dataset on geoserver:

Now you can see the layer and get the WMS link. For this go to Layer Preview option in data section and open the published data as OpenLayer option.

To Style Raster Dataset on GeoServer  Steps –  Publish Style Raster Dataset

To add built in style to your GeoTIFF file follow the given steps.

Step 1:

First of all make sure your file has been added on server. Then open that layer using layer option in data section.

Step 2 to style raster dataset in geoserver:

There will be 4 tabs as data, publishing, dimensions and tile caching. As on adding layer you already have visited data tab and set SRS coordinates. Now click publishing tab.

Publish and Style Raster Dataset On GeoServer
Publish and Style Raster Dataset On GeoServer

In publishing tab find the WMS setting option, under that option check the Queryable check box and select style in default style drop down.

There are styles for point, line, polygon and raster in Geoserver:

1. Burg: point
2. Dem: raster
3. Capitals: points
4. Roads: line
5. Lakes: polygon
6. Raster: raster
7. Point: point
8. Line: line
9. Polygon: polygon
10. Rain: raster
11. Population: raster

According to your shape file you can add the style and click to save.

Step 3:

Now to check the styling, add Raster option as style and click the layer preview option under same data section. Open as openLayer.

You can add your own SLD (Styled Layer Descriptor) profile to style the GeoTiff data. For this you can follow this article and for more information you can visit http://docs.geoserver.org/latest/en/user/styling/sld/reference/rastersymbolizer.html link.

The Styled Layer Descriptor (SLD) supported in geoserver raster dataset:  

Profile of the Web Map Service (WMS) Encoding Standard defines an encoding that extends the WMS standard to allow user-defined symbolisation and colouring of geographic feature (vector data) and coverage data (raster data).

SLD has some elements as:

  • <StyledLayerDescriptor> Which is the root element for an SLD. It contains a Layers and Styles elements which describe how a map is to be composed and styled.
    <NamedLayer>: A reference to a named layer in the server catalogue
  • <UserLayer>: A layer defined in the style itself
  • <FeatureTypeStyle>: The FeatureTypeStyle element specifies the styling that is applied to a single feature type of a layer. It contains a list of rules which determine the symbology to be applied to each feature of a layer.
    <Rule>: Styling rules define the portrayal of features. A rule combines a filter with any number of symbolizers. Features for which the filter condition evaluates as true are rendered using the symbolizers in the rule.
  • <RasterSymbolizer>: styles raster coverages.
    The <Opacity> element sets the transparency level for the entire rendered image. As is standard, the values range from zero (0) to one (1), with zero being transparent, and one being opaque.
  • The <ChannelSelection> element specifies how dataset bands are mapped to image colour channels. Named dataset bands may be mapped to red, green and blue channels, or a single named band may be mapped to a grayscale channel.
  • Here we can select any of the band or all three band. But particularly in this article we have selected a single band of an RGB image as a grayscale channel and re-colorizing it via a ColorMap.
  • A color map is defined by a sequence of <ColorMapEntry> elements. Each <ColorMapEntry> element specifies a color and a quantity attribute. The quantity refers to the value of a raster pixel. The color value is denoted in standard hexadecimal RGB format (#RRGGBB). <ColorMapEntry> elements can also have opacity and label attributes. As in the code quantity is given as 0, 150, 200 and 255. Then the pixels having other values get interpolated range of color.
  • In the last close all the elements and save the style.
    After that open the layer option and select the geotiff file. Add the style in publishing tab and save the layer. To view this style over layer, open layer preview option and open this layer as Openlayer option.

Full length code Publish Style Raster Dataset On GeoServer

<?xml version=”1.0″ encoding=”UTF-8″?>
<StyledLayerDescriptor version=”1.0.0″
xsi:schemaLocation=”http://www.opengis.net/sld StyledLayerDescriptor.xsd”
xmlns=”http://www.opengis.net/sld”
xmlns:ogc=”http://www.opengis.net/ogc”
xmlns:xlink=”http://www.w3.org/1999/xlink”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”>
<NamedLayer>
<Name>default_raster</Name>
<UserStyle>
<Title>Default Raster</Title>
<FeatureTypeStyle>
<Rule>
<Name>rule1</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=”#0000ff” quantity=”0″/>
<ColorMapEntry color=”#009933″ quantity=”150″/>
<ColorMapEntry color=”#ff9900″ quantity=”200″ />
<ColorMapEntry color=”#ff0000″ quantity=”255″/>
</ColorMap>
</RasterSymbolizer>
</Rule>
</FeatureTypeStyle>
</UserStyle>
</NamedLayer>
</StyledLayerDescriptor>

Publish and Style Raster Dataset On GeoServer
Publish Style Raster Dataset On GeoServerHope

Hope this article to Publish Style Raster Dataset On GeoServer is helpful for you and you might be easily able to create a beautiful colour map with the help of geoserver. If you find any problem in following the steps to style and publish the raster layer of geoserver do comment below with the problem in the box provided below.

Install Geoserver – Windows OS – Step by Step

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.

Download stable version of GeoServer to Install:

Google out http://geoserver.org/ link.

Install Geoserver in windows

Hit the Download tab and install the stable version of geoserver. In this tutorial we have downloaded GeoServer 2.12.0. Before installation make sure that you already have JRE installed. If you have not installed that please visit

http://www.oracle.com/technetwork/java/javase/downloads/index.html

to download JRE (Java runtime environment) and install it.

To install GeoServer follow the steps given below,

Step 1:

First of all download the GeoServer application file and keep in drive, where you want to install it.

Step 2 to install geoserver:

Double click the application file and start installation.

Install Geoserver in windows

Click next button.

Step 3:

Select I agree option and set the path to drive, where you want to install this application.

Install Geoserver in windows

Click I agree.

Install Geoserver in windows

Before choosing the install location check space available in drive. Then provide installation location and click next.

Install Geoserver in windows

Here click next button.

Install Geoserver in windows

Give the path where you have installed the JRE.

Install Geoserver in windows

Click next button.

Step 4 to install geoserver:

You can change the Username and password.

Install Geoserver in windows

Set the Username and password and click next button.

Install Geoserver in windows

Click next button.

Install Geoserver in windows

Click next button.

Install Geoserver in windows

Check the details provided and click install button. After installation click finish button. You will find the GeoServer folder in the directory.

Step 5 to install geoserver:

After installation search Start GeoServer application, it will run in command prompt then in web browser search localhost:8080/geoserver/web link.

You can also visit articles on Publish and style Vector data, Publish and style Raster data, Install geoserver in linux operating system etc.

Feel free to comment in provided comment box for any other queries and problem.

Shp to SQL – Convert Shapefile to postgersql file

Shapefile shp can be converted in pgsql file using shp2pgsql command line tool. Sometimes you have a shapefile and want to upload the same in postgresql database, you can directly use shp2pgsql command and upload shapefile to postgis. While there might be possibilites that you would not be having access to your production server to install shp2pgsql command line tool, so you can convert shapefile into a sql file and then upload the same to Database. Lets check how to convert shp to sql file.

Conversion using shp2pgsql – shp to sql

Try Our Tool MapOG Converter for SHP to SQL conversion

For executing this command you need to have shp2pgsql utility in your system. You can check the presence of utility by typing shp2pgsql in terminal. If this utility is present then you will see the following result.

Convert- Shapefile Shp to SQL postgersql file
Convert- Shapefile Shp to SQL postgersql file

Shp2pgsql has some option, some for them are used here. Option -I creates a spatial index on the geocolumn. Option -s specifies the SRS (Spatial Reference system) in EPSG (European Petroleum Survey Group) number.

–> shp2pgsql -I -s 4326 shpfilepath.shp output_table_name > output.sql

After executing this command, you can run the sql file in postgres to insert data in table.

Code – Convert- Shapefile Shp to SQL postgersql filE

If you know to read binary files by knowing its format, you can easily read and convert shapefile to sql, as shapefile has an open standard file format. For instance, you can look over tutorial I had created in how to read shapefile bounding box using c++ or reading shapefile header.

In codeigniter framework of php, we can use shell_exec() by providing command as input. In command we need to export PGPASSWORD, where password is supplied.
While writing command in PHP, we need to take SRS (Spatial Reference system) of shape file, input shapefile and output file name from the user. The passwrThen query is written in string format and supplied to shell_exec() method. This method returns output as string and generates file in folder.

PGPASSWORD behaves the same as the password connection parameter. Use of this environment variable is not recommended for security reasons, as some operating systems allow non-root users to see process environment variables via ps; instead consider using the ~/.pgpass file. For more detail you can visit https://www.postgresql.org/docs/9.1/static/libpq-envars.html link.

public function shptosql($shpfilepath,$output){
$srs=4326;
$query=”export PGPASSWORD=’download1′; shp2pgsql -I -s $srs $shpfilepath $output > $output.sql”;
shell_exec($query);
}

You can check for SQL file in the same folder where shapefile is kept. The generated result will look like-

Convert- Shapefile Shp to SQL postgersql file
Convert- Shapefile Shp to SQL postgersql file

Change coordinate system – shp to sql

While converting shapefile into sql, you can not change the coordinate system. But you can execute this process in two steps as-

  1. Change the coordinate system of shapefile

–> ogr2ogr -f ‘ESRI shapefile’ -s_srs EPSG:4326 (old EPSG number) -t_srs EPSG:32643 (new EPSG number) new_shapefile.shp India_raods.shp

2. Then convert shapefile into sql

–> shp2pgsql -I -s 32643 new_shapefile.shp output_table_name > output.sql

ogr2ogr utility has some options as-

-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

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

Hope you enjoyed the conversion and executed it successfully. Let us know you face any difficulty during execution of this tutorial via commenting in provided box.

Shp to MIF – Convert Shapefile to MapInfo Interchange Format

Many people uses MapServer as their Server, so they might need to store shape file as MIF (Map Info File) file on server. The OGR Simple Features Library allows MapServer users to display several types of vector data files in their native formats. For example, MapInfo Mid/Mif and TAB data can be seen on MapServer when using OGR support with it. So lets see how to convert Shapefile shp to mif or map info file.

Here is the online tool To convert Shapefile to MapInfo MIF 

Lets look what is MIF ( MapInfo Interchange Format) Before converting shp to Mif

MIF (Map Info File) File format used by MapInfo mapping and geographic analysis software. This stores a map visualization in a format that can be recognized by third party applications. Also used as an exchange format between GIS applications. This sometimes accompanied by a .MID (MapInfo data) file that contains additional spatial data. MID files are GIS data files created by MapInfo, a spatial data analysis and visualization software, saves spatial data for a corresponding .MIF (MapInfo Interchange Format) file. Also used for storing larger data sets not expressed in the MIF file.  What is Shapefile – collection of geometry with other supported files as shx, dbf, prj ect.

MIF file show some general property when open with QGIS software, as like :

i.) Storage type of this layer
–> MapInfo File
ii.) 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)
iii.) Source for this layer
–> /var/www/html/PHP_pgrouting/public/shpfolder222/newwhello.mif
iv.) Geometry type of the features in this layer
–> Line
v.) The number of features in this layer
–> 19148
vi.) Capabilities of this layer
–> Fast Access to Features at ID, Presimplify Geometries, Presimplify Geometries with Validity Check
vii.) In layer spatial reference system units
–> xMin,yMin 68.4982,7.92528 : xMax,yMax 97.3348,35.5013
viii.) Layer Spatial Reference System
–> +proj=longlat +datum=WGS84 +no_defs

Convert Shapefile SHP TO MIF format using ogr2ogr utility-

ogr2ogr supports some file format MIF is one of them. You can write a simple command to convert your shapefile. Before this you must check for ogr2ogr utility. That can be done by typing ogr2pgr in your terminal.

Convert- Shapefile Shp to MIF - Map Info File
Convert- Shapefile Shp to MIF – Map Info File

If this utitlity is not available, you should run the given commands-

Convert- Shapefile Shp to MIF - Map Info File

After this please check ogr2ogr utility http://www.gdal.org/ogr2ogr.html is available now.

Now you can move for conversion. For conversion please use the given command

–> ogr2ogr -f “MapInfo File” output_file.mif Input_SHP.shp

Note-

You must have shp along with .shx and .dbf file for proper conversion.
If you only have shp file you will got an error something like.

Convert- Shapefile Shp to MIF - Map Info File
Convert- Shapefile Shp to MIF – Map Info File

And if you don’t have .dbf file, then you following error will appear

Convert- Shapefile Shp to MIF - Map Info File

Code to Convert Shp to MIF

If you are aware of reading binary file by knowing the file format, you can easily read and parse shapefile and convert the same to any other format. You can check out one such tutorial which I had created to read header of shapefile using c++ or bounding box of shapefile using c++.

This same work can be done in PHP using shelll_exec() method, which execute the command and gives output as string. The following function describes the $query variable, which takes command as string and given to shell_exec(0 method.

public function shptomif($shpfilepath,$output) {
$query=”ogr2ogr -f ‘MapInfo file’ $output.mif $shpfilepath.shp”;
shell_exec($query);
}

Output of mif file from shp file-

The Output will contain .mif and .mid files. You can open MIF file in QGIS software.

If you are using Windows operating software than you can open .mif (Map Info File) with microsoft word. The following result will appear

Version 300
Charset “Neutral”
Delimiter “,”
CoordSys Earth Projection 1, 104
Columns 7
MED_DESCRI Char(254)
RTT_DESCRI Char(254)
F_CODE_DES Char(10)
ISO Char(7)
ISOCOUNTRY Char(54)
Length_km Decimal(11,2)
Latitude Decimal(11,2)
Data line(…..)

Change Coordinate System of MIF from shp format

Converting shapefile into MapInfo File with desired coordinate system can be done by using ogr2ogr utility. It has some options related to SRS (Spatial reference system), given below-

-t_srs srs_def:

Reproject/transform to this SRS on output

-s_srs srs_def:

Override source SRS

So the query can be written as-

–> ogr2ogr -f ‘MapInfo File’ -s_srs EPSG:4326 (old EPSG) -t_srs EPSG:32643 (new EPSG) output_mifFile.mif Input_file.shp 

Hope this tutorial helped you to convert your shapefile to MIF (Map Info File) format. There are also various conversion available as- Shape to CSV, GeoJson to topoJson, Shapefile to Topojson , shapefile to kml, shp to ods, shp to gml etc.

Please let us know, if any find any difficulty in performing this conversion via commenting in provided box.

SHP to XLSX – Convert Shapefile to Excel

Sometimes we just need to see attribute details not geometry. So instead of carrying heavy shape files we can convert them in XLSX format. XLSX file contains on attribute detail or can say non spatial data. XLSX files are light in weight. Along with shp to xlsx convert you may also check for shp to ods, shp to csv conversion which also more focuses on attribute details.

Convert SHP to XLSX using MapOG Tool for hassle free conversion

KNOW ABOUT XLSX AND SHAPEFILE format -BEFORE CONVERTING SHP TO XLSX

An XLSX file is an Excel spreadsheet created by Microsoft Excel or another spreadsheet program. It stores data in worksheets, which contain cells arranged in a grid of rows and columns, and may also contain charts, mathematical functions, styles, and formatting. XLSX files create simple or complex mathematical models.

What is shapefile? Each object within a SHP file contains an individual geographic feature and its attributes.

Conversion from shapefile to XLSX using ogr2ogr utility-

–> ogr2ogr -f XLSX output_xlsx_filename.xlsx India_raods.shp

In command -f is file format and XLSX is driver. Then you can specify the output file name with .xlsx extension and input shapefile. This command can be executed on terminal or using PHP code. Here you must look for the ogr2ogr utility in your system. If not available you can install it using given line of code.

SHP to XLSX

Then you can check the presence of utility by typing ogr2ogr in terminal. The output will look like-

SHP to XLSX
SHP to XLSX

Note that while converting shapefile to XLSX, you must check for .shx file. If shx file is not available you may get following error.

SHP to XLSX

Shapefile has some supporting file like .dbf, .shx, .prj etc. So you must take all file whenever you perform conversion.

PHP CODE – SHP to XLSX

If you are aware of Shapefile Open description format, then you can easily access shapefile data through coding. As i have created one such shapefile minimum bounding box parser in c++. Below in the php code to execute ogr2ogr tool.

Here you can perform the conversion using shell_exec() method, which actually executes the command and returns string as output.

public function shptoxlsx($shpfilepath,$output) {
$query=”ogr2ogr -f XLSX $output.xlsx $shpfilepath.shp”;
shell_exec($query);
}

After execution of command you can check the specified folder to see generated xlsx file. The content of file will be something like-

SHP to XLSX

You may also look forward to convert shapefile to GeoJSON, Shapefile to Kml, Shapefile to topojson and etc conversions.

Hope you enjoyed the article and successfully converted shape file into XLSX file. If you have any problem regarding conversion please feel free to write in comment box.