Related
I am creating a google map for hiking. Each individual hike is displayed by a polyline. Each individual hike also has a start location and end location (at either end of the polyline). The start and end locations are each displayed by a marker (NOT a symbol). I have spent hours trying to add functionality such that when there is a mouseover event over EITHER the polyline OR either of the markers then both the polyline and both markers will "react" (in this case the opacity will change).
I have spent hours trying to find the solution. The closest I have got is the code below. In the code below, only if the mouse moves over the polyline will the polyline and markers react. But if the mouse moves over either marker, the polyline and markers do not react. I do understand my code is incorrect, but I cannot get closer to the solution.
I guess I somehow need to "group" each polyline and the respective 2 markers to one "object", "variable" or "layer" - but I simply cannot work this out.
Please note, the code below is simplified for only one marker (start location) per polyline (hike).
(At top of the code below is the gpx file from which the polyline and markers are created. Copy the gpx data into file and name google.gpx)
//start of the trimmed gpx data. Copy to new file and save as google.gpx
<lines>
<trkseg>
<trkpt lat="-33.879843" lng="151.225769"/>
<trkpt lat="-33.869843" lng="151.245769"/>
<trkpt lat="-33.859843" lng="151.255769"/>
</trkseg>
<trkseg>
<trkpt lat="-33.869843" lng="151.265769"/>
<trkpt lat="-33.869843" lng="151.275769"/>
</trkseg>
</lines>
//end of the trimmed gpx data
<style>
#map {
height: 100%;
}
</style>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(-33.863276, 151.207977),
zoom: 12
});
downloadUrl('google.gpx', function(data) {
var xml = data.responseXML;
var trkseg = xml.querySelectorAll("trkseg");
for (var l = 0; l < trkseg.length; l++) {
var path = [],
trkPoints = trkseg[l].querySelectorAll('trkpt');
for (var p = 0; p < trkPoints.length; p++) {
var trkpt = trkPoints[p],
lat = parseFloat(trkpt.getAttribute("lat")),
lng = parseFloat(trkpt.getAttribute("lng")),
point = new google.maps.LatLng(lat, lng);
path.push(point);
}
var trkptMarker = trkPoints[0];
var startMarkerLat = parseFloat(trkptMarker.getAttribute("lat"));
var startMarkerLng = parseFloat(trkptMarker.getAttribute("lng"));
var startMarkerLatLng = {lat: startMarkerLat, lng: startMarkerLng};
var startIcon = 'https://stunninghikes.com/wp-content/uploads/2018/08/hike_start_pin_circular-e1534182115238.png';
var startIconImage = new google.maps.MarkerImage(startIcon);
var polyline = new google.maps.Polyline({
path: path,
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2,
startMarker: new google.maps.Marker({
position: startMarkerLatLng,
map: map,
opacity: 0.5,
icon: startIconImage,
zIndex: 10
}),
});
polyline.setMap(map);
google.maps.event.addListener(polyline, 'mouseover', function(event) {
this.get('startMarker').setOptions({
opacity: 1.0,
});
this.setOptions({
strokeColor: '#128934',
strokeOpacity: 1,
strokeWeight: 5,
});
});
google.maps.event.addListener(polyline, 'mouseout', function(event) {
this.get('startMarker').setOptions({
opacity: 0.5,
});
this.setOptions({
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2
});
});
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=GOOGLEKEY&&callback=initMap">
</script>
The simplest option given your existing code is to add the equivalent mouseover/mouseout listeners to the marker:
var startMarker = new google.maps.Marker({
position: startMarkerLatLng,
map: map,
opacity: 0.5,
icon: startIconImage,
zIndex: 10
});
var polyline = new google.maps.Polyline({
path: path,
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2,
map: map,
startMarker: startMarker
});
startMarker.set("polyline", polyline);
google.maps.event.addListener(polyline, 'mouseover', function(event) {
this.get('startMarker').setOptions({
opacity: 1.0,
});
this.setOptions({
strokeColor: '#128934',
strokeOpacity: 1,
strokeWeight: 5,
});
});
google.maps.event.addListener(polyline, 'mouseout', function(event) {
this.get('startMarker').setOptions({
opacity: 0.5,
});
this.setOptions({
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2
});
});
google.maps.event.addListener(startMarker, 'mouseover', function(event) {
this.setOptions({
opacity: 1.0,
});
this.get("polyline").setOptions({
strokeColor: '#128934',
strokeOpacity: 1,
strokeWeight: 5,
});
});
google.maps.event.addListener(startMarker, 'mouseout', function(event) {
this.setOptions({
opacity: 0.5,
});
this.get("polyline").setOptions({
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2
});
});
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: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
var xml = parseXml(xmlStr);
var trkseg = xml.querySelectorAll("trkseg");
for (var l = 0; l < trkseg.length; l++) {
var path = [],
trkPoints = trkseg[l].querySelectorAll('trkpt');
for (var p = 0; p < trkPoints.length; p++) {
var trkpt = trkPoints[p],
lat = parseFloat(trkpt.getAttribute("lat")),
lng = parseFloat(trkpt.getAttribute("lng")),
point = new google.maps.LatLng(lat, lng);
path.push(point);
bounds.extend(point);
}
var trkptMarker = trkPoints[0];
var startMarkerLat = parseFloat(trkptMarker.getAttribute("lat"));
var startMarkerLng = parseFloat(trkptMarker.getAttribute("lng"));
var startMarkerLatLng = {
lat: startMarkerLat,
lng: startMarkerLng
};
var startIcon = 'https://stunninghikes.com/wp-content/uploads/2018/08/hike_start_pin_circular-e1534182115238.png';
var startIconImage = new google.maps.MarkerImage(startIcon);
var startMarker = new google.maps.Marker({
position: startMarkerLatLng,
map: map,
opacity: 0.5,
icon: startIconImage,
zIndex: 10
});
var polyline = new google.maps.Polyline({
path: path,
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2,
map: map,
startMarker: startMarker
});
startMarker.set("polyline", polyline);
google.maps.event.addListener(polyline, 'mouseover', function(event) {
this.get('startMarker').setOptions({
opacity: 1.0,
});
this.setOptions({
strokeColor: '#128934',
strokeOpacity: 1,
strokeWeight: 5,
});
});
google.maps.event.addListener(polyline, 'mouseout', function(event) {
this.get('startMarker').setOptions({
opacity: 0.5,
});
this.setOptions({
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2
});
});
google.maps.event.addListener(startMarker, 'mouseover', function(event) {
this.setOptions({
opacity: 1.0,
});
this.get("polyline").setOptions({
strokeColor: '#128934',
strokeOpacity: 1,
strokeWeight: 5,
});
});
google.maps.event.addListener(startMarker, 'mouseout', function(event) {
this.setOptions({
opacity: 0.5,
});
this.get("polyline").setOptions({
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2
});
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('MicrosoftXMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
}
var xmlStr = '<lines><trkseg><trkpt lat="-33.879843" lng="151.225769"/><trkpt lat="-33.869843" lng="151.245769"/><trkpt lat="-33.859843" lng="151.255769"/></trkseg><trkseg><trkpt lat="-33.869843" lng="151.265769"/><trkpt lat="-33.869843" lng="151.275769"/></trkseg></lines>';
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>
I'm plotting a polyline on Google Maps API V3, from a GPX file.
On mouseover of that polyline, I have an animated dot, moving along the polyline, using function animateRoute();
Currently however, I don't have a way to remove the animated dot on mouseout, and as a result, if you mouseover, mouseout, mouseover etc, you end up with multiple animated dots moving along the same line.
Code snippet: (see full working URL below too)
var gmarkers = [];
function loadGPXFileIntoGoogleMap(map, filename,recordNum, name, hex_code) {
$.ajax({
type: "GET",
url: filename,
dataType: "xml",
success: function(xml) {
var points = [];
var bounds = new google.maps.LatLngBounds ();
$(xml).find("trkpt").each(function() {
var lat = $(this).attr("lat");
var lon = $(this).attr("lon");
if((lat != 0) && (lon != 0))
{
var p = new google.maps.LatLng(lat, lon);
points.push(p);
bounds.extend(p);
}
});
var strokeColor = "#ff0000";
var poly = new google.maps.Polyline({
path: points,
strokeColor: strokeColor,
strokeOpacity: 1,
strokeWeight: 4,
recordNum: recordNum,
});
poly.setMap(map);
google.maps.event.addListener(poly, 'mouseover', function() {
var start = {
path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
fillColor: '#00ff00',
fillOpacity: 1,
strokeColor:'#000000',
strokeWeight: 4,
scale: 0.5
}
var end = {
path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
fillColor: '#FF0000',
fillOpacity: 1,
strokeColor:'#000000',
strokeWeight: 4,
scale: 0.5
}
var markerStart = new google.maps.Marker({
position: poly.getPath().getAt(0),
icon: start,
map: map,
zIndex: 200,
scale: 1
});
gmarkers.push(markerStart);
var markerEnd = new google.maps.Marker({
position: poly.getPath().getAt(poly.getPath().getLength() - 1),
icon: end,
map: map,
zIndex: 200,
scale: 1
});
gmarkers.push(markerEnd);
var icons = this.setOptions({
icons: [{
icon: {
path: google.maps.SymbolPath.CIRCLE,
strokeOpacity: 1,
strokeColor: "#000000",
strokeWeight: 2,
scale: 4
},
}]});
animateRoute(poly);
});
function animateRoute(line) {
var count = 0;
window.setInterval(function() {
count = (count + 1) % 200;
var icons = poly.get('icons');
icons[0].offset = (count / 2) + '%';
poly.set('icons', icons);
}, 60);
}
google.maps.event.addListener(poly, 'mouseout', function() {
removeMarkers();
});
// fit bounds to track
map.fitBounds(bounds);
}
});
}
function removeMarkers(){
for(i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
$(document).ready(function() {
var mapOptions = {
zoom: 17,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
loadGPXFileIntoGoogleMap(map, "cmsAdmin/uploads/blue_and_green_not_comfortable_.gpx","724","Example A","FFFF00");
loadGPXFileIntoGoogleMap(map, "cmsAdmin/uploads/taraweratrailrouterecce.gpx","431","Example B","4F4CBE");
});
Full working example:
https://www.wildthings.club/mapStack.php
Hover over the blue line and you'll see the animated dot.
Mouse off, and then after a few seconds hover again - a second dot will appear, and the first dot is still going.
Repeat and you'll soon have a bunch of jittery dots.
Ideally I'd like to remove all animated dots on mouseout.
Second option would be to not add a subsequent animated dot icon if there is already one on that polyLine (note there are multiple polyLines on the map).
Third option failing that would be to have the animated dot stop and remove once it reaches the end (position markerEnd) so at least it doesn't loop.
I have tried placing the icons into an array and then removing from there (like I have done with the gmarkers array and removeMarkers(), but no luck.
I also had a play with Animate google maps polyline but this just works with straight line point to point, rather than following a series of points from a GPX file.
Any help, most appreciated
Cheers
You should use the window.clearInterval() function to remove the interval you are using to animate the icon on the polyline. You should save the id when call window.setInterval() in animateRoute(). Here is a simple JSBin proof of concept adapted from the code on that website. In my code, I'm just simply using a global id variable, and updating that variable in animateRoute():
<!DOCTYPE html>
<html>
<head>
<title>Polyline path</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map {
height: 100%;
width: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var map;
var id;
var gmarkers = [];
var gmarkersicons = [];
function initMap() {
var mapOptions = {
zoom: 3,
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: {lat: 9.291, lng: -157.821}
};
map = new google.maps.Map(document.getElementById("map"),
mapOptions);
var points = [
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var poly = new google.maps.Polyline({
path: points,
strokeColor: "red",
strokeOpacity: 1,
strokeWeight: 4,
recordNum: "test"
});
poly.setMap(map);
google.maps.event.addListener(poly, 'mouseover', function() {
var start = {
path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
fillColor: '#00ff00',
fillOpacity: 1,
strokeColor:'#000000',
strokeWeight: 4,
scale: 0.5
}
var end = {
path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
fillColor: '#FF0000',
fillOpacity: 1,
strokeColor:'#000000',
strokeWeight: 4,
scale: 0.5
}
var go = {
path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
fillColor: '#000000',
fillOpacity: 1,
strokeColor:'#fff',
strokeWeight: 4,
scale: 0.5
}
var markerStart = new google.maps.Marker({
position: poly.getPath().getAt(0),
icon: start,
map: map,
zIndex: 200,
scale: 1
});
gmarkers.push(markerStart);
var markerEnd = new google.maps.Marker({
position: poly.getPath().getAt(poly.getPath().getLength() - 1),
icon: end,
map: map,
zIndex: 200,
scale: 1
});
gmarkers.push(markerEnd);
var icons = this.setOptions({
icons: [{
icon: {
path: google.maps.SymbolPath.CIRCLE,
strokeOpacity: 1,
strokeColor: "#000000",
strokeWeight: 2,
scale: 4
},
}]});
this.setOptions({
strokeColor: "red",
scale: 1,
strokeWeight:15,
strokeOpacity:.6
});
var contentString = "Testing";
var infowindow = new google.maps.InfoWindow({
content: contentString
});
infowindow.open(map, markerStart);
id = animateRoute(poly);
});
function animateRoute(line) {
var count = 0;
var id = window.setInterval(function() {
count = (count + 1) % 200;
var icons = poly.get('icons');
icons[0].offset = (count / 2) + '%';
poly.set('icons', icons);
}, 60);
return id;
}
google.maps.event.addListener(poly, 'mouseout', function() {
removeMarkers();
this.setOptions({strokeColor:"red",strokeWeight:4,strokeOpacity:1});
this.setOptions( { suppressMarkers: true } );
this.setOptions({
icons: [{}]});
window.clearInterval(id);
});
function removeMarkers(){
for(i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}
}
$(document).ready(function() {
initMap();
});
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
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/
Trying to figure out how to "attach" an InfoBox" to the left edge of a circle drawn in Google Maps (v3).
Here's what I have so far:
http://jsfiddle.net/a1aq9ey8/6/
If you zoom in/out of the map, you'll notice that the InfoBox (8 MILE) position no longer left aligns with the circle... I'd like the infoBox to stay left aligned to the left/centered edge of the circle when the user zooms in or out... Is this possible?
$(document).ready(function(){
//set your google maps parameters
var map;
var bblocation = new google.maps.LatLng(37.787321,-122.258365);
var map_zoom = 11;
//set google map options
var map_options = {
center: bblocation,
zoom: map_zoom,
panControl: false,
zoomControl: true,
mapTypeControl: false,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
disableDefaultUI: true,
}
//inizialize the map
map = new google.maps.Map(document.getElementById('google-container'), map_options);
var radiusOptions = {
strokeColor:"#222c38",
strokeOpacity:1,
strokeWeight:1,
fillColor:"#ffffff",
fillOpacity:0,
map: map,
center: bblocation,
radius: 12872
};
markerCircles = new google.maps.Circle(radiusOptions);
var labelText = "8 MILE";
var myOptions = {
content: labelText,
boxStyle: {
background: '#222c38',
color: '#ffffff',
textAlign: "center",
fontSize: "8pt",
width: "50px"
},
disableAutoPan: true,
pixelOffset: new google.maps.Size(-45, 0),
position: new google.maps.LatLng(37.787321,-122.374365),
closeBoxURL: "",
isHidden: false,
pane: "mapPane",
enableEventPropagation: true
};
var mmLabel = new InfoBox(myOptions);
mmLabel.open(map);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
});
You need to calculate the position of the label to put it on the circle. Using the geometry library computeOffset method.
distance = radius of the circle
heading = -90 degrees (west)
fromLatLng = center of the circle
var radiusOptions = {
strokeColor:"#222c38",
strokeOpacity:1,
strokeWeight:1,
fillColor:"#ffffff",
fillOpacity:0,
map: map,
center: bblocation,
radius: 12872
};
markerCircles = new google.maps.Circle(radiusOptions);
// calculate the position of the label
var labelPosn = google.maps.geometry.spherical.computeOffset(radiusOptions.center,radiusOptions.radius,-90);
var labelText = "8 MILE";
var myOptions = {
content: labelText,
boxStyle: {
background: '#222c38',
color: '#ffffff',
textAlign: "center",
fontSize: "8pt",
width: "50px"
},
disableAutoPan: true,
pixelOffset: new google.maps.Size(0, 0), // left upper corner of the label
position: labelPosn, // on the left edge of the circle
closeBoxURL: "",
isHidden: false,
pane: "mapPane",
enableEventPropagation: true
};
updated fiddle
code snippet:
$(document).ready(function() {
//set your google maps parameters
var map;
var bblocation = new google.maps.LatLng(37.787321, -122.258365);
var map_zoom = 11;
//set google map options
var map_options = {
center: bblocation,
zoom: map_zoom,
panControl: false,
zoomControl: true,
mapTypeControl: false,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
disableDefaultUI: true,
}
//inizialize the map
map = new google.maps.Map(document.getElementById('google-container'), map_options);
var radiusOptions = {
strokeColor: "#222c38",
strokeOpacity: 1,
strokeWeight: 1,
fillColor: "#ffffff",
fillOpacity: 0,
map: map,
center: bblocation,
radius: 12872
};
markerCircles = new google.maps.Circle(radiusOptions);
// calculate the position of the label
var labelPosn = google.maps.geometry.spherical.computeOffset(radiusOptions.center, radiusOptions.radius, -90);
var labelText = "8 MILE";
var myOptions = {
content: labelText,
boxStyle: {
background: '#222c38',
color: '#ffffff',
textAlign: "center",
fontSize: "8pt",
width: "50px"
},
disableAutoPan: true,
pixelOffset: new google.maps.Size(0, 0), // left upper corner of the label
position: labelPosn, // on the left edge of the circle
closeBoxURL: "",
isHidden: false,
pane: "mapPane",
enableEventPropagation: true
};
var mmLabel = new InfoBox(myOptions);
mmLabel.open(map);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
});
html,
body,
#google-container {
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=geometry"></script>
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/infobox/src/infobox.js"></script>
<div id="google-container"></div>
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>