Remove DrawingManager from Google maps - 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/

Related

Is there way to get google maps polygon co-ordinates value in string format

This is how I am drawing polygon. And I want it get the polygon area as drawn and mark the properties on the map in next page that lies under the drawn polygon area and also draw the polygon on it.I am getting the co-ordinates of the polygon but it is difficult to send the co-ordinates on the url to next page.
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [ 'polygon']
},
markerOptions: {icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'},
polygonOptions: {
editable: true
}
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
$.each(event.overlay.getPath().getArray(), function(key, latlng){
var lat = latlng.lat();
var lon = latlng.lng();
console.log(lat, lon);
console.log(latlng); //do something with the coordinates
lats.push({lat:lat,lon:lon});
var latlng = {lat: parseFloat(lat), lng: parseFloat(lon)};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
var t = results[0].formatted_address.split(',');
var country = t[t.length-1];
var state = t[t.length-2];
locations.push({'state':state,country:country});
// console.log(locations);
// console.log(lats);
// locations.push({'state:'lat,lon});
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
});
I can suggest using encoded paths in order to send a polygon as a string parameter in the URL of the next page. Maps JavaScript API has geometry library that allows encode and decode array of LatLng into string:
https://developers.google.com/maps/documentation/javascript/reference/3/geometry#encoding
You can use something like
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
var encodedPath = google.maps.geometry.encoding.encodePath(event.overlay.getPath());
window.open(m_url + "?path="+encodedPath, "restore polygon");
});
in page with drawing manager and restore array of LatLng on the next page as
let params = (new URL(document.location)).searchParams;
let encodedPath = params.get("path");
if (encodedPath) {
var path = google.maps.geometry.encoding.decodePath(encodedPath);
var polygon = new google.maps.Polygon({
paths: path,
map: map
});
}
Proof of concept
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [ 'polygon']
},
markerOptions: {
icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'},
polygonOptions: {
editable: true
},
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
var encodedPath = google.maps.geometry.encoding.encodePath(event.overlay.getPath());
console.log(encodedPath);
window.open("http://output.jsbin.com/hicomid?path="+encodedPath, "restore polygon");
});
}
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&libraries=drawing,geometry&callback=initMap"
async defer></script>
You can also check this example on jsfiddle: https://jsfiddle.net/xomena/tpvoL426/
I hope this helps!

After marker drag even polygon line doesn't change as per marker

