-2

I have some questions and i hope someone help me to solve it . the questions is:

1) i want to save the drawing polygon into database mysql. 2) each polygon can have different name and insert into database. 3) edit and delete the polygon that was created and save it into database.

in my code i'm using google map tool to draw and give color to each polygon was drawing on google map. so i hope someone help me of code about save all these into database. Thank you

code.

<script type="text/javascript"
  src="http://maps.google.com/maps/api/js?sensor=false&libraries=drawing"></script>
<style type="text/css">
  #map, html, body {
    padding: 0;
    margin: 0;
    height: 100%;
  }

  #panel {
    width: 200px;
    font-family: Arial, sans-serif;
    font-size: 13px;
    float: right;
    margin: 10px;
  }

  #color-palette {
    clear: both;
  }

  .color-button {
    width: 14px;
    height: 14px;
    font-size: 0;
    margin: 2px;
    float: left;
    cursor: pointer;
  }

  #delete-button {
    margin-top: 5px;
  }
</style>
<script type="text/javascript">
  var drawingManager;
  var selectedShape;
  var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
  var selectedColor;
  var colorButtons = {};

  function clearSelection() {
    if (selectedShape) {
      selectedShape.setEditable(false);
      selectedShape = null;
    }
  }

  function setSelection(shape) {
    clearSelection();
    selectedShape = shape;
    shape.setEditable(true);
    selectColor(shape.get('fillColor') || shape.get('strokeColor'));
  }

  function deleteSelectedShape() {
    if (selectedShape) {
      selectedShape.setMap(null);
    }
  }

  function selectColor(color) {
    selectedColor = color;
    for (var i = 0; i < colors.length; ++i) {
      var currColor = colors[i];
      colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
    }

    // Retrieves the current options from the drawing manager and replaces the
    // stroke or fill color as appropriate.
    var polylineOptions = drawingManager.get('polylineOptions');
    polylineOptions.strokeColor = color;
    drawingManager.set('polylineOptions', polylineOptions);

    var rectangleOptions = drawingManager.get('rectangleOptions');
    rectangleOptions.fillColor = color;
    drawingManager.set('rectangleOptions', rectangleOptions);

    var circleOptions = drawingManager.get('circleOptions');
    circleOptions.fillColor = color;
    drawingManager.set('circleOptions', circleOptions);

    var polygonOptions = drawingManager.get('polygonOptions');
    polygonOptions.fillColor = color;
    drawingManager.set('polygonOptions', polygonOptions);
  }

  function setSelectedShapeColor(color) {
    if (selectedShape) {
      if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
        selectedShape.set('strokeColor', color);
      } else {
        selectedShape.set('fillColor', color);
      }
    }
  }

  function makeColorButton(color) {
    var button = document.createElement('span');
    button.className = 'color-button';
    button.style.backgroundColor = color;
    google.maps.event.addDomListener(button, 'click', function() {
      selectColor(color);
      setSelectedShapeColor(color);
    });

    return button;
  }

   function buildColorPalette() {
     var colorPalette = document.getElementById('color-palette');
     for (var i = 0; i < colors.length; ++i) {
       var currColor = colors[i];
       var colorButton = makeColorButton(currColor);
       colorPalette.appendChild(colorButton);
       colorButtons[currColor] = colorButton;
     }
     selectColor(colors[0]);
   }

  function initialize() {
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(22.344, 114.048),
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      disableDefaultUI: true,
      zoomControl: true
    });

    var polyOptions = {
      strokeWeight: 0,
      fillOpacity: 0.45,
      editable: true
    };
    // Creates a drawing manager attached to the map that allows the user to draw
    // markers, lines, and shapes.
    drawingManager = new google.maps.drawing.DrawingManager({
      drawingMode: google.maps.drawing.OverlayType.POLYGON,
      markerOptions: {
        draggable: true
      },
      polylineOptions: {
        editable: true
      },
      rectangleOptions: polyOptions,
      circleOptions: polyOptions,
      polygonOptions: polyOptions,
      map: map
    });

    google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
        if (e.type != google.maps.drawing.OverlayType.MARKER) {
        // Switch back to non-drawing mode after drawing a shape.
        drawingManager.setDrawingMode(null);

        // Add an event listener that selects the newly-drawn shape when the user
        // mouses down on it.
        var newShape = e.overlay;
        newShape.type = e.type;
        google.maps.event.addListener(newShape, 'click', function() {
          setSelection(newShape);
        });
        setSelection(newShape);
      }
    });

    // Clear the current selection when the drawing mode is changed, or when the
    // map is clicked.
    google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
    google.maps.event.addListener(map, 'click', clearSelection);
    google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);

    buildColorPalette();
  }
  google.maps.event.addDomListener(window, 'load', initialize);
