Allow user to draw rectangle on Google Maps

I am trying to allow the user to draw a rectangle on Google Maps by clicking on a button, and then adding a rectangle to the map, which can then be resized / dragged. As far as I know, the Google API does not allow us to click and drag on the map to draw a rectangle, so I think we should use the start / start borders?

I get an error (see my JSFiddle here ) when I click on the event handler responsible for drawing the rectangle:

rectangle.setMap(map);
google.maps.event.addListener(map, 'click', function() {
    addRecPath();
});

I am trying to create a way for users to draw a rectangle based on tutorials provided by Google here (polylines) and here (user editable shapes) .

Where am I mistaken? It seems the problem is the event handler. Can (or should) this rectangle be clicked inside the array?

+4
source share
1 answer

Things you miss

  • You need to initialize the Google Maps API API.
  • You must initialize the Draw Manager object to draw shapes.

Follow the tutorial for reference.

. / google. Google API- Google . (, , , )

.

JS

var map;
var drawingManager = new google.maps.drawing.DrawingManager();

function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(44.5452, -78.5389),
        zoom: 9
    };
    map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);
}

function drawRec() {
        //Setting options for the Drawing Tool. In our case, enabling Polygon shape.
        drawingManager.setOptions({
            drawingMode : google.maps.drawing.OverlayType.RECTANGLE,
            drawingControl : true,
            drawingControlOptions : {
                position : google.maps.ControlPosition.TOP_CENTER,
                drawingModes : [ google.maps.drawing.OverlayType.RECTANGLE ]
            },
            rectangleOptions : {
                strokeColor : '#6c6c6c',
                strokeWeight : 3.5,
                fillColor : '#926239',
                fillOpacity : 0.6,
                editable: true,
                draggable: true
            }   
        });
        // Loading the drawing Tool in the Map.
        drawingManager.setMap(map);
}

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

HTML

<button onclick="drawRec();">Draw Rectangle</button>
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=drawing"></script>
+7

Source: https://habr.com/ru/post/1536202/


All Articles