Custom Drawing Control [Google Maps v3 Drawing Library]
Asked Answered
G

2

5

I'm working with the Drawing Library of the Google Maps API and i want to trigger the drawing of a marker with a custom button.

I've read this part of the documentation :

Hiding the drawing control causes the drawing tools control to not display, but all of the functionality of the DrawingManager class is still available. In this way, you can implement your own control, if desired. Removing the DrawingManager from the map object disables all drawing functionality; it must be reattached to the map with drawingManager.setMap(map), or a new DrawingManager object constructed, if drawing features are to be restored.

But i cannot find out how to use the DrawingManager to do this.

Genus answered 23/2, 2012 at 17:19 Comment(0)
B
13

on button click:

turn on drawing marker: drawingManager.setDrawingMode(google.maps.drawing.OverlayType.MARKER);

turn off: drawingManager.setDrawingMode(null);

Bibelot answered 23/2, 2012 at 20:56 Comment(1)
Same applies to, OverlayType.CIRCLE, OverlayType.POLYGONBacker
F
4

You can:

  1. create a DrawingManager without controls, or with certain controls omitted, then
  2. add custom buttons for them, and then
  3. add handlers to those buttons to trigger the functions that @user1226919 mentions.

Example:

var drawingManager = new google.maps.drawing.DrawingManager({
    drawingControl: false
});
drawingManager.setMap(map);

// drawingManager is now ready

var marker_btn = document.createElement("button");
marker_btn.innerHTML = "Create Marker";

// add handlers
marker_btn.addEventListener("click", (function () {
    // closure handles local toggle variables
    var toggled = false;
    var originalHTML = marker_btn.innerHTML;
    return function (e) {
        if (toggled) {
            drawingManager.setDrawingMode(null);
            e.target.innerHTML = originalHTML;
        } else {
            drawingManager.setDrawingMode(google.maps.drawing.OverlayType.MARKER);
            e.target.innerHTML = "Cancel";
        }
        toggled = !toggled;
    }
})());

// add button to map controls
map.controls[ google.maps.ControlPosition.TOP_CENTER ].push( marker_btn );

Check out a working example with a custom polygon button: https://codepen.io/bozdoz/pen/jZNXNP?editors=0010

Fluctuate answered 28/1, 2018 at 21:53 Comment(2)
I like this answer because of very well working fiddleMillennium
Note .setDrawingModer(null) will set the cursor to the little hand, with which you can select drawn objects and move the map.Atonsah

© 2022 - 2024 — McMap. All rights reserved.