john david
  • 11
  • 4
  • 2
    As it stands this is too broad. Is there a database table created? Do you have a reliable ajax function? Do you have the sql query set that will insert the polygon points? What is the criteria involved that will trigger the saving of the polygon - button?Right-click? – Professor Abronsius May 09 '19 at 10:22
  • thx u for answer, there is no database till now created. and no ajax as u seen just only javascript and html to draw and delete the polygon. yes i want to save the polygon after drawing into database with given name of it and select that polygon later to edit and delete . – john david May 09 '19 at 10:33
  • 1
    [Get the Polygon path(s)](https://developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.getPath) and save that to your DB. – MrUpsidown May 09 '19 at 10:47
  • Possible duplicate of https://stackoverflow.com/questions/19614805/how-to-save-a-google-maps-overlay-shape-in-the-database – MrUpsidown May 09 '19 at 10:48
  • its not duplicate sir!!! i had check the other answer before i post it and saw this link already ! – john david May 09 '19 at 11:17

1 Answers1

0

Ok, considering the broad nature to the question and lack of supporting structure / resources you will need to study and adapt if the following does what you need.

The first step would be to create the database structure you need - here I have created two, very basic, mySQL tables in a new database called gm_polygons. I'm not suggesting that these schemas will be sufficient for all the data that you need to store in the tables - such as colour, stroke, title etc etc but will give a starting point.

create table `paths` (
    `id` int(10) unsigned not null auto_increment,
    `pid` int(10) unsigned not null default '0',
    `lat` float not null default '0',
    `lng` float not null default '0',
    primary key (`id`),
    index `pid` (`pid`)
)
collate='utf8_general_ci'
engine=innodb;


create table `polygon` (
    `id` int(10) unsigned not null auto_increment,
    `name` varchar(50) not null default '0',
    primary key (`id`)
)
collate='utf8_general_ci'
engine=innodb;

The php map page. The map loads, in this case centred upon London, and assigns a listener to the map which allows drawing of the polygon ( only polygons in this demo, no circles or polylines etc ) - the form has an input for the name of the poly and a button to send, via ajax, the details to the php script to process.

You could, after generating the db and tables shown here, modify the following byadding relevant details for host,user,password etc and run this to test.

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();


        /* process the addition of the polygon */
        if( !empty( $_POST['name'] ) && !empty( $_POST['path'] ) ){


            $dbhost =   'localhost';
            $dbuser =   'root'; 
            $dbpwd  =   'xxx'; 
            $dbname =   'gm_polygons';
            $db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );


            $name=$_POST['name'];
            $path=json_decode( $_POST['path'] );



            /* insert new path */
            $sql='insert into polygon set `name`=?';
            $stmt=$db->prepare( $sql );

            if( !$stmt )exit( 'Error: query 1' );

            $stmt->bind_param('s',$name);
            $stmt->execute();
            $stmt->free_result();
            $stmt->close();


            /* get the ID for the newly inserted Polygon name */
            $id=$db->insert_id;




            /* add all the latlng pairs for the polygon */
            $sql='insert into `paths` ( `pid`, `lat`, `lng` ) values ( ?, ?, ? )';
            $stmt=$db->prepare( $sql );

            if( !$stmt )exit( 'Error: query 2' );

            $stmt->bind_param( 'idd', $id, $lat, $lng );

            foreach( $path as $obj ){
                $lat=$obj->lat;
                $lng=$obj->lng;
                $stmt->execute();
            }
            $stmt->close();

            echo json_encode(
                array(
                    'name'=>$name,
                    'points'=>count($path)
                )
            );

        }
        exit();
    }