I am working on google map polygon marker, I have predefined lat long array, and need to set polygon area, It is working fine for me, but when i drag the marker polygon line doesn't change, it should have to be change as i drag the marker, can anyone please help me how can i resolve this issue ? Here i have added my code, can anyone please help me ?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Polygon Arrays</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<input type="text" name="estimated_area" id="estimated_area" value="">
<input type="text" name="field_fj0d6" id="field_fj0d6" value="">
<script>
// This example creates a simple polygon representing the Bermuda Triangle.
// When the user clicks on the polygon an info window opens, showing
// information about the polygon's coordinates.
var map;
var infoWindow;
var markers = []; // Store Marker in an Array
function initMap() {
var lM = 't';
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {lat: 24.886, lng: -70.268},
mapTypeId: 'terrain'
});
// Define the LatLng coordinates for the polygon.
var triangleCoords = [
{lat: 25.774, lng: -80.190},
{lat: 18.466, lng: -66.118},
{lat: 32.321, lng: -64.757}
];
// Add Markers to Coordinates
for (var i = 0; i < triangleCoords.length; i++) {
var pos = triangleCoords[i];
var marker = new google.maps.Marker({
map: map,
position: pos,
draggable: true,
});
marker.setMap(map);
markers.push(marker);
var measure = {
mvcLine: new google.maps.MVCArray(),
mvcPolygon: new google.maps.MVCArray(),
mvcMarkers: new google.maps.MVCArray(),
line: null,
polygon: null
};
var latLng = pos;
var dot = marker;
/************** New Code ****************/
measure.mvcLine.push(latLng);
measure.mvcPolygon.push(latLng);
measure.mvcMarkers.push(dot);
var latLngIndex = measure.mvcLine.getLength() - 1;
google.maps.event.addListener(dot, "drag", function (evt) {
measure.mvcLine.setAt(latLngIndex, evt.latLng);
measure.mvcPolygon.setAt(latLngIndex, evt.latLng);
});
google.maps.event.addListener(dot, "dragend", function () {
console.log('<p>Marker dropped: Current Lat: ' + this.getPosition().lat() + ' Current Lng: ' + this.getPosition().lng() + '</p>');
drag = true;
setTimeout(function () {
drag = false;
}, 250);
if (measure.mvcLine.getLength() > 1) {
mC();
}
});
if (measure.mvcLine.getLength() > 1) {
if (!measure.line) {
measure.line = new google.maps.Polyline({
map: map,
clickable: false,
strokeColor: "#ff5b06",
strokeOpacity: 1,
strokeWeight: 3,
path: measure.mvcLine
});
}
if (measure.mvcPolygon.getLength() > 2) {
if (!measure.polygon) {
if (lM) {
measure.polygon = new google.maps.Polygon({
clickable: false,
map: map,
fillOpacity: 0.6,
fillColor: '#000000',
strokeOpacity: 0,
paths: measure.mvcPolygon
});
} else {
measure.polygon = new google.maps.Polygon({
clickable: false,
map: map,
fillOpacity: 0.6,
fillColor: '#000000',
strokeOpacity: 0,
paths: measure.mvcPolygon
});
}
}
}
}
if (measure.mvcLine.getLength() > 1) {
mC();
}
}
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#ff5b06',
strokeOpacity: 1,
strokeWeight: 3,
fillColor: '#000000',
fillOpacity: 0.6
});
bermudaTriangle.setMap(map);
}
function mR() {
if (measure.polygon) {
measure.polygon.setMap(null);
measure.polygon = null;
}
if (measure.line) {
measure.line.setMap(null);
measure.line = null
}
measure.mvcLine.clear();
measure.mvcPolygon.clear();
measure.mvcMarkers.forEach(function (elem, index) {
elem.setMap(null);
});
measure.mvcMarkers.clear();
document.getElementById('estimated_area').value = '';
document.getElementById('field_fj0d6').value = '';
}
function mC() {
var l = 0;
if (measure.mvcPolygon.getLength() > 1) {
l = google.maps.geometry.spherical.computeLength(measure.line.getPath());
}
var a = 0;
if (measure.mvcPolygon.getLength() > 2) {
a = google.maps.geometry.spherical.computeArea(measure.polygon.getPath());
}
if (a) {
var km = a / (1000 * 1000);
var feet = a * 10.7639104;
var yards = a * 1.19599005;
var acres = a * 0.000247105381;
var unit = " meters²";
var unit1 = " acres";
var unit2 = " km²";
var unit3 = " sq. ft.";
var unit4 = " yards²";
var area = feet.toFixed(0) + unit3;
//This is for update details in review tab
document.getElementById('estimated_area').value = parseFloat(area);
document.getElementById('field_fj0d6').value = String(area);
}
}
function rL() {
var test = measure.mvcLine.pop();
if (test) {
measure.mvcPolygon.pop();
var dot = measure.mvcMarkers.pop();
dot.setMap(null);
mC();
}
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDYeDBDl-8Wx98Az55EbVnpvRfSIBbwxyE&callback=initMap">
</script>
</body>
</html>
You need to bind the vertices of the polygon to the markers.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#ff5b06',
strokeOpacity: 1,
strokeWeight: 3,
fillColor: '#000000',
fillOpacity: 0.6
});
bermudaTriangle.setMap(map);
bermudaTriangle.binder = new MVCArrayBinder(bermudaTriangle.getPath());
for (var j = 0; j < bermudaTriangle.getPath().getLength(); j++) {
var mark = new google.maps.Marker({
position: bermudaTriangle.getPath().getAt(),
map: map,
draggable: true
});
mark.bindTo('position', bermudaTriangle.binder, (j).toString());
}
online example
proof of concept fiddle
code snippet:
var map;
var markers = []; // Store Marker in an Array
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: 24.886,
lng: -70.268
},
mapTypeId: 'terrain'
});
// Define the LatLng coordinates for the polygon.
var triangleCoords = [{
lat: 25.774,
lng: -80.190
},
{
lat: 18.466,
lng: -66.118
},
{
lat: 32.321,
lng: -64.757
}
];
// Add Markers to Coordinates
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#ff5b06',
strokeOpacity: 1,
strokeWeight: 3,
fillColor: '#000000',
fillOpacity: 0.6
});
bermudaTriangle.setMap(map);
bermudaTriangle.binder = new MVCArrayBinder(bermudaTriangle.getPath());
for (var j = 0; j < bermudaTriangle.getPath().getLength(); j++) {
var mark = new google.maps.Marker({
position: bermudaTriangle.getPath().getAt(),
map: map,
draggable: true
});
mark.bindTo('position', bermudaTriangle.binder, (j).toString());
}
}
google.maps.event.addDomListener(window, 'load', initMap);
/*
* Use bindTo to allow dynamic drag of markers to refresh poly.
*/
function MVCArrayBinder(mvcArray) {
this.array_ = mvcArray;
}
MVCArrayBinder.prototype = new google.maps.MVCObject();
MVCArrayBinder.prototype.get = function(key) {
if (!isNaN(parseInt(key))) {
return this.array_.getAt(parseInt(key));
} else {
this.array_.get(key);
}
}
MVCArrayBinder.prototype.set = function(key, val) {
if (!isNaN(parseInt(key))) {
this.array_.setAt(parseInt(key), val);
} else {
this.array_.set(key, val);
}
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Draw polygon with drawing manager & show area * co-ordinates in Infowindow in google maps

I'm trying to create a map where I can draw a polygon & show it's area & coordinates in the infowindow.
Below is what I have, I'm stuck at the displaying of area & co-ordinates inside the infowindow.
Link to code
code snippet:
var map, infoWindow, drawingManager;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
infoWindow = new google.maps.InfoWindow();
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYGON
]
},
polygonOptions: {
fillColor: '#ffff00',
fillOpacity: 1,
strokeWeight: 5,
clickable: false,
editable: true,
zIndex: 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
openInfoWindowPolygon(polygon);
});
}
function openInfoWindowPolygon(polygon) {
var vertices = polygon.getPath();
var contents = "z";
var bounds = new google.maps.LatLngBounds();
vertices.forEach(function(xy, i) {
bounds.extend(xy);
});
infoWindow.setContent(contents);
infoWindow.setPosition(bounds.getCenter());
drawingManager.setDrawingMode(null);
infoWindow.open(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=drawing"></script>
<div id="map-canvas"></div>
Using the Google Maps Geometry Library, there are functions that allow for computation of area.
function openInfoWindowPolygon(polygon) {
var vertices = polygon.getPath();
var contents = "<b>Vertices:</b><ol>";
vertices.forEach(function(vert, index){contents += "<li>"+vert.toString()+"</li>"});
contents += "</ol><b>Area:</b>"+google.maps.geometry.spherical.computeArea(vertices);
infoWindow.setContent(contents);
var bounds = new google.maps.LatLngBounds();
vertices.forEach(function(xy,i){
bounds.extend(xy);
});
infoWindow.setPosition(bounds.getCenter());
drawingManager.setDrawingMode(null);
infoWindow.open(map);
}
This code compiles the vertices into an <ol>, and then adds the area underneath.

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);

Hover on FusionTablesLayer in google maps

I have a FusionTablesLayer on my google map and it works great, but now I have to add a hover to it and I can figure out if it's possible. I've seen examples with a hover on different polygons, but I can't use this.
My layer:
layer = new google.maps.FusionTablesLayer({
map: map,
suppressInfoWindows: true,
heatmap: { enabled: false },
query: {
select: "col0",
from: key,
where: CreateQuery(shownMunicipalities)
},
styles: [{
polygonOptions: {
fillColor: '#eeeeee',
fillOpacity: 0.5,
strokeColor: '#000000',
strokeOpacity: 0.2,
strokeWeight: 2
}
}, {
where: CreateQuery(activeMunicipalities),
polygonOptions: {
fillColor: '#00FF00',
fillOpacity: 0.3
}
}],
options: {
styleId: 2,
templateId: 2
}
});
I've tried add a listener of the mouseover event, but this doesn't seem to do anythin.
google.maps.event.addListener(layer, 'mouseover', function (event) {
alert('hover');
});
Am I trying to do the impossible?
FusionTablesLayers don't support mouseover events, only click events.
(see this enhancement request)
There are implementations that add mouseover support (fusiontips) and this example from the FusionTables documentation.
code snippet (example from documentation):
var colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00'];
var map;
function initialize() {
var myOptions = {
zoom: 2,
center: new google.maps.LatLng(10, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
myOptions);
// Initialize JSONP request
var script = document.createElement('script');
var url = ['https://www.googleapis.com/fusiontables/v1/query?'];
url.push('sql=');
var query = 'SELECT name, kml_4326 FROM ' +
'1foc3xO9DyfSIF6ofvN0kp2bxSfSeKog5FbdWdQ';
var encodedQuery = encodeURIComponent(query);
url.push(encodedQuery);
url.push('&callback=drawMap');
url.push('&key=AIzaSyAm9yWCV7JPCTHCJut8whOjARd7pwROFDQ');
script.src = url.join('');
var body = document.getElementsByTagName('body')[0];
body.appendChild(script);
}
function drawMap(data) {
var rows = data['rows'];
for (var i in rows) {
if (rows[i][0] != 'Antarctica') {
var newCoordinates = [];
var geometries = rows[i][1]['geometries'];
if (geometries) {
for (var j in geometries) {
newCoordinates.push(constructNewCoordinates(geometries[j]));
}
} else {
newCoordinates = constructNewCoordinates(rows[i][1]['geometry']);
}
var randomnumber = Math.floor(Math.random() * 4);
var country = new google.maps.Polygon({
paths: newCoordinates,
strokeColor: colors[randomnumber],
strokeOpacity: 0,
strokeWeight: 1,
fillColor: colors[randomnumber],
fillOpacity: 0.3
});
google.maps.event.addListener(country, 'mouseover', function() {
this.setOptions({
fillOpacity: 1
});
});
google.maps.event.addListener(country, 'mouseout', function() {
this.setOptions({
fillOpacity: 0.3
});
});
country.setMap(map);
}
}
}
function constructNewCoordinates(polygon) {
var newCoordinates = [];
var coordinates = polygon['coordinates'][0];
for (var i in coordinates) {
newCoordinates.push(
new google.maps.LatLng(coordinates[i][1], coordinates[i][0]));
}
return newCoordinates;
}
google.maps.event.addDomListener(window, 'load', initialize);
#map-canvas {
height: 500px;
width: 600px;
}
<script src="https://maps.google.com/maps/api/js"></script>
<div id="map-canvas"></div>