In this tutorial, we will share how to use Google Map polygon shape creator with server side language PHP. If you have not heard about Google Map polygon shape creator yet, you can refer to our first tutorial here. In short, it is a client side JavaScript library to draw polygon.
We will need a database table to store the latitude and longitude coordinates. Create your own database, then inside your database, import database table below:
CREATE TABLE IF NOT EXISTS `points` (
`data` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
This is a very simple table(points) with one text field("data"). Please note we are storing only one polygon data in this tutorial for demonstration purpose.
Create a PHP file with name "server.php" and paste the content below.
<?php
/*
* Author: Xu Ding
* website: www.startutorial.com
* www.the-di-lab.com
*/
class Polygon
{
static $_dbHost = 'localhost';
static $_dbName = 'polygon';
static $_dbUserName = 'root';
static $_dbUserPwd = '';
// get coordinates
static public function getCoords()
{
return self::get();
}
// save coordinates
static public function saveCoords($rawData)
{
self::save($rawData);
}
// save lat/lng to database
static public function save ($data)
{
$con = mysql_connect(self::$_dbHost, self::$_dbUserName, self::$_dbUserPwd);
// connect to database
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(self::$_dbName, $con);
// delete old data
mysql_query("DELETE FROM points");
// insert data
mysql_query("INSERT INTO points (data) VALUES ($data)");
// close connection
mysql_close($con);
}
// get lat/lng from database
static private function get()
{
$con = mysql_connect(self::$_dbHost, self::$_dbUserName, self::$_dbUserPwd);
// connect to database
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(self::$_dbName, $con);
$result = mysql_query("SELECT * FROM points");
$data = false;
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$data = $row['data'];
}
// close connection
mysql_close($con);
return $data;
}
}
There are basically four variables and four functions in this class. We used static variable and function, because we want the simplest way of calling the functions. Let us take a look at variables and functions in detail below:
Ok, this is the part we are going to use our polygon creator lib, and make it work with the "server.php". Just in case you have not downloaded the JavaScript class. Go ahead and download it. Create a PHP file "index.php" and we will go through each step of coding below:
<?php
include "server.php";
if (!empty($_POST)) {
Polygon::saveCoords ($_POST['coords']);
}
$data = Polygon::getCoords();
$coords = null;
if(false!=$data) {
// parse data
preg_match_all('/\((.*?)\)/', $data, $matches);
$coords= $matches[1];
}
?>
<!DOCTYPE>
<html>
<head>
<title>Google Map V3 Polygon Creator by Xu Ding</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="polygon.min.js"></script>
<script type="text/javascript">
$(function(){
// create map
var singapoerCenter=new google.maps.LatLng(1.37584, 103.829);
var myOptions = {
zoom: 12,
center: singapoerCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('main-map'), myOptions);
// attached a polygon creator drawer to the map
var creator = new PolygonCreator(map);
// reset button
$('#reset').click(function(){
creator.destroy();
creator=null;
creator=new PolygonCreator(map);
});
// set polygon data to the form hidden field
$('#map-form').submit(function () {
$('#map-coords').val(creator.showData());
});
<?php if (null!=$coords): ?>
// create
var polygonCoords = [<?php
foreach ( $coords as $i=>$coord ):
echo 'new google.maps.LatLng('.$coord.')';
if ( $i<=count($coords)) {
echo ',';
}
endforeach;?>];
// construct the polygon
polygon = new google.maps.Polygon({
paths: polygonCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35
});
// show polygon on the map
polygon.setMap(map);
<?php endif;?>
});
</script>
</head>
<body>
<div style="margin:auto; width: 500px; ">
<div id="main-map" style="height: 400px;"></div>
<form action="index.php" method="POST" id="map-form">
<input type="hidden" name="coords" id="map-coords" value=""/>
<input type="submit" value="Save"/>
<input type="button" value="Reset" id="reset"/>
</form>
</div>
</body>
</html>
Now, navigate to index.php from your browser, you should have a nice Google Map polygon creator. With the power of backend script PHP, now every newly drawn polygon is saved to database.
Hopefully you have enjoyed this simple tutorial. If you like our post, please follow us on Twitter and tweet out this tutorial. If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.