?>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Google Maps: Storing Polygons in database</title>
        <script async defer src='//maps.google.com/maps/api/js?key=APIKEY-gFJ0&callback=initMap&region=GB&language=en'></script>
        <script>

            let map;
            let div;
            let bttn;
            let input;
            let options;
            let centre;
            let poly;
            let path;
            let polypath;

            function initMap(){

                const ajax=function( url, params, callback ){
                    let xhr=new XMLHttpRequest();
                    xhr.onload=function(){
                        if( this.status==200 && this.readyState==4 )callback( this.response )
                    };
                    xhr.open( 'POST', url, true );
                    xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
                    xhr.send( buildparams( params ) );
                };
                const buildparams=function(p){
                    if( p && typeof( p )==='object' ){
                        p=Object.keys( p ).map(function( k ){
                            return typeof( p[ k ] )=='object' ? buildparams( p[ k ] ) : [ encodeURIComponent( k ), encodeURIComponent( p[ k ] ) ].join('=')
                        }).join('&');
                    }
                    return p;
                };
                const createpoly=function(){
                    poly=new google.maps.Polygon({
                      strokeColor: '#FF0000',
                      strokeOpacity: 0.8,
                      strokeWeight: 3,
                      fillColor: '#FF0000',
                      fillOpacity: 0.35,
                      draggable:true,
                      editable:true
                    });
                    poly.setMap( map );
                    return poly;
                };

                centre=new google.maps.LatLng( 51.483719, -0.020037 );
                div=document.getElementById('map');
                input=document.querySelector('#container > form > input[name="polyname"]');
                bttn=document.querySelector('#container > form > input[type="button"]');

                options = {
                    zoom: 15,
                    center: centre,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    disableDefaultUI: false,
                    mapTypeControl: true,
                    mapTypeControlOptions: {
                        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                        mapTypeIds: [ 'roadmap', 'terrain', 'satellite', 'hybrid' ]
                    }
                };
                map = new google.maps.Map( div, options );



                createpoly();



                google.maps.event.addListener( map, 'click', e=>{
                    path=poly.getPath();
                    path.push( e.latLng );
                });

                google.maps.event.addListener( poly, 'rightclick', e=>{
                    poly.setMap( null );
                    createpoly();
                });

                bttn.addEventListener('click',e=>{
                    if( input.value!='' ){

                        path=poly.getPath();
                        polypath=[];

                        for( let i=0; i < path.length; i++ ){
                            let point=path.getAt( i );
                            polypath.push( { lat:point.lat(), lng:point.lng() } )
                        }
                        let params={
                            path:JSON.stringify( polypath ),
                            name:input.value
                        }
                        let url=location.href;
                        let callback=function(r){
                            console.info( r );
                            input.value='';
                            poly.setMap( null );
                            createpoly();
                        };
                        /* send the polygon data */
                        ajax.call( this, url, params, callback );
                    }
                })
            }
        </script>
        <style>
            body{ background:white; }
            #container{
                width: 90%;
                min-height: 90vh;
                height:auto;
                box-sizing:border-box;
                margin: auto;
                float:none;
                margin:1rem auto;
                background:whitesmoke;
                padding:1rem;
                border:1px solid gray;
                display:block;
            }
            #map {
                width: 100%;
                height: 80%;
                clear:none;
                display:block;
                z-index:1!important;
                background:white;
                border:1px solid black;
            }
        </style>
    </head>
    <body>
        <div id='container'>
            <form method='post'>
                <input type='text' name='polyname' />
                <input type='button' value='Commit' title='Store the polygon' />
            </form>
            <div id='map'></div>
            <div id='data'></div>
        </div>
    </body>
</html>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • thank you sir for great and perfect answer ,can you please just add the option box to select the polygon from database to edit and remove. and second thing can we do for circle also? like we use google map tool? thank you again – john david May 09 '19 at 13:22
  • alas I'm a little too busy - anyway, I'm sure you'd appreciate a little challenge - it is, after all, not a terribly difficult task that lies ahead. – Professor Abronsius May 09 '19 at 14:35
  • i appreciate your help sir, thank you so much and i will try my best about next part and hope when u get free time you can drop ur help here again , thank you sir. – john david May 09 '19 at 15:45