Draw and delete polygon in google map - google-maps

I try to draw polygon on button click and delete polygon from another button, it's working fine first time but after delete I can't draw another polygon. Please guide me. Here is code snippet:
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true,
fillColor: '#FF1493'
};
var selectedShape;
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: false,
markerOptions: {
draggable: true
},
polygonOptions: polyOptions
});
$('#enablePolygon').click(function(){
drawingManager.setMap(map);
});
$('#resetPolygon').click(function(){
if (selectedShape) {
selectedShape.setMap(null);
}
drawingManager.setMap(null);
$('#showonPolygon').hide();
$('#resetPolygon').hide();
});
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
}
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
all_overlays.push(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);
}
});
Here I show reset button on polygon complete event and try to find area of current polygon:
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
// var area = google.maps.geometry.spherical.computeArea(selectedShape.getPath());
// $('#areaPolygon').html(area.toFixed(2)+' Sq meters');
$('#resetPolygon').show();
});
Here is HTML:
<input type="button" id="enablePolygon" value="Calculate Area" />
<input type="button" id="resetPolygon" value="Reset" style="display: none;" />
<div id="showonPolygon" style="display:none;"><b>Area:</b> <span id="areaPolygon"> </span></div>

You are setting the DrawingMode of the DrawingManager to null. When you re-enable the DrawingManager, you need to set it back to google.maps.drawing.OverlayType.POLYGON.
$('#enablePolygon').click(function() {
drawingManager.setMap(map);
drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
});
proof of concept fiddle
code snippet:
var geocoder;
var map;
var all_overlays = [];
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true,
fillColor: '#FF1493'
};
var selectedShape;
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: false,
markerOptions: {
draggable: true
},
polygonOptions: polyOptions
});
$('#enablePolygon').click(function() {
drawingManager.setMap(map);
drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
});
$('#resetPolygon').click(function() {
if (selectedShape) {
selectedShape.setMap(null);
}
drawingManager.setMap(null);
$('#showonPolygon').hide();
$('#resetPolygon').hide();
});
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
// var area = google.maps.geometry.spherical.computeArea(selectedShape.getPath());
// $('#areaPolygon').html(area.toFixed(2)+' Sq meters');
$('#resetPolygon').show();
});
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
}
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
all_overlays.push(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);
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<input type="button" id="enablePolygon" value="Calculate Area" />
<input type="button" id="resetPolygon" value="Reset" style="display: none;" />
<div id="showonPolygon" style="display:none;"><b>Area:</b> <span id="areaPolygon"> </span>
</div>
<div id="map_canvas"></div>

Related

Getting updated coords when polyline/polygon vertex moved. (Google Maps)

I've figured out how to grab the coords when a polyline or polygon is added or a vertex is deleted, but I can't seem to apply how to catch when a polyline or polygon vertex is moved (vertex only, I have dragging entire poly's disabled intentionally). I'm using this link as a reference: event after modifying polygon in google maps api v3
Here is my complete HTML code (posted at pastebin for the sake of the reader):
http://pastebin.com/95HcHqQR
Here is the section I'm trying to make catch moves:
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);
///////////////////////////////////////////////////////////
//This section is intended to catch vertex moves...currently not
google.maps.event.addListener(newShape, 'polygoncomplete', function(e) {
google.maps.event.addListener(newShape.getPath(), 'set_at', function(e) {
google.maps.event.addListener(newShape.getPath(), 'insert_at', function(e) {
var path = newShape.getPaths().getAt(e.path);
document.getElementById("polygonEditTest").value += path.getAt(e.vertex) + '\n';
})
});
});
google.maps.event.addListener(newShape, 'polylinecomplete', function(e) {
google.maps.event.addListener(newShape.getPath(), 'set_at', function(e) {
google.maps.event.addListener(newShape.getPath(), 'insert_at', function(e) {
var path = newShape.getPaths().getAt(e.path);
document.getElementById("polylineEditTest").value += path.getAt(e.vertex) + '\n';
})
});
});
///////////////////////////////////////////////////////////
// Add an event listener that selects the newly-drawn shape when the user
// clicks 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);
/////////////////////////////////////////////////////////////
//Update textboxes with geo data when polygon vertex deleted
document.getElementById("action_gon").value = ''
document.getElementById("action_gon").value += "#polygon vertex deleted\n";
for (var i = 0; i < path.length; i++) {
document.getElementById("action_gon").value += path.getAt(i) + '\n';
}
//
if (path.length < 3) {
newShape.setMap(null);
document.getElementById("action_gon").value = 'This box shows coords when a new POLYGON shape is added and/or vertex deleted'
}
}
if (newShape.type === google.maps.drawing.OverlayType.POLYLINE) {
var path = newShape.getPath();
path.removeAt(e.vertex);
/////////////////////////////////////////////////////////////
//Update textboxes with geo data when polyline vertex deleted
document.getElementById("action_line").value = ''
document.getElementById("action_line").value += "#polyline vertex deleted\n";
for (var i = 0; i < path.length; i++) {
document.getElementById("action_line").value += path.getAt(i) + '\n';
}
//
if (path.length < 2) {
newShape.setMap(null);
document.getElementById("action_line").value = 'This box shows coords when a new POLYLINE shape is added and/or vertex deleted'
}
}
}
setSelection(newShape);
});
setSelection(newShape);
} else {
google.maps.event.addListener(newShape, 'click', function(e) {
setSelection(newShape);
});
setSelection(newShape);
}
});
EDIT: Here is what I believe to be the minimal code needed to demonstrate the problem (inability to capture vertex moves).
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<title>Test</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=drawing,places"></script>
<style type="text/css">
#map, html, body {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
}
</style>
<script type="text/javascript">
//Map Specifications
function initialize () {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: new google.maps.LatLng(33.27144940863937, -117.2983479390361),
mapTypeId: google.maps.MapTypeId.HYBRID,
disableDefaultUI: true,
zoomControl: true,
mapTypeControl: false,
scaleControl: true,
streetViewControl: true,
rotateControl: true,
fullscreenControl: false
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true,
draggable: false
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers and lines
drawingManager = new google.maps.drawing.DrawingManager({
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYLINE,
google.maps.drawing.OverlayType.POLYGON
]
},
markerOptions: {
draggable: false
},
polylineOptions: {
editable: true,
draggable: false
},
//rectangleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
//////////////////////////////////////////
var drawingManager;
var selectedShape;
function clearSelection () {
if (selectedShape) {
if (selectedShape.type !== 'marker') {
selectedShape.setEditable(false);
}
selectedShape = null;
}
}
function setSelection (shape) {
if (shape.type !== 'marker') {
clearSelection();
shape.setEditable(true);
}
selectedShape = shape;
}
//////////////////////////////////////////
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);
google.maps.event.addListener(newShape, 'polygoncomplete', function (e) {
google.maps.event.addListener(newShape.getPath(), 'set_at', function() {
google.maps.event.addListener(newShape.getPath(), 'insert_at', function() {
var path = newShape.getPaths().getAt(e.path);
document.getElementById("polygonEditTest").value += path.getAt(e.vertex) + '\n';
})
});
});
google.maps.event.addListener(newShape, 'polylinecomplete', function (e) {
google.maps.event.addListener(newShape.getPath(), 'set_at', function(e) {
google.maps.event.addListener(newShape.getPath(), 'insert_at', function(e) {
var path = newShape.getPaths().getAt(e.path);
document.getElementById("polylineEditTest").value += path.getAt(e.vertex) + '\n';
})
});
});
// Add an event listener that selects the newly-drawn shape when the user
// clicks it.
setSelection(newShape);}
else {
google.maps.event.addListener(newShape, 'click', function (e) {
setSelection(newShape);
});
setSelection(newShape);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="geoinfoboxes">
<textarea id="polylineEditTest" rows="8" cols="46">This box shows coords for edited POLYLINES (ie. moving a vertex)</textarea>
<textarea id="polygonEditTest" rows="8" cols="46">This box shows coords for edited POLYGONS (ie. moving a vertex)</textarea>
</div>
<div id="map"></div>
</body>
</html>
To listen for the drag of an editable polygon's vertex drag, use an MCVArray set_at event listener:
google.maps.event.addListener(polygon.getPath(), 'set_at', processVertex);
google.maps.event.addListener(polygon.getPath(), 'insert_at', processVertex);
function processVertex(e) {
var logStr = ""
for (var i = 0; i < this.getLength(); i++) {
logStr += this.getAt(i).toUrlValue(6) + " ";
}
console.log(logStr);
}
proof of concept fiddle
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var polygon = new google.maps.Polygon({
path: [new google.maps.LatLng(37.4544762, -122.1161696),
new google.maps.LatLng(37.3751, -122.1731859),
new google.maps.LatLng(37.4274745, -122.169719)
],
map: map,
editable: true
});
google.maps.event.addListener(polygon.getPath(), 'set_at', processVertex);
google.maps.event.addListener(polygon.getPath(), 'insert_at', processVertex);
function processVertex(e) {
var logStr = ""
for (var i = 0; i < this.getLength(); i++) {
logStr += this.getAt(i).toUrlValue(6) + " ";
}
console.log(logStr);
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

Google Maps 2 InfoWindows Auto-Opening infoWindow, 1 infoWindow after click

I have an auto-opening infoWindow.
I wish only two were opened automatically, while one did not. The effect Just like in the pictures.
My Code:
<script>
function initialize() {
var openedInfoWindow = [];
var locations = [
['Oddział', 52.846190, 17.723237, 3],
['Oddział', 52.812224, 17.201023, 2],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1]
];
var cityCircle;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2], locations[i][3]),
map: map,
content: locations[i][0]
});
bounds.extend(marker.position);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i, infowindow) {
return function () {
if(openedInfoWindow[i] != null){
openedInfoWindow[i].close();
openedInfoWindow[i] = null;
}else{
infowindow.setContent(this.content);
infowindow.open(map, this);
openedInfoWindow[i] = infowindow;
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow[i] = null;
});
}
}
})(marker, i, infowindow));
google.maps.event.trigger(marker, 'click');
}
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(9);
google.maps.event.removeListener(listener);
});
}
function loadScript() {
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyADTnbl7e9y2o13cXkUFO8RZpXFJI-yzp4&' + 'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>`
Picture 1 = so now
Picture 2 = so it has to be
I would suggest you generalize it, add a member to your array to determine whether to open the marker or not.
var locations = [
// IW content, lat, lng, nowrap, open IW
['Oddział', 52.846190, 17.723237, 3, true],
['Oddział', 52.812224, 17.201023, 2, true],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1, false]
];
Then do this to open the infowindow:
if (locations[i][4]) {
google.maps.event.trigger(marker, 'click');
}
proof of concept fiddle
code snippet:
function initialize() {
var openedInfoWindow = [];
var locations = [
['Oddział', 52.846190, 17.723237, 3, false],
['Oddział', 52.812224, 17.201023, 2, true],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1, true]
];
var cityCircle;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2], locations[i][3]),
map: map,
content: locations[i][0]
});
bounds.extend(marker.position);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i, infowindow) {
return function() {
if (openedInfoWindow[i] != null) {
openedInfoWindow[i].close();
openedInfoWindow[i] = null;
} else {
infowindow.setContent(this.content);
infowindow.open(map, this);
openedInfoWindow[i] = infowindow;
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow[i] = null;
});
}
}
})(marker, i, infowindow));
if (locations[i][4]) {
google.maps.event.trigger(marker, 'click');
}
}
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() {
map.setZoom(9);
google.maps.event.removeListener(listener);
});
}
function loadScript() {
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?' + 'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

Remove DrawingManager from Google maps

I've created a map where I can draw lines in different colors, works just fine, but when I'm trying to remove my drawings it doesn't work very well. I insert all my DrawingManager into an array, and from there trying to remove them. Anyone can help me please?
See the whole project at http://jsfiddle.net/jv8wp4p0/
$(document).ready(function(){
google.maps.event.addDomListener(window, 'load', initGMap);
var gMap;
var drawingMap = [];
var colorIndex = 0;
function initGMap() {
var mapOptions = {
center: new google.maps.LatLng(63.354122, 16.007140),
zoom: 6,
mapTypeId: google.maps.MapTypeId.TERRAIN,
disableDefaultUI: true
};
gMap = new google.maps.Map(document.getElementById('googleMaps'), mapOptions);
}
$.selMapBtn = function (btnObj) {
$(".mapBtn").removeClass('mapBtnSelected');
if ($(btnObj).hasClass('reMap')) {
// Remove last action...
if(drawingMap.length > 0) {
drawingMap[drawingMap.length-1].setMap(null);
}
}
if ($(btnObj).hasClass('clMap')) {
// Remove all actions...
for(i in drawingMap) {
drawingMap[i].setMap(null);
}
}
if ($(btnObj).hasClass('mapPen')) {
$(btnObj).addClass('mapBtnSelected');
penColor = $(btnObj).data('color');
i = drawingMap.length;
drawingMap[i] = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYLINE,
drawingControl: false,
polylineOptions: {
strokeColor: penColor,
strokeWeight: 5,
clickable: false,
editable: false,
zIndex: 1
}
});
drawingMap[i].setMap(gMap);
}
};
$(".mapBtn").click(function () {
$.selMapBtn($(this));
return false;
});
});
Basically you don't need multiple DrawingManager-instances at all, the options of a DrawingManager may be set dynamically(e.g. the PolylineOptions in your code).
To access the shapes created by the DrawingManager you must store them somewhere(e.g. in an array). Observe the overlaycomplete-event of the DrawingManager, that's the moment when you may access a newly created shape.
$(document).ready(function () {
google.maps.event.addDomListener(window, 'load', initGMap);
var gMap,
drawings = [],
drawingMan,
colorIndex = 0;
function initGMap() {
var mapOptions = {
center: new google.maps.LatLng(63.354122, 16.007140),
zoom: 6,
mapTypeId: google.maps.MapTypeId.TERRAIN,
disableDefaultUI: true
};
gMap = new google.maps.Map(document.getElementById('googleMaps'),
mapOptions);
drawingMan = new google.maps.drawing.DrawingManager({
drawingControl: false
});
google.maps.event.addListener(drawingMan, 'overlaycomplete',
function (shape) {
//push shape onto the array
drawings.push(shape.overlay);
});
}
$.selMapBtn = function (btnObj) {
$(".mapBtn").removeClass('mapBtnSelected');
if ($(btnObj).hasClass('reMap')) {
drawingMan.setDrawingMode(null);
if (drawings.length) {
//remove last shape
drawings.pop().setMap(null);
}
}
if ($(btnObj).hasClass('clMap')) {
drawingMan.setDrawingMode(null);
//remove all shapes
while (drawings.length) {
drawings.pop().setMap(null);
}
}
if ($(btnObj).hasClass('mapPen')) {
$(btnObj).addClass('mapBtnSelected');
penColor = $(btnObj).data('color');
drawingMan.setOptions({
polylineOptions: {
strokeColor: penColor,
strokeWeight: 5,
clickable: false,
editable: false,
zIndex: 1
},
map: gMap,
drawingMode: google.maps.drawing.OverlayType.POLYLINE
});
}
};
$(".mapBtn").click(function () {
$.selMapBtn($(this));
return false;
});
});
http://jsfiddle.net/jv8wp4p0/3/

Get the lat lng when plotting the polygon points

I am trying to get the lat lng of the polygon while drawing the polygon on google map. Does anyone know what event is triggered when we plot the points of polygon.
Basically what I am trying to do is undo/redo function for the polygon. So when a user plots 2 points one then clicks undo then it should be able to delete 1 point on one click.
As the map click event is disabled while drawing a polygon how to get the lat lng points? Is it possible what I am trying to do? Can anyone please help me with this? Any links or examples that I could refer to?
Below is my code to draw polygon:
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: false,
polygonOptions: {
strokeWeight: 2,
fillOpacity: 0.2,
editable: true,
fillColor: '#FFF000',
strokeColor: '#FFF000',
geodesic: true,
suppressUndo: true
},
polylineOptions: {
editable: false,
suppressUndo: true
}
});
drawingManager.setMap(map);
Try this
var myPoly;
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
myPoly = polygon;
get_coordinates(polygon);//call to get coordinates
//editing polygon function
google.maps.event.addListener(polygon.getPath(), 'set_at', function() {
get_coordinates(polygon);//call to get coordinates
});
var newShape = polygon.overlay;
//newShape.type = polygon.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
});
and the get coordinate function
//function to get coordinates of polygon
function get_coordinates(polygon){
var full_path = [];//initialize array for set coordinates.
polygon.getPath().forEach(function(elem, index){
full_path.push(elem.toUrlValue());
});
return full_path;
}
ok. I can give you all the functions you need. You can integrate last code with the following. And you cannot delete any point but replace it.
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);

Enabling and Disabling Dragging Markers by Checkbox

Can you please take a look at this Demo and let me know how I can make the markers Dragable when the check box is unchecked. Please be informed that all markers has their own associated checkbox it means that user can lock each marker which they want( Not all together). Initially all Markers are unchecked when they loaded to page . And finally I need to change the icon when the marker checked as lock.
var contentString = ' -- Lock <input name="your_name" value="your_value" type="checkbox">';
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var infowindow = new google.maps.InfoWindow({ content: "" });
var data = {
"markers": [{
"latitude": 11.606503,
"longitude": 122.712637,
"title": "Copenhagen"
}, {
"latitude": 11.585988,
"longitude": 122.757084,
"title": "Barcelona"
}
]
};
locations.length = 0;
for (p = 0; p < data.markers.length; p++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.markers[p].latitude, data.markers[p].longitude),
map: map,
draggable: true,
title: "marker " + p,
id: p
});
bindMarker(marker);
bindInfoWindow(marker, map, infowindow, data.markers[p].title);
}
function bindMarker(marker) {
google.maps.event.addListener(marker, 'dragend', function () {
marker.setIcon('https://www.google.com/mapfiles/marker_green.png');
});
google.maps.event.addListener(marker, 'click', function () {
});
}
function bindInfoWindow(marker, map, infowindow, strDescription) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(strDescription + contentString);
infowindow.open(map, marker);
});
}
});
**
Update
function bindMarkerDrag(marker){
google.maps.event.addListener(checkbox, "click", function(){
draggable: false
//marker.setClickable(checkbox.checked);
});
}
then I add the
bindMarkerDrag(marker);
inside the loop Here is a Demo but not working
As I said in my comment, you need to add checkbox.checked = !marker.getDraggable(); in your marker click event listener. Not in the checkbox event listener.
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = !marker.getDraggable();
checkbox.addEventListener('click', function () {
marker.setDraggable(!this.checked);
});
Create the checbox
Check it or not if the marker is draggable or not
Manage the checkbox click event
You could something like:
google.maps.event.addListener(marker, 'mouseover', function(e){
marker.setDraggable(document.getElementById('checkbox').checked);
});
This will set the draggable property to false or true before you start dragging (if you put it on the dragstart event, you will have a slight delay.)
Replace the id checkbox with the one you need.
Check this code!! I have updated buildInfoWindow function to meet your requirements.
var map;
var locations = [];
var contentString = "--";
var infowindows = [];
$(document).ready(function () {
var latlng = new google.maps.LatLng(11.610707, 122.740089);
var myOptions = {
zoom: 12,
center: latlng,
disableDefaultUI: true,
scaleControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: true,
draggableCursor: 'move',
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var data = {
"markers": [{
"latitude": 11.606503,
"longitude": 122.712637,
"title": "Copenhagen"
}, {
"latitude": 11.585988,
"longitude": 122.757084,
"title": "Barcelona"
}
]
};
locations.length = 0;
for (p = 0; p < data.markers.length; p++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.markers[p].latitude, data.markers[p].longitude),
map: map,
draggable: true,
title: "marker " + p,
id: p
});
var infowindow = new google.maps.InfoWindow({ content: "" });
bindMarker(marker);
bindInfoWindow(marker, map, infowindow, data.markers[p].title, p);
bindMarkerDrag(marker);
}
function bindMarker(marker) {
google.maps.event.addListener(marker, 'dragend', function () {
marker.setIcon('https://www.google.com/mapfiles/marker_green.png');
});
}
function bindMarkerDrag(marker){
}
function bindInfoWindow(marker, map, infowindow, strDescription, p) {
google.maps.event.addListenerOnce(marker, 'click', function() {
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.addEventListener('click', function () {
marker.setDraggable(!this.checked);
});
var div = document.createElement('div');
div.innerHTML = strDescription + contentString + "<br /> Lock drag: ";
div.appendChild(checkbox);
infowindow.setContent(div);
infowindow.open(map, marker);
infowindows[p]= infowindow;
});
google.maps.event.addListener(marker, 'click', function() {
infowindows[p].open(map, marker);
});
}
});