Friday, March 4, 2011

Basic tutorial of GoogleMaps Mashup using PostGIS

 Goal:
Main goal of this tutorial is to create simple web application containing google map. So that user can get some information from the google maps or post some information on it. In this tutorial we will store all our information in our local PostgreSQL database.
PostGIS is a spatial database extension for PostgreSQL object relational databse. PostgreSQL is an open-source databse. PostGIS "spatially enables" the PostgreSQL server, allowing it to be used as a backend spatial database for geographic information systems (GIS). PostGIS is an open-source spatial database extender. So the main database is PostgreSQL and PostGIS extension provides us to store spatial (GIS) data (which we will collect from google maps).
In this example we will get/post the information from the google map using google maps API’s. This information will be stored in the database in PostgreSQL database.
To get/post the information and then to save it to database, we need server side calculations. So in this example we will use ASP.Net 2010 to develop web application.

PostgreSQL:

Usually when you install PostgreSQL, PostGIS is included in package and you don’t need to install it separately.
·         You can download PostgreSQL from their site.
·         You can see the installation guide of PostgreSQL for windows.
·         If you are new to PostgreSQL database then there are some basic tutorials available to start with PostgreSQL.
In PostgreSQL I created one table named “cities” which contain two columns “Name” and “Location”. “Name” is of type “character” with 100 length and “Location” is of type “Point” (spatial data type to store longitude and latitude values)



DSN Connection:

In this example, to escape from all hurdles of connection string I prefer to user DSN connection. It is very simple to create. You just need to go to Control Panel -> Administrative Tool -> DataSource (ODBC).  For more detail guideline is mentioned here. So now when we want to create connection string ASP.Net when can just give this DSN name instead of whole connection string.
We also need to install ODBC drivers for .Net. You can download it from here.

Web Application:

Create an ASP.Net web application. Steps are as follows:
1.       Create New WebSite.
2.       Create New form on the Project and name it GoogleMap.
3.       Download GMaps.dll from here.
4.       Add this GMaps.dll to your project by Add References.
5.       Go to the source of GoogleMap.aspx and Add this line
<%@ Register Assembly="GMaps" Namespace="Subgurim.Controles" TagPrefix="cc1" %>
Suddenly after this
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GoogleMap.aspx.cs" Inherits="GoogleMap" %>

Then in div tag add
<cc1:GMap ID="GMap1" runat="server" enableServerEvents="true" Height="400px" key="ABQIAAAAusGCH_px9VqRxwWsCqAqLRQXMqAnCiUGp61u43JOa0JAz4-4rxTcuIwbEDN12F9MyEb0HqiQQyqwtA" Width="600px" />
After adding this line your whole GoogleMaps.aspx page will look like this.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GoogleMap.aspx.cs" Inherits="GoogleMap" %>

<%@ Register Assembly="GMaps" Namespace="Subgurim.Controles" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<cc1:GMap ID="GMap1" runat="server" enableServerEvents="true" Height="400px"
key="ABQIAAAAusGCH_px9VqRxwWsCqAqLRQXMqAnCiUGp61u43JOa0JAz4-4rxTcuIwbEDN12F9MyEb0HqiQQyqwtA"
Width="600px" />
</div>
</form>
</body>
</html>

Now run the application you can see simple Google Map on the screen.
Note: If you receive the error of Key then you have to sign up here to get your key and put it in <cc1> tag instead of other key.
6.       We want to add Click event, so that when user click on the map it post back its information to the server side. So we need to add “OnClick=”GMap1_Click” to our cc1 tag. So it will look like this.
<cc1:GMap ID="GMap1" runat="server" enableServerEvents="true" Height="400px"                     key="ABQIAAAAusGCH_px9VqRxwWsCqAqLRQXMqAnCiUGp61u43JOa0JAz4-4rxTcuIwbEDN12F9MyEb0HqiQQyqwtA" OnClick="GMap1_Click" Width="600px" />

7.       Now to GoogleMap.aspx.cs file and add header file add this method after load method.

using Subgurim.Controles;  // add it as header file before load

protected string GMap1_Click(object s, GAjaxServerEventArgs e)
{
return null;
}

8.       Go to GoogleMap.aspx Design View and Add GridView right after the GoogleMap component.
9.       In GoogleMap.aspx.cs, Add this method


using System.Data.Odbc;            //Add these two in header files
using System.Data;

public void loadgrid()
{
string connectionString = "DSN=PostgreSQL30";
OdbcConnection connection = new OdbcConnection(connectionString);
connection.Open();

string con = "select * from cities";
OdbcCommand com = new OdbcCommand(con, connection);
OdbcDataAdapter da = new OdbcDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);

GridView1.DataSource = dt;
GridView1.DataBind();
connection.Close();
}

In this way we can see all the values in the cities table in GridView.

Insert GoogleMap data in the database

If user click the google map, we might want to put the marker on that location and put that value in the database.
10.   Add this code in the “GMap1_Click” method
protected string GMap1_Click(object s, GAjaxServerEventArgs e)
{
string connectionString = "DSN=PostgreSQL30";
OdbcConnection connection = new OdbcConnection(connectionString);
connection.Open();

GMap gmap = new GMap(e.map);

// GMarker and GInfoWindow
GMarker marker = new GMarker(e.point);
//GInfoWindow window = new GInfoWindow(marker, "Cool!!", true);
gmap.Add(marker);

string str1 = "Insert into cities values ('abc', '" + e.point + "')";
OdbcCommand com1 = new OdbcCommand(str1, connection);
com1.ExecuteNonQuery();

connection.Close();

loadgrid();
return gmap.ToString();

}

Retrieve data from PostgreSQL and Display in GridView

11.   To retrieve the data from the database we will put one button on design view and named it “Show Marker”. Now double click that button to go to its method and write this code.

string connectionString = "DSN=PostgreSQL30"; //+ ConfigurationManager.AppSettings["PostgreSQL30"];
OdbcConnection connection = new OdbcConnection(connectionString);
connection.Open();

string con = "select * from cities";
OdbcCommand com = new OdbcCommand(con, connection);
OdbcDataAdapter da = new OdbcDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);

for (int i = 0; i < dt.Rows.Count; i++)
{
string location = dt.Rows[i][1].ToString();
location = location.Replace(")", "");
location = location.Replace("(", "");
string[] str = location.Split(',');


GLatLng la = new GLatLng(double.Parse(str[0].Replace('.',',')),          double.Parse(str[1].Replace('.',',')));
GMarker marker = new GMarker(la);
GMap1.Add(marker);
}

In this method we receive the value from the database. In cities table “Location” is stored as datatype of “Point”. Here I pick the Point value and split its longitude and latitude value to add marker.
12.   We can clear marker from map by adding one more button of Clear and In the method of button write
GMap1.resetMarkers();
When we run the application, It shows like this


By clicking show points on the Map it will show marker saved in the database.


When you click on the map, it will add marker on that location and in the same time save the marker value in the database.

This example is the basic example to store and retrieve the data from GoogleMaps to PostgreSQL and PostgreSQL to GoogleMaps Marker. Google Maps provide lot more API’s for GoogleMaps. You can add zoom functionality, Satellite View, Road Map etc. 

No comments:

Post a Comment