Skip to content

Instantly share code, notes, and snippets.

@knownasilya
Forked from Hagith/drawing-tools.html
Last active November 6, 2023 18:45
Show Gist options
  • Save knownasilya/89a32e572989f0aff1f8 to your computer and use it in GitHub Desktop.
Save knownasilya/89a32e572989f0aff1f8 to your computer and use it in GitHub Desktop.
Google Maps Advanced Drawing
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>Drawing Tools</title>
<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;
width: 960px;
height: 700px;
}
#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) {
if (selectedShape.type !== 'marker') {
selectedShape.setEditable(false);
}
selectedShape = null;
}
}
function setSelection (shape) {
if (shape.type !== 'marker') {
clearSelection();
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
selectedShape = shape;
}
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: 16,
center: new google.maps.LatLng(52.25097, 20.97114),
mapTypeId: google.maps.MapTypeId.SATELLITE,
disableDefaultUI: true,
zoomControl: true
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true,
draggable: 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,
draggable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) {
var newShape = e.overlay;
newShape.type = e.type;
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.
google.maps.event.addListener(newShape, 'click', function (e) {
if (e.vertex !== undefined) {
if (newShape.type === google.maps.drawing.OverlayType.POLYGON) {
var path = newShape.getPaths().getAt(e.path);
path.removeAt(e.vertex);
if (path.length < 3) {
newShape.setMap(null);
}
}
if (newShape.type === google.maps.drawing.OverlayType.POLYLINE) {
var path = newShape.getPath();
path.removeAt(e.vertex);
if (path.length < 2) {
newShape.setMap(null);
}
}
}
setSelection(newShape);
});
setSelection(newShape);
}
else {
google.maps.event.addListener(newShape, 'click', function (e) {
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);
</script>
</head>
<body>
<div id="panel">
<div id="color-palette"></div>
<div>
<button id="delete-button">Delete Selected Shape</button>
</div>
</div>
<div id="map"></div>
</body>
</html>
@knownasilya
Copy link
Author

See demo here: http://bl.ocks.org/knownasilya/89a32e572989f0aff1f8

  • Fixed marker deletion

@aikusuma
Copy link

how to get a new address ?
add search bar pls

@skwerlzu
Copy link

I am messing around with this and I have added further variables and some click events to move directly from one object to another.

I need to figure out how to perform a click event on a polyline to load the vars associated, but I can't for the life of me figure out how to do it programmatically. I need to cycle through the created items and pull the wanted data.

> <script type="text/javascript">
      var drawingManager;
      var selectedShape;
      var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
      var selectedColor;
      var colorButtons = {};
      var cur_coords = '';
      var lines = [];
      var gons = [];
      var marker_list = [];
      var infowindow = new google.maps.InfoWindow();
      var shape;
      var cur_type;
      var dummy_selected;
      var map;

      function clearSelection() {
          dummy_selected = selectedShape;
          $('#objectid').val('');
            $('#object_name_div').html('<label for="object_name">Name</label><input type="text" class="form-control" id="object_name" name="object_name" placeholder="Name">');
            //alert(shape.name);
            $('#objectcoords_div').html('<label for="objectcoords">Coordinates</label><input type="text" class="form-control" id="objectcoords" name="objectcoords" placeholder="Coordinates">')

            $('#objecticons').val(['']).trigger("change");
            $('#objectcats').val(['']).trigger("change");
            $("textarea#objectdesc").val('');
            $('#objecticon').attr('value','');
            $('#objectimg').attr('value','');

          if (cur_type == google.maps.drawing.OverlayType.MARKER) {
              selectedShape = null;
          }else{
        if (selectedShape) {
                setTimeout(function(){
            $('#path_coords').text(selectedShape.getPath().getArray().toString());
            setTimeout(function(){
                dummy_selected.setEditable(false);
          dummy_selected = null;
            //selectedShape.setEditable(false);
          //selectedShape = null;
        },100);
        },100);


        }
        }
      }


      function clearSelectionAll() {
          dummy_selected = selectedShape;
          $('#objectid').val('');
            $('#object_name_div').html('<label for="object_name">Name</label><input type="text" class="form-control" id="object_name" name="object_name" placeholder="Name">');
            //alert(shape.name);
            $('#objectcoords_div').html('<label for="objectcoords">Coordinates</label><input type="text" class="form-control" id="objectcoords" name="objectcoords" placeholder="Coordinates">')
            $('#objecticons').val(['']).trigger("change");
            $('#objectcats').val(['']).trigger("change");
            $("textarea#objectdesc").val('');
            $('#objecticon').attr('value','');
            $('#objectimg').attr('value','');

          if (cur_type == google.maps.drawing.OverlayType.MARKER) {
              selectedShape = null;
          }else{
        if (selectedShape) {
                setTimeout(function(){
            $('#path_coords').text(selectedShape.getPath().getArray().toString());
            setTimeout(function(){
                dummy_selected.setEditable(false);
          dummy_selected = null;
            selectedShape.setEditable(false);
          selectedShape = null;
        },100);
        },100);


        }
        }
      }

      function updateselected(){

         selectedShape.name = $('#object_name').val();
         selectedShape.desc = $('#objectdesc').val();
         selectedShape.cats = $('#objectcats').val();
         selectedShape.icon = $('#objecticons').val();
      }

      function setSelection(shape) {

        dummy_selected = selectedShape;
        clearSelection();

        selectedShape = shape;

        cur_type = shape.type;
        if (shape.type == google.maps.drawing.OverlayType.MARKER) {
            $('#objectcoords_div').html('');
            $('#imgurlreset').html('<input type="text" class="media-input" name="icon-url" id="icon-url"/>');

            $('#objectid').val(shape.id);
            $('#object_name').attr('value', shape.name)
            //alert(shape.name);
            $('#objectcoords').attr('value', shape.coords)
            $('#objectcats').val(shape.cats).trigger("change");
            $("textarea#objectdesc").val(shape.desc);
            $('#objecticons').val(shape.icon).trigger("change");
            $('#objectimg').attr('value',shape.imgurl);

        }else if (shape.type == google.maps.drawing.OverlayType.POLYLINE){
            $('#objectcoords_div').html('<label for="objectcolor">Color</label><input type="text" class="form-control" id="objectcolor" name="objectcolor" placeholder="Color"><input type="hidden" class="form-control" id="objectcoords" name="objectcoords" placeholder="Coordinates">');

            $('#objectid').val(shape.id);
            $('#object_name').attr('value', shape.name)
            //alert(shape.name);
            $('#objectcoords').attr('value', selectedShape.getPath().getArray().toString())
            $('#objectcats').val(shape.cats).trigger("change"); 
            $("textarea#objectdesc").val(shape.desc);
            //$('#objecticon').attr('value',shape.icon);
            $('#objectcolor').attr('value',shape.color);
            shape.setEditable(true);
            selectColor(shape.get('fillColor') || shape.get('strokeColor'));
        alert(selectedShape.getPath().getArray());
        setTimeout(function(){
            $('#path_coords').text(selectedShape.getPath().getArray().toString());
        },100);
        }else{
            $('#objectcoords_div').html('<label for="objectcolor">Color</label><input type="text" class="form-control" id="objectcoords" name="objectcolor" placeholder="Color"><input type="hidden" class="form-control" id="objectcoords" name="objectcoords" placeholder="Coordinates">');

            $('#objectid').val(shape.id);
            $('#object_name').attr('value', shape.name)
            //alert(shape.name);
            $('#objectcoords').attr('value', selectedShape.getPath().getArray().toString())
            $('#objectcats').val(shape.cats).trigger("change"); 
            $("textarea#objectdesc").val(shape.desc);
            //$('#objecticon').attr('value',shape.icon);
            $('#objectcolor').attr('value',shape.color);
            shape.setEditable(true);
            selectColor(shape.get('fillColor') || shape.get('strokeColor'));

        setTimeout(function(){
            $('#path_coords').text(selectedShape.getPath().getArray().toString());
        },100);
        }




      }

      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() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 7,
          center: new google.maps.LatLng(40.0000, 48.0000),
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          disableDefaultUI: true,
          zoomControl: true

        });



        var polyOptions = {
          strokeWeight: 8,
          fillOpacity: 0.8,
          editable: true,
          id: gons.length
        };
        // 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.POLYLINE,
          drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: [
        google.maps.drawing.OverlayType.MARKER,
        google.maps.drawing.OverlayType.POLYGON,
        google.maps.drawing.OverlayType.POLYLINE
      ]
    },
          markerOptions: {
              position: event.latLng,
              animation: google.maps.Animation.DROP,
            draggable: true,
            id: 'm'+marker_list.length
          },
          polylineOptions: {
              strokeWeight: 8,
          fillOpacity: 0.8,
            editable: true,
            id: lines.length
          },
          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.id = 'm'+marker_list.length;
            newShape.name = 'Marker ' + marker_list.length;
            newShape.imgurl = 'image here';
            newShape.cats = [];
            newShape.coords = event.latLng;
            newShape.desc = 'This is a new marker bitch!';
            newShape.icon = '';
            newShape.type = e.type;
            marker_list.push(newShape);
            google.maps.event.addListener(newShape, 'click', function() {
                //alert(this.position);
                //alert(this.id);
              setSelection(newShape);
            });

            setSelection(newShape);

          }else if (e.type == google.maps.drawing.OverlayType.POLYLINE){
              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.id = 'pl'+lines.length;
            newShape.name = 'Polyline ' + lines.length;
            newShape.color = '#ffffff';
            newShape.cats = [];
            newShape.desc = 'This is a new marker bitch!';
            newShape.icon = 'Super Icon here';
            newShape.type = e.type;
            lines.push(newShape);
            google.maps.event.addListener(newShape, 'click', function() {
              setSelection(newShape);

            });

            setSelection(newShape);
          }else{
            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.id = 'pg'+gons.length;
            newShape.name = 'Polygon ' + gons.length;
            newShape.color = '#ffffff';
            newShape.cats = [];
            newShape.desc = 'This is a new marker bitch!';
            newShape.icon ;
            newShape.type = e.type;
            gons.push(newShape);
            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', clearSelectionAll);
        google.maps.event.addListener(map, 'click',  clearSelectionAll);
        google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);

        buildColorPalette();

              setTimeout(function(){

google.maps.event.addListener(drawingManager, 'polylinecomplete', function(line) {
$('#path_coords').text(line.getPath().getArray().toString());




});

},1000);
      }
      google.maps.event.addDomListener(window, 'load', initialize);




