Chart js - avoid overlapping of tooltips in pie chart - charts

I've used chart js library for make pie chart. I want to display tooltips always. I've done this. I've attached screenshot.
But now the tooltips are overlapped . How to solve this?
This is my code
myPieChart = new Chart(pie_chart).Pie(data_results.comp.pie, {
tooltipTemplate: "<%= value %> %",
scaleFontSize: 14,
scaleFontColor: "#333",
tooltipFillColor: "rgba(0,0,0,0)",
onAnimationComplete: function()
{
this.showTooltip(this.segments, true);
},
tooltipEvents: [],
tooltipFontColor: "#000",
});
I want to change tooltip position if already one present in that position.

Actually to detect overlapping tooltips is very difficult.
I solved it in the end by deactivating the color in the toolbox, reducing the size of the tooltip, moving the tooltip closer to the outer border and hiding all tooltips, which represent less than 2%. Example looks like that:
I used for that the following code:
Chart.Tooltip.positioners.outer = function(elements) {
if (!elements.length) {
return false;
}
var i, len;
var x = 0;
var y = 0;
for (i = 0, len = elements.length; i < len; ++i) {
var el = elements[i];
if (el && el.hasValue()) {
var elPosX = el._view.x+0.95*el._view.outerRadius*Math.cos((el._view.endAngle-el._view.startAngle)/2+el._view.startAngle);
var elPosY = el._view.y+0.95*el._view.outerRadius*Math.sin((el._view.endAngle-el._view.startAngle)/2+el._view.startAngle);
if (x < elPosX) {
x = elPosX;
}
if (y < elPosY) {
y = elPosY;
}
}
}
return {
x: Math.round(x),
y: Math.round(y)
};
},
Chart.pluginService.register({
beforeRender: function (chart) {
if (chart.config.options.showAllTooltips) {
// create an array of tooltips
// we can't use the chart tooltip because there is only one tooltip per chart
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function (dataset, i) {
chart.getDatasetMeta(i).data.forEach(function (sector, j) {
if ((sector._view.endAngle-sector._view.startAngle) > 2*Math.PI*0.02) {
chart.pluginTooltips.push(
new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart)
);
}
});
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: function (chart, easing) {
if (chart.config.options.showAllTooltips) {
// we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
tooltip.initialize();
tooltip._options.position = "outer";
tooltip._options.displayColors = false;
tooltip._options.bodyFontSize = tooltip._chart.height*0.025;
tooltip._options.yPadding = tooltip._options.bodyFontSize*0.30;
tooltip._options.xPadding = tooltip._options.bodyFontSize*0.30;
tooltip._options.caretSize = tooltip._options.bodyFontSize*0.5;
tooltip._options.cornerRadius = tooltip._options.bodyFontSize*0.50;
tooltip.update();
// we don't actually need this since we are not animating tooltips
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
});

Related

Leaflet - Change and revert polygon feature style

I make a little app using leaflet to display information about polygons.
Here's how the code works :
A crosshair is displayed in the center of the screen on top of the map
When map pans, crosshair remains in the center on the screen
When crosshair overlaps a polygon, polygon information is displyed in a div
the purpose of this system is to help polygon selecting on mobile for very small polygons
I came up with the following app : https://www.laurentgontier.com/Crosshair/
I need to be able to change polygon style when it is overlaped by crosshair and revert to default style when crosshair leaves polygon.
so far, I wasn't able to achieve this.
Here's the part of code :
//Geojson layer display
var geojsonLayer = new L.GeoJSON.AJAX("map.geojson",{
onEachFeature: onEachFeature
});
geojsonLayer.addTo(map);
//Crosshair display
var crosshairIcon = L.icon({
iconUrl: 'Cible.png',
iconSize: [30, 30], // size of the icon
iconAnchor: [15, 15], // point of the icon which will correspond to marker's location
});
crosshair = new L.marker(map.getCenter(), {icon: crosshairIcon, clickable:false});
crosshair.addTo(map);
// Move the crosshair to the center of the map when the user pans
map.on('move', function(e) {
crosshair.setLatLng(map.getCenter());
});
// Move the crosshair to the center of the map when the user pans
map.on('moveend', function(e) {
var hasHit = false;
var newCenter = map.getCenter();
geoJsonLayers.forEach(function(layer){
var currLayerFeature = layer.feature;
var layerPlace = currLayerFeature.properties.Place;
var layerCoordinates = currLayerFeature.geometry.coordinates[0]
var xp = [], yp =[];
for(var i = 0; i<layerCoordinates.length; i++){
xp.push(layerCoordinates[i][0]); yp.push(layerCoordinates[i][1]);
}
if(checkPointForHit(xp, yp , newCenter.lng, newCenter.lat)){
displayPlace.innerHTML = layerPlace; hasHit = true}
})
if(!hasHit)displayPlace.innerHTML = 'Not overlaping polygon'
});
function checkPointForHit(xp/*array of xpointsOfPolygon*/, yp /*array of ypointsOfPolygon*/, x, y) {
var i, j, c = 0, npol = xp.length;
for (i = 0, j = npol-1; i < npol; j = i++) {
if ((((yp[i] <= y) && (y < yp[j])) ||
((yp[j] <= y) && (y < yp[i]))) &&
(x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i])) {
c =!c;
}
}
return c;
}
Any idea about that ?
Use the turfjs library and then use booleanContains:
map.on('moveend', function(e) {
var hasHit = false;
geojsonLayer.resetStyle()
geoJsonLayers.forEach(function(layer){
var layerPlace = layer.feature.properties.Place;
if(turf.booleanContains(layer.toGeoJSON(),crosshair.toGeoJSON())){
displayPlace.innerHTML = layerPlace;
hasHit = true;
layer.setStyle({color: 'red'});
}
})
if(!hasHit){
displayPlace.innerHTML = 'Not overlaping polygon';
}
});
When you change the event from moveend to move the color is updated while moveing
Add DOM Script
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://cdn.jsdelivr.net/npm/#turf/turf#5.1.6/turf.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
map.on('move moveend', function(e) {
var hasHit = false;
var newCenter = map.getCenter();
geojsonLayer.resetStyle()
geoJsonLayers.forEach(function(layer){
var layerPlace = layer.feature.properties.Place;
if(turf.booleanContains(layer.toGeoJSON(),crosshair.toGeoJSON())){
displayPlace.innerHTML = layerPlace;
hasHit = true;
layer.setStyle({color: 'red'});
}
})
if(!hasHit){
displayPlace.innerHTML = 'Not overlaping polygon';
}
});

How do you properly configure an event listener/handler for a CategoryFilter control?

I am trying to plot the following sample data using a LineChart with a CategoryFilter to filter on year.
Data table is defined as:
aggData: [Date: date][Team: string][Score: number]
From the aggData table I dynamically calculate the default hAxis ticks as
var hAxisTicks = [];
var dateRange = aggData.getColumnRange(0);
for (var date = dateRange.min; date <= dateRange.max; date = new Date(date.getFullYear(), date.getMonth() + 1)) {
hAxisTicks.push(date);
}
The year picker and the line chart are configured as:
var yearPicker = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'categoryFilter_div',
options: {
filterColumnIndex: 0,
ui: {
allowTyping: false,
allowMultiple: false,
label: 'Year:',
labelStacking: 'vertical'
},
useFormattedValue: true
}
});
var lineChart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart_div',
options: {
width: 900,
height: 500,
hAxis: {
format: 'MMM', ticks: hAxisTicks
}
}
});
I added the following event listener
google.visualization.events.addListener(yearPicker, 'statechange', function () {
google.visualization.events.addOneTimeListener(lineChart, 'ready', getTicks);
});
I need to create/recreate the hAxis ticks everytime the yearPicker changes by calling getTicks
function getTicks() {
var ticks = [];
if (yearPicker.getState().selectedValues.length > 0) {
for (var i = 0; i <= hAxisTicks.length; i = i + 1) {
var date = new Date(hAxisTicks[i]);
if (date.getFullYear() == yearPicker.getState().selectedValues[0]) {
ticks.push(date)
}
}
}
else {
for (var i = 0; i <= hAxisTicks.length; i = i + 1) {
var date = new Date(hAxisTicks[i]);
ticks.push(date);
}
lineChart.setOption('hAxis.ticks', ticks);
lineChart.draw();
}
lineChart.setOption('hAxis.ticks', ticks);
lineChart.draw();
}
Here's what happens at different stages
1- When page first loads the graph looks like (the getTicks function is NOT called) which is correct:
2- When the year is changed to 2019, for example, the hAxis ticks get recalculated (the getTicks function is does get called) and the graph appears to be correct
3- Attempting to go back to the default chart to display all years, an a.getTime is not a function error message appears under the CategoryFilter
4- Any subsequent attempts to change the CategoryFilter to any value throws a ```One or more participants failed to draw()
How can I rectify this behavior?
I realized my iteration over the hAxisTics array was incorrect. I should stop at < hAxisTics.length instead of <= hAxisTics.length and I should recalculate inside the event handler
google.visualization.events.addListener(yearPicker, 'statechange', function () {
var ticks = [];
if (yearPicker.getState().selectedValues.length > 0) {
for (var i = 0; i < hAxisTicks.length; i = i + 1) {
var date = new Date(hAxisTicks[i]);
if (date.getFullYear() == yearPicker.getState().selectedValues[0]) {
ticks.push(date)
}
}
}
else {
for (var i = 0; i < hAxisTicks.length; i = i + 1) {
var date = new Date(hAxisTicks[i]);
ticks.push(date);
}
lineChart.setOption('hAxis.ticks', ticks);
lineChart.draw();
}
lineChart.setOption('hAxis.ticks', ticks);
lineChart.draw();
});

Chart.js click on labels, using bar chart

i need help with my Chart.js interactivity. When I click on the label, I need to return the column(index) number at which I clicked.
I tried to use getElementsAtEvent but it only work if I click directly at chart.
This http://jsfiddle.net/yxz2sjam/ is pretty much what I am looking for but getPointsAtEvent is no longer available in the new versions.
canvas.onclick = function (evt) {
var points = chart.getPointsAtEvent(evt);
alert(chart.datasets[0].points.indexOf(points[0]));
};
I also found this http://jsfiddle.net/1Lngmtz7/ but it isn't working with bar chart.
var ctx = document.getElementById("myChart").getContext("2d");
var myRadarChart = new Chart(ctx, {
type: 'radar',
data: data
})
$('#myChart').click(function (e) {
var helpers = Chart.helpers;
var eventPosition = helpers.getRelativePosition(e, myRadarChart.chart);
var mouseX = eventPosition.x;
var mouseY = eventPosition.y;
var activePoints = [];
helpers.each(myRadarChart.scale.ticks, function (label, index) {
for (var i = this.getValueCount() - 1; i >= 0; i--) {
var pointLabelPosition = this.getPointPosition(i, this.getDistanceFromCenterForValue(this.options.reverse ? this.min : this.max) + 5);
var pointLabelFontSize = helpers.getValueOrDefault(this.options.pointLabels.fontSize, Chart.defaults.global.defaultFontSize);
var pointLabeFontStyle = helpers.getValueOrDefault(this.options.pointLabels.fontStyle, Chart.defaults.global.defaultFontStyle);
var pointLabeFontFamily = helpers.getValueOrDefault(this.options.pointLabels.fontFamily, Chart.defaults.global.defaultFontFamily);
var pointLabeFont = helpers.fontString(pointLabelFontSize, pointLabeFontStyle, pointLabeFontFamily);
ctx.font = pointLabeFont;
var labelsCount = this.pointLabels.length,
halfLabelsCount = this.pointLabels.length / 2,
quarterLabelsCount = halfLabelsCount / 2,
upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount),
exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount);
var width = ctx.measureText(this.pointLabels[i]).width;
var height = pointLabelFontSize;
var x, y;
if (i === 0 || i === halfLabelsCount)
x = pointLabelPosition.x - width / 2;
else if (i < halfLabelsCount)
x = pointLabelPosition.x;
else
x = pointLabelPosition.x - width;
if (exactQuarter)
y = pointLabelPosition.y - height / 2;
else if (upperHalf)
y = pointLabelPosition.y - height;
else
y = pointLabelPosition.y
if ((mouseY >= y && mouseY <= y + height) && (mouseX >= x && mouseX <= x + width))
activePoints.push({ index: i, label: this.pointLabels[i] });
}
}, myRadarChart.scale);
var firstPoint = activePoints[0];
if (firstPoint !== undefined) {
alert(firstPoint.index + ': ' + firstPoint.label);
}
});
Thank for response.
I solve the problem with
document.getElementById("chart").onclick = function(e)
{
var activeElement = weatherMainChart.lastTooltipActive;
console.log(activeElement[0]._index);
};
this solution register clicks on chart and label, then I restricted it with e.layerY to register only clicks on label section.
document.getElementById("chart").onclick = function(e)
{
var activeElement = weatherMainChart.lastTooltipActive;
if(e.layerY > 843 && e.layerY < 866 && activeElement[0] !== undefined)
console.log(activeElement[0]._index);
};
If you add a click handler through the onClick option you can use the following code using the getElementsAtEventForMode() call:
function handleClick(evt) {
var col;
switch(chartType) {
case "horizontalBar":
this.getElementsAtEventForMode(evt, "y", 1).forEach(function(item) { col = item._index });
break;
case "bar":
this.getElementsAtEventForMode(evt, "x", 1).forEach(function(item) { col = item._index });
break;
}
if (!col) {
return;
}
alert("Column " + col + " was selected");
};
You'll probably need to add extra switch checks for other chart types but I'm sure you get the idea.
Using version 2.4.0, i created an onClick Event, and inside it
var activeIndex = localChart.tooltip._lastActive[0]._index;
var clickCoordinates = Chart.helpers.getRelativePosition(e, localChart.chart);
if (clickCoordinates.y >= 530) { //custom value, depends on chart style,size, etc
alert("clicked on " + localChart.data.labels[activeIndex]);
}
I Solved this problem with single or multiple label click you will be find using true/false
First you need to set your chartJs Id click
below code SessionChart = Your ChartJs ID e.g. ("myChart") I was replace it for my Id
document.getElementById("SessionChart").onclick = function (evt) {
var meta = SubscriberSessionChart.getDatasetMeta(0);
if (meta.$filler.chart.legend.legendItems[0].text.toLowerCase() "sessions")
{
if (meta.$filler.chart.legend.legendItems[0].hidden) {
sessionHidden = true;
}
}
}
here "sessions" = first label text
meta.$filler.chart.legend.legendItems[0].text.toLowerCase() = is your first label
from Array so you can get multiple label's click here true / false
if (meta.$filler.chart.legend.legendItems[0].hidden) = your label is not active then
you will get hidden true otherwise you will get false if not tick on label
by default label tick hidden is false in chart js

d3.js : very simple mouse interaction

I wan't to do a very simple chart with mouse interaction.
Example (work in progress) is on this page : http://velo70.ouvaton.org/2013/gpxvtt-un-nouveau-plugin/
The goal is : when you change the slider position, a circle have the same position on the chart. On the map, it's already done :)
The best issue could be : when you move the slide, the circle-chart move, and when you move the circle on the chart, the slide move too... But maybe too hard for me :\
Any link with tutorial to progress with that ?
Thanks.
One way is to bind circles to every data point in your graph and then set the display: none to all but the one that corresponds to your active slider position.
Add the circles after you append path.lineSup:
chart.selectAll("circle.highlightPoint")
.data(data)
.enter()
.append("circle")
.attr("class", "highlightPoint")
.attr("fill", "pink")
.attr("cx", function(d) { return x(d.dist); })
.attr("cy", function(d) { return y(d.ele); })
.attr("display", "none");
Add to your slider function:
d3.selectAll("circle.highlightPoint")
.attr("display", function(d,i) { return i == id ? "block" : "none"});
I think that should work.
Thanks. Good and pedagogic way for me :)
I finally test with
chart.append("circle")
.data(data)
.attr("class", "highlightPoint")
.attr("r",4)
.attr("innerRadius",0)
.style("fill", "pink")
.style("stroke","blue")
.style("stroke-width",1)
.attr("cx", function(d) { return x(d.dist); })
.attr("cy", function(d) { return y(d.ele); })
.attr("display","block") ;
But it display only the first circle.
I don't really understand the function(d) and function(d,i) use :\
Test in http://velo70.ouvaton.org/2013/gpxvtt-un-nouveau-plugin/
It's a little late.. but i need participation points.. :)
For simple handle click mouse and call function on event, I give you a complete file to link with simple function for d3.js..
<script src="js/file.js"></script>
And "THE" File to include ( mainly analyse it for 'on') :
$(function() {
// Handler for .ready() called.
var data = [],
width = 300,
height = 300,
// An array to hold the coordinates
// of the line drawn on each svg.
coords = [],
line = d3.svg.line(),
// Set the behavior for each part
// of the drag.
drag = d3.behavior.drag()
.on("dragstart", function() {
// Empty the coords array.
coords = [];
svg = d3.select(this);
// If a selection line already exists,
// remove it.
//svg.select(".selection").remove();
// Add a new selection line.
svg.append("path").attr({"class": "selection"});
})
.on("drag", function() {
// Store the mouse's current position
coords.push(d3.mouse(this));
svg = d3.select(this);
// Change the path of the selection line
// to represent the area where the mouse
// has been dragged.
svg.select(".selection").attr({
d: line(coords)
});
// Figure out which dots are inside the
// drawn path and highlight them.
selected = [];
svg.selectAll("circle.dot").each(function(d, i) {
point = [d3.select(this).attr("cx"), d3.select(this).attr("cy")];
if (pointInPolygon(point, coords)) {
selected.push(d.id);
}
});
highlight(selected);
})
.on("dragend", function() {
svg = d3.select(this);
// If the user clicks without having
// drawn a path, remove any paths
// that were drawn previously.
if (coords.length === 0) {
// d3.selectAll("svg path").remove();
unhighlight();
return;
}
// Draw a path between the first point
// and the last point, to close the path.
svg.append("line").attr({
"class": "terminator",
d: line([coords[0], coords[coords.length-1]])
});
});
function randomPoint() {
return Math.floor(Math.random()*(width-30)) + 20;
}
// from https://github.com/substack/point-in-polygon
function pointInPolygon (point, vs) {
var xi, xj, i, intersect,
x = point[0],
y = point[1],
inside = false;
for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
xi = vs[i][0],
yi = vs[i][1],
xj = vs[j][0],
yj = vs[j][1],
intersect = ((yi > y) != (yj > y))
&& (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
}
function unhighlight() {
d3.selectAll("circle.dot").classed("highlighted", false);
}
function highlight(ids) {
// First unhighlight all the circles.
unhighlight();
// Find the circles that have an id
// in the array of ids given, and
// highlight those.
d3.selectAll("circle.dot").filter(function(d, i) {
return ids.indexOf(d.id) > -1;
})
.classed("highlighted", true);
}
function Scatter(data, selector, group) {
var svg = d3.select(selector).append("svg")
.attr({
width: width,
height: height
}).call(drag),
g = svg.append("g").attr({"class": "g-dot"}),
// Create a circle element for each
// item in the data passed.
dot = g.selectAll("circle.dot")
.data(data)
.enter().append("circle")
.attr({
"class": "dot",
r: 8,
cx: function(d, i) {
return d[group].x;
},
cy: function(d, i) {
return d[group].y;
},
})
.on("mouseover", function(d, i) {
// Highlight circles on mouseover, but
// only if a path hasn't been drawn.
if (d3.selectAll("svg path").empty()) {
highlight([d.id]);
}
})
.on("mouseout", function(d, i) {
// If a path hasn't been drawn,
// unhighlight the highlighted circles.
if (d3.selectAll("svg path").empty()) {
unhighlight();
}
});
text = g.selectAll("text")
.data(data)
.enter().append("text")
.attr({
x: function(d, i) {
return d[group].x;
},
y: function(d, i) {
return d[group].y + 4;
}
})
.text(function(d, i) {
return d.id;
});
}
// Add the dots to each canvas div.
Scatter(data, "#tableau_principal", "a");
Scatter(data, "#canvas2", "b");
Scatter(data, "#canvas3", "c");
}); // // FIN DOC READY //
// functions generales used partt //

Integrating / adding Google Earth View to my map

I am creating an interactive map for a non profit association "Friends of Knox Mountain Park" but I am getting trouble with the Google Earth view.
I've been searching on the web for weeks and none of the solutions I found works for me. Can someone take a look of the code and let me know what I should do to include Google Earth View in the map? Thanks in advance.
The online project: http://www.virtualbc.ca/knoxmountain/
And this is the javascript file (mapa2.js) containing the google map's code:
google.load('earth', '1');
var map;
var googleEarth;
var gmarkers = [];
var iconShadow = new google.maps.MarkerImage('icons/shadow.png',
new google.maps.Size(46, 42),
new google.maps.Point(0,0),
new google.maps.Point(13, 42));
var sites = [
['Apex Trail - Shelter',49.91174271, -119.48507050, 4, '<img src="images/apex_point_high.jpg">','magenta','14'],
['Apex Trail',49.91286999, -119.48413424, 3, '<img src="images/apex_point_low.jpg">','lemon','1'],
['Gordon Trail',49.91971281, -119.47954356, 2, '<img src="images/apex_point_low.jpg">','lemon','1'],
['Paul Tomb Bay',49.92555541, -119.47710250, 1, '<img src="images/tomb_bay.jpg">','lemon','1']
];
var infowindow = null;
var overlay;
// Used to make Google Map quard coords to MapCruncher/BingMaps quard coords
function TileToQuadKey ( x, y, zoom)
{
var quad = "";
for (var i = zoom; i > 0; i--)
{
var mask = 1 << (i - 1);
var cell = 0;
if ((x & mask) != 0)
cell++;
if ((y & mask) != 0)
cell += 2;
quad += cell;
}
return quad;
}
function init() {
var centerMap = new google.maps.LatLng(49.909671, -119.482241);
var myOptions = {
zoom: 10,
center: centerMap,
mapTypeId: google.maps.MapTypeId.SATELLITE
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Create the tile layers
// ASTER Tile Layer
myASTEROptions = {
getTileUrl : function (a,b) {
return "http://www.virtualbc.ca/knoxmountain/map/" + TileToQuadKey(a.x,a.y,b) + ".png";
},
isPng: true,
opacity: 1.0,
tileSize: new google.maps.Size(256,256),
name: "ASTER",
minZoom:13,
maxZoom:20
}
ASTERMapType = new google.maps.ImageMapType( myASTEROptions );
map.overlayMapTypes.insertAt(0, ASTERMapType);
// Aerial Tile Layer
myAerialOptions = {
getTileUrl : function (a,b) {
return "http://www.virtualbc.ca/knoxmountain/map/" + TileToQuadKey(a.x,a.y,b) + ".png";
},
isPng: true,
opacity: 1.0,
tileSize: new google.maps.Size(256,256),
name: "Aerial",
minZoom:15,
maxZoom:21
}
AerialMapType = new google.maps.ImageMapType( myAerialOptions );
map.overlayMapTypes.insertAt(1, AerialMapType);
var panorama = new google.maps.StreetViewPanorama(map.getDiv());
panorama.setVisible(false);
panorama.set('enableCloseButton', true);
map.setStreetView(panorama);
panorama.setPosition(centerMap);
setMarkers(map, sites);
setZoom(map, sites);
infowindow = new google.maps.InfoWindow({
content: "Loading..."
});
googleEarth = new GoogleEarth(map);
google.maps.event.addListenerOnce(map, 'tilesloaded', addOverlays);
}
/*
This functions sets the markers (array)
*/
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var site = markers[i];
var siteLatLng = new google.maps.LatLng(site[1], site[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: site[0],
zIndex: site[3],
html: site[4],
// Markers drop on the map
animation: google.maps.Animation.DROP,
icon: 'http://www.virtualbc.ca/knoxmountain/icons/icon.png',
shadow: iconShadow
});
gmarkers.push(marker);
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
/*
Set the zoom to fit comfortably all the markers in the map
*/
function setZoom(map, markers) {
var boundbox = new google.maps.LatLngBounds();
for ( var i = 0; i < markers.length; i++ )
{
boundbox.extend(new google.maps.LatLng(markers[i][1], markers[i][2]));
}
map.setCenter(boundbox.getCenter());
map.fitBounds(boundbox);
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i-1], "click");
}
google.maps.event.addDomListener(window, 'load', init);
The first issue I notice with your site is you are linking to http://www.virtualbc.ca/src/googleearth-compiled.js which does not exist.