Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow User to Draw Rectangle on Google Maps

I am trying to let the user draw a rectangle on Google Maps by clicking on a button and then adding the rectangle to the map that they can then resize/drag. As far as I know, Google's API doesn't allow us to let the user click and drag the mouse cursor across the map to draw the rectangle, so I think we have to use initial/starting bounds?

I am getting 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've been trying to create how to let the users draw a rectangle based on the tutorials provided by Google here (polylines) and here (user-editable shapes).

Where am I going wrong? It seems like the problem is the event handler. Can (or should) this rectangle be pushed inside an array?

like image 488
kaoscify Avatar asked Apr 12 '14 04:04

kaoscify


1 Answers

Things you are missing

  1. Need to initialize google drawing Maps API library.
  2. Need to initialize drawing Manager Object to draw Shapes.

Follow the tutorial for your reference.

NO. You dont have to use initial/starting bounds to draw a shape in google maps. Google provides Google drawing API to allow users to draw a shapes. You can use any shapes.(Polygon, Polyline, circle, rectangle)

Please go through the following demo.

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>
like image 164
ArunRaj Avatar answered Oct 22 '22 17:10

ArunRaj