function add_from_text(){

    map.data.toGeoJson(function (json) {
        alert(JSON.stringify(json));
        localStorage.setItem('geoData', JSON.stringify(json));
        initControls(json);
    });

}



    </script>

> 

@guilherme1301
Copy link

guilherme1301 commented Apr 22, 2016

First of all, thanks for this code, it was really helpful on what i had to do.
I have messed around with it a little bit and this is what i came up with: I have changed the map type, changed the position of a few things and added a confirmation box when the button "Delete a selected shape" is clicked, I hope this was helpful to some of you.
(the code is in the link bellow)

https://github.com/guilherme1301/Mapa-para-a-Behive/blob/master/Deleting%20a%20selected%20shape.html

@filpap
Copy link

filpap commented Feb 21, 2018

Thanks for the very helpful code.
I would like to ask if there is a way to view the coordinates of the position of the mouse cursor while you are drawing.
Thanks

@adityatandon007
Copy link

Thanks buddy, I was looking for this for the past few days. Awesome work. One more thing I would like to ask if we can get the coordinates while drawing and, when shapes are moved to new location. Would be very helpful ! Thanks again

@RohitNext
Copy link

How we can manage predefined shapes. Like change shape color, edit and delete the shape etc.
How we use "setSelection" methods for exits shapes.

@imezei
Copy link

imezei commented Sep 10, 2018

yes, if we can get the coordinates while drawing - that would be great! tnx.

@azaddeveloper
Copy link

Thanks a lot,
One more question can you help me with how can I save CIRCLE, RECTANGLE, POLYGON drawing data into database and load when my map is fully loaded.

@knownasilya
Copy link
Author

@azaddeveloper not natively with the drawing manager. I created a tool to help https://github.com/knownasilya/google-maps-drawing-tools

@Deepp805
Copy link

Deepp805 commented Nov 2, 2023

Was someone able to figure out how to get the coordinates of the shape as you are drawing the shape?

@knownasilya
Copy link
Author

@Deepp805 you'd have to manually draw the polygon and then add it to the drawing manager, example here: https://github.com/knownasilya/google-maps-markup/blob/master/addon/components/google-maps-markup.js#L213

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment