TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

PHP + Google Map polygon shape creator

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.

Create Database table

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.

Develop server side handler

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:

  1. static $_dbHost : This is the host for MySQL connection. It is normally "localhost" unless your database server is sitting in a different server from your application server.
  2. static $_dbName: This is the database name, where you have imported "points" database table.
  3. static $_dbUserName: This is database user, which has access right to your database.
  4. static $_dbUserPwd: This is password for the database user above.
  5. static private function get(): In this function, we connect to database and select the data needed. When no data is found, a boolean false is returned
  6. static public function save ($data) : This function is used to save data into database. Note that, we always delete the exsiting data before inserting new one. This is because we are storing only one polygon.
  7. static public function getCoords(): This is a wrapper function for get(). Note two function above are private, we do not want to exposed the direct database access functions.
  8. static public function saveCoords($rawData): This is a wrapper function for save ($data). Nothing much is done in wrapper class, but that is how we prefer to write the code.

Develop front page

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:

  1. Paste code below to the beginning of "index.php", we will explain some important lines of codes after:
<?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];
    }
?>
  • line 1: Include class Polygon from file "server.php". Modify the path if you have saved the file at a different location.
  • line 4 - 5: Check if there is any data $_POST , and if so, save it to database.
  • line 8 - 17: Get coordinates from database and parse them to pairs for JavaScript below.
  1. Paste code below after codes above, we will explain some important lines of codes after:
<!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>
  • line 8 - 9: Include JavaScript libraries we need, please update path of polygon.min.js to where you place it.
  • line 16 - 25: Create a Google Map object.
  • line 27 - 28: Create a Google Map polygon creator, this is created by polygon.min.js. And finally attach it to Google Map object created above.
  • line 30 - 35: Create a reset button, which will clear a current drawing polygon.
  • line 38 - 40: Whenever form is submitted, get coordinates data from polygon using function showData() and store it to a hidden field, so that we can get it on server side.
  • line 43 - 51: Create an array of google.maps.LatLng object using $coords which we parsed at the begining of the file.
  • line 53 - 61: Create an google.maps.Polygon object.
  • line 64: Finally show the polygon on the Google Map.
  1. Paste code below after codes above, we will explain some important lines of codes after:
    <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>
  • line 3: Create a DIV with id "main-map", note we use this id to create a Google Map object in JavaScript section.
  • line 5 - 12: Create a form for submitting data, please note we have a hidden field "coords". In the JavaScript section, we dynamically update the field value when form is submitted.

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.

The end

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.