Building a Google Maps Application with PostgreSQL

Google Map
How to save points from Google maps in a PostgreSQL database. This has been adapted from 2 articles for MySQL, referenced from The Google Geo Developers Blog -

New Articles: Powering Maps API v3 Apps with MySQL

"Using PHP/MySQL with Google Maps" shows how to pull data from a SQL database as XML and display that on the map.

"From InfoWindows to a Database: Saving User-Added Form Data" shows you how to enable users to add geo-tagged information to a database via your map application.


Migrating this to PostgreSQL was worth the effort as it opened opportunities to integrate the Google Maps application with PostGIS.  See Google Maps (API 3) application and related story: Getting Productive With QGIS, Postgresql, PostGIS, and Google maps

The following code snippets give examples of the PostgreSQL adapted code - no other changes are needed from the referenced articles. Learn more about this in our online training module - Getting Productive with (Q)GIS

1. PHP code to output the XML to view geo-tagged points saved in a PostgreSQL table




// Start XML file, create parent node
$dom = new DOMDocument("1.0&quotWink;
$node = $dom->createElement("markers&quotWink;
$parnode = $dom->appendChild($node);
// Opens a connection to a pgSQL server
$conn_string = "host=$host port=5432 dbname=$db user=$dbuser password=$pwd";
$conn = pg_connect($conn_string);  
    die ("Could not open connection to database server&quotWink;
$query = "SELECT * FROM marker";
$result = pg_query($conn, $query);
    die('Invalid query : ' . pg_last_error());
header("Content-type: text/xml&quotWink;
// Iterate through the rows, adding XML nodes for each
while ($row = pg_fetch_assoc($result)){
$node = $dom->createElement("marker&quotWink;
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("type", $row['type']);
echo $dom->saveXML();



2. PHP code to save geo-tagged points clicked on a Google Map to a PostgreSQL table



// Opens a connection to a pgSQL server
$conn_string = "host=$host port=5432 dbname=$db user=$dbuser password=$pwd";
$conn = pg_connect($conn_string);
    die ("Not connected : " . pg_last_error());
// Gets data from URL parameters
$name = $_GET['name'];
$address = $_GET['address'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
$type = $_GET['type'];
// Insert new row with user data
$query = sprintf("INSERT INTO marker " .
         " (name, address, lat, lng, type ) " .
         " VALUES ('%s', '%s', '%s', '%s', '%s&#39Wink;",
$result = pg_query($conn,$query);
if (!$result) {
  die('Invalid query: ' . pg_last_error());



Tag: postgresql postgis google map gis


Comments are closed