Google corechart map not showing anymore - javascript

I have a map that is drawn by coordinates.
It was working 3 days ago but now it's not showing.
code:
google.load("visualization", "1", {packages:["corechart"]});
error:
jsapi:22 A Parser-blocking, cross-origin script,
https://www.google.com/uds/?file=visualization&v=1&packages=corechart,
is invoked via document.write. This may be blocked by the browser if
the device has poor network connectivity.google.loader.f # jsapi:22
2jsapi:22 A Parser-blocking, cross-origin script,
https://www.google.com/uds/api/visualization/1.0/1195ca6324d5ce101c2f520f3c62c843/format+pt_PT,default+pt_PT,ui+pt_PT,corechart+pt_PT.I.js,
is invoked via document.write. This may be blocked by the browser if
the device has poor network connectivity.
I tryed to change to:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
google.charts.load('current', {'packages':['corechart', 'map']});
google.charts.setOnLoadCallback(CarregaMapa("map-geral","eda",continente,7,-1,"#FFF",1000,600));
and i get the error:
loader.js:152 Uncaught TypeError: a.shift(...) is not a function(…)
Update:
I change to
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
google.charts.load('current', {'packages':['corechart', 'map']});
MapaConcelhos.map = new google.visualization.Map(document.getElementById(mapa), {
scrollwheel: false,
draggable: isDraggable,
disableDoubleClickZoom: true,
disableDefaultUI: true,
center: local,
mapTypeId: "",
backgroundColor: bk,
zoom: zoomlocal
});
but I have to add a polygon to the map:
var concelho = new google.maps.Polygon({
paths: coords,
idc: idconcelho,
strokeColor: "black",
strokeOpacity: 0.3,
strokeWeight: 1,
fillColor: item.Cor ? item.Cor : "white",
fillOpacity: 0.8,
html: contentString
});
concelho.setMap(MapaConcelhos.map);
so the error is:
setMap: not an instance of Map
Is it possible to add polygon to a visualization map?
Why can't I use the old code? Why jsapi is having warnings and the map and polygons are not drawn anymore?
Old code:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
google.load("visualization", "1", {packages:["corechart"]})
var MapaConcelhos = CarregaMapa("map-geral","eda",continente,7,-1,"#FFF",1000,600);
var mapbounds = new google.maps.LatLngBounds();
var centromapa = new google.maps.LatLng();
var isDraggable = !('ontouchstart' in document.documentElement);
var longpress = false;
function CarregaMapa(mapa,mapatipo,local,zoomlocal,idd, bk,w,h) {
var MapaConcelhos = {
concelhos: [],
addlegenda: function(item) {
var leg = {
ordem: item.Legenda_key,
cor: item.Cor,
label: item.Label
}
Array.prototype.inArray = function(comparer) {
for(var i=0; i < this.length; i++) {
if(comparer(this[i])) return true;
}
return false;
};
Array.prototype.sortOn = function(key){
this.sort(function(a, b){
if(a[key] < b[key]){
return -1;
}else if(a[key] > b[key]){
return 1;
}
return 0;
});
}
Array.prototype.pushIfNotExist = function(element, comparer) {
if (!this.inArray(comparer)) {
Mapalegenda.push(element);
Mapalegenda.sortOn("ordem")
var legenda="<p><b>Legenda:</b></p>";
for (var i=0; i<Mapalegenda.length; i++) {
legenda = legenda +'<div id="map-legenda-linha"><div id="map-legenda-cor" style="background: ' + Mapalegenda[i].cor + ';"></div>' + Mapalegenda[i].label + '</div>';
}
document.getElementById("map-legenda").innerHTML = legenda;
}
};
Mapalegenda.pushIfNotExist(leg, function(e) {
return e.cor === leg.cor && e.label === leg.label;
});
},
addConcelho: function(item) {
//Set concelho coordenadas
var coords = [];
var coord = item.Coordenadas.split("|");
for (var i = 0; i < coord.length; i++) {
var latlng = coord[i].split(",");
coords.push(new google.maps.LatLng(latlng[1], latlng[0]));
}
var contentString="<b>"+item.Nome+"</b>"+item.Descricao;
//Create polygon
var idconcelho=item.Id;
var concelho = new google.maps.Polygon({
paths: coords,
idc: idconcelho,
strokeColor: "black",
strokeOpacity: 0.3,
strokeWeight: 1,
fillColor: item.Cor ? item.Cor : "white",
fillOpacity: 0.8,
html: contentString
});
MapaConcelhos.concelhos.push(concelho);
concelho.setMap(MapaConcelhos.map);
var bounds = new google.maps.LatLngBounds();
for (var i=0; i< coords.length; i++) {
bounds.extend(coords[i]);
mapbounds.extend(coords[i]);
}
var centroconcelho = bounds.getCenter();
var timer = null;
if (isDraggable)
{
google.maps.event.addListener(concelho,"click",function(){
showConcelho(concelho.idc);});
}
else
{
google.maps.event.addListener(concelho, 'mousedown', function(event){
start = new Date().getTime();
});
google.maps.event.addListener(concelho, 'mouseup', function(){
end = new Date().getTime();
longpress = (end - start < 300) ? false : true;
if (longpress) showConcelho(concelho.idc);
});
}//else
MapaConcelhos.addlegenda(item);
if (item.Ultimo=="1")
{
MapaConcelhos.map.fitBounds(mapbounds);
MapaConcelhos.map.setCenter(local);
}
function isInfoWindowOpen(infoWindow){
var map = infoWindow.getMap();
return (map !== null && typeof map !== "undefined");
}
var minZoom=8;
if (idd==41 || idd==-1) minZoom=7;
google.maps.event.addListenerOnce(MapaConcelhos.map, 'bounds_changed', function(event) {
if (this.getZoom() < minZoom) {
this.setZoom(minZoom);
MapaConcelhos.map.setCenter(local);
}
});
function showArrays(event) {
var vertices = this.getPath();
var contentString =this.html;
infoWindow.setContent(contentString);
infoWindow.setPosition(event.latLng);
infoWindow.open(MapaConcelhos.map);
}
function showConcelho(idc) {
$.fancybox({
href : "/ficha.php?id="+idc,
width : w,
height : h,
fitToView : true,
autoSize : false,
type: "iframe",
padding: 0,
openEffect : "elastic",
openSpeed : 150,
aspectRatio : true,
closeEffect : "elastic",
closeSpeed : 150,
closeClick : true,
scrolling : "auto",
preload : true
});
}
},
map: undefined,
mapContainer: document.getElementById(mapa),
initialize: function() {
google.maps.visualRefresh = true;
MapaConcelhos.map = new google.maps.Map(document.getElementById(mapa), {
scrollwheel: false,
draggable: isDraggable,
disableDoubleClickZoom: true,
disableDefaultUI: true,
center: local,
mapTypeId: "",
backgroundColor: bk,
zoom: zoomlocal
});
}
};
var requester = {};
requester.Request = function () {
$.ajax({
url: "/scripts/concelhos.php",
type: "GET",
data: { tipo: mapatipo, distrito:idd},
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-1",
dataType: "json",
}).done(function(result) {
if (result) {
$.each(result, function(index, item) {
MapaConcelhos.addConcelho(item);
});
} else {
}
}).error(function() {
});
};
MapaConcelhos.initialize();
requester.Request();
return MapaConcelhos;
} //CarregaMapa
New code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
google.charts.load('current', {
'callback': function () {
var MapaConcelhos = CarregaMapa("map-geral","eda",continente,7,-1,"#FFF",1000,600);
},
'packages': ['corechart', 'map']
});
var mapbounds = new google.maps.LatLngBounds();
var centromapa = new google.maps.LatLng();
var isDraggable = !('ontouchstart' in document.documentElement);
var longpress = false;
function CarregaMapa(mapa,mapatipo,local,zoomlocal,idd, bk,w,h) {
var MapaConcelhos = {
concelhos: [],
addlegenda: function(item) {
var leg = {
ordem: item.Legenda_key,
cor: item.Cor,
label: item.Label
}
Array.prototype.inArray = function(comparer) {
for(var i=0; i < this.length; i++) {
if(comparer(this[i])) return true;
}
return false;
};
Array.prototype.sortOn = function(key){
this.sort(function(a, b){
if(a[key] < b[key]){
return -1;
}else if(a[key] > b[key]){
return 1;
}
return 0;
});
}
Array.prototype.pushIfNotExist = function(element, comparer) {
if (!this.inArray(comparer)) {
Mapalegenda.push(element);
Mapalegenda.sortOn("ordem")
var legenda="<p><b>Legenda:</b></p>";
for (var i=0; i<Mapalegenda.length; i++) {
legenda = legenda +'<div id="map-legenda-linha"><div id="map-legenda-cor" style="background: ' + Mapalegenda[i].cor + ';"></div>' + Mapalegenda[i].label + '</div>';
}
document.getElementById("map-legenda").innerHTML = legenda;
}
};
Mapalegenda.pushIfNotExist(leg, function(e) {
return e.cor === leg.cor && e.label === leg.label;
});
},
addConcelho: function(item) {
//Set concelho coordenadas
var coords = [];
var coord = item.Coordenadas.split("|");
for (var i = 0; i < coord.length; i++) {
var latlng = coord[i].split(",");
coords.push(new google.maps.LatLng(latlng[1], latlng[0]));
}
var contentString="<b>"+item.Nome+"</b>"+item.Descricao;
//Create polygon
var idconcelho=item.Id;
var concelho = new google.maps.Polygon({
paths: coords,
idc: idconcelho,
strokeColor: "black",
strokeOpacity: 0.3,
strokeWeight: 1,
fillColor: item.Cor ? item.Cor : "white",
fillOpacity: 0.8,
html: contentString
});
MapaConcelhos.concelhos.push(concelho);
concelho.setMap(MapaConcelhos.map);
var bounds = new google.maps.LatLngBounds();
for (var i=0; i< coords.length; i++) {
bounds.extend(coords[i]);
mapbounds.extend(coords[i]);
}
var centroconcelho = bounds.getCenter();
var timer = null;
if (isDraggable)
{
google.maps.event.addListener(concelho,"click",function(){
showConcelho(concelho.idc);});
}
else
{
google.maps.event.addListener(concelho, 'mousedown', function(event){
start = new Date().getTime();
});
google.maps.event.addListener(concelho, 'mouseup', function(){
end = new Date().getTime();
longpress = (end - start < 300) ? false : true;
if (longpress) showConcelho(concelho.idc);
});
}//else
MapaConcelhos.addlegenda(item);
if (item.Ultimo=="1")
{
//MapaConcelhos.map.fitBounds(mapbounds);
//MapaConcelhos.map.setCenter(local);
}
function isInfoWindowOpen(infoWindow){
var map = infoWindow.getMap();
return (map !== null && typeof map !== "undefined");
}
var minZoom=8;
if (idd==41 || idd==-1) minZoom=7;
google.maps.event.addListenerOnce(MapaConcelhos.map, 'bounds_changed', function(event) {
if (this.getZoom() < minZoom) {
this.setZoom(minZoom);
MapaConcelhos.map.setCenter(local);
}
});
function showArrays(event) {
var vertices = this.getPath();
var contentString =this.html;
infoWindow.setContent(contentString);
infoWindow.setPosition(event.latLng);
infoWindow.open(MapaConcelhos.map);
}
function showConcelho(idc) {
$.fancybox({
href : "/ficha.php?id="+idc,
width : w,
height : h,
fitToView : true,
autoSize : false,
type: "iframe",
padding: 0,
openEffect : "elastic",
openSpeed : 150,
aspectRatio : true,
closeEffect : "elastic",
closeSpeed : 150,
closeClick : true,
scrolling : "auto",
preload : true
});
}
},
map: undefined,
mapContainer: document.getElementById(mapa),
initialize: function() {
google.maps.visualRefresh = true;
MapaConcelhos.map = new google.visualization.Map(document.getElementById(mapa), {
scrollwheel: false,
draggable: isDraggable,
disableDoubleClickZoom: true,
disableDefaultUI: true,
center: local,
mapTypeId: "",
backgroundColor: bk,
zoom: zoomlocal
});
}
};
var requester = {};
requester.Request = function () {
$.ajax({
url: "/scripts/concelhos.php",
type: "GET",
data: { tipo: mapatipo, distrito:idd},
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-1",
dataType: "json",
}).done(function(result) {
if (result) {
$.each(result, function(index, item) {
MapaConcelhos.addConcelho(item);
});
} else {
}
}).error(function() {
});
};
MapaConcelhos.initialize();
requester.Request();
return MapaConcelhos;
} //CarregaMapa

definitely need to use the following library, remove jsapi
<script src="https://www.gstatic.com/charts/loader.js"></script>
the load statement looks fine
google.charts.load('current', {'packages':['corechart', 'map']});
however, setOnLoadCallback expects a reference to a function, not the result of a function
regardless, the 'callback' can be added to the load statement as well
recommend using the following load statement...
google.charts.load('current', {
'callback': function () {
CarregaMapa("map-geral","eda",continente,7,-1,"#FFF",1000,600);
},
'packages': ['corechart', 'map']
});

I found the solution.
To keep the old code working I had to use a frozen version...
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?**v=3.25**&key=XXX>
I wonder if this version is retired what will hapen?
it's showing the same jsapi warnings but the map and polygons are drawn...
so the problem was with the version of the maps api...

Related

Javascript: What is this? Array in array? I don't understand why I can't access it? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Is Chrome’s JavaScript console lazy about evaluating objects?
(7 answers)
Closed 2 years ago.
Good morning,
I get data from JSON, with physical addresses that get converted to geo coordinates (If needed I can put the whole code here or a link to the site under construction).
Then I need to work with these coordinates to calculate distances or whatever.
But somehow I can't access them.
my code (extract) looks like this:
var positionsCenter = [];
for (let i = 0; i < positions.length; i++) {
lux.geocode({
num: positions[i].num,
street: positions[i].street,
zip: positions[i].zip,
locality: positions[i].locality
}, function (position) {
**positionsCenter[i] = position;**
var pFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform(position, 'EPSG:2169', 'EPSG:3857')),
id: i
});
vectorSource.addFeature(pFeature);
});
}
These are coordinates on a map (vector layer) but something's wrong.
When I output this via:
console.log(positionsCenter);
It gives me this:
[]
0: (2) [75980.11870000046, 75098.00039954418]
1: (2) [87897.10419999996, 63546.633999540085]
2: (2) [88238.34310000022, 63389.17289954127]
3: (2) [73701.38559999966, 76385.07059954498]
4: (2) [71212.77219999957, 74969.26619954518]
5: (2) [80450.28039999957, 72414.96529954427]
6: (2) [83811.06230000037, 75487.27249954658]
7: (2) [86081.38100000011, 86362.58049954918]
8: (2) [77022.02340000033, 80667.17809954635]
9: (2) [66163.39429999988, 62664.86699954068]
length: 10
__proto__: Array(0)
But when I try to access one of the entries like this:
console.log(positionsCenter[1]);
or
console.log(positionsCenter[1][1]);
or even
console.log(positionsCenter.length);
it's always undefined!
What do I miss? I'm confused :-/
Thank you for any help.
Best regards,
Claude
Here's the whole part of this code:
var map;
var vectorSource;
var highlightedFeature = null;
var selectedFeature = null;
function loadMap() {
map = new lux.Map({
target: 'map',
bgLayer: 'basemap_2015_global', //default basemap_2015_global, streets_jpeg
zoom: 16, //18
position: [75977, 75099],
showLayerInfoPopup: true,
search: {
target: 'searchbox',
dataSets: ['Adresse', 'Coordinates']
}
});
//-------------------------------------------------------------- FEATURES -
vectorSource = new ol.source.Vector({
features: []
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
function styleFunction(feature, resolution) {
var sti = feature.get('status');
const liv = 'livraison';
const tak = 'take-away';
var newColor = [128, 128, 128];
if (sti.includes('ouvert')) {
newColor = [0, 255, 0];
}
var imgSource = '../images/pin.png';
if (sti.includes(liv) && sti.includes(tak)) {
imgSource = '../images/pin-livraison-takeaway.png';
} else {
if (sti.includes(liv)) {
imgSource = '../images/pin-livraison.png';
} else {
if (sti.includes(tak)) {
imgSource = '../images/pin-takeaway.png';
}
}
}
var isSelected = feature.get('selected') || feature.get('highlighted');
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 0.5],
color: newColor,
anchorXUnits: 'fraction',
anchorYUnits: 'fraction',
src: imgSource,
scale: isSelected ? 1.5 : 1
}))
});
return [iconStyle];
}
vectorLayer.setStyle(styleFunction);
map.addLayer(vectorLayer);
for (let i = 0; i < positions.length; i++) {
lux.geocode({
num: positions[i].num,
street: positions[i].street,
zip: positions[i].zip,
locality: positions[i].locality
}, function (position) {
positionsCenter[i] = position;
var pFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform(position, 'EPSG:2169', 'EPSG:3857')),
id: i
});
const sti = statuses[i];
pFeature.set('status', sti);
pFeature.setId(i);
pFeature.set('selected', false);
pFeature.set('highlighted', false);
vectorSource.addFeature(pFeature);
});
//console.log(positions[i]);
}
map.on('click', function (evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
return feature;
});
if (feature !== undefined) {
if (selectedFeature !== null) {
selectedFeature.set('selected', false);
selectedFeature = null;
}
feature.set('selected', true);
selectedFeature = feature;
var outPut = feature.get('id');
infoField.innerHTML = arr[outPut].innerHTML;
infoField.style.display = 'block';
CloseinfoField.style.display = 'block';
galImage.style.display = 'none';
ClosegalImage.style.display = 'none';
getThumbs(outPut);
for (let j = 0; j < arr.length; j++) {
arr[j].classList.remove('active');
}
arr[outPut].className += ' active';
var current = document.getElementById('item' + outPut);
current.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
} else {
console.log('');
}
});
map.on('pointermove', function (evt) {
if (highlightedFeature !== null) {
highlightedFeature.set('highlighted', false);
highlightedFeature = null;
}
var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
return feature;
});
if (feature !== undefined) {
highlightedFeature = feature;
highlightedFeature.set('highlighted', true);
}
});
//------------------------------------------------------------------ DISTANCE -
var sourceProj = map.getView().getProjection();
var wgs84Sphere = new ol.Sphere(6378137);
var coordinates1 = [75977, 75099];
var coordinates2 = [76977, 75099];
// EDIT/UPDATE ----------------------------------------
function delay(ms) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve();
}, ms);
});
}
function getFive() {
return delay(100).then(function () {
return positionsCenter[0];
})
}
getFive().then(function (five) {
console.log(five);
});
// EDIT ----------------------------------------
var c1 = ol.proj.transform(coordinates1, sourceProj, 'EPSG:4326');
var c2 = ol.proj.transform(coordinates2, sourceProj, 'EPSG:4326');
var distance = wgs84Sphere.haversineDistance(c1, c2);
console.log(distance);
//----------------------------------------------------------------- /DISTANCE -
document.getElementById('myLocation').addEventListener('click', getLocation);
document.getElementById('navList').addEventListener('click', getnavList);
}

find nearest point and show properties from nearest point into user created marker in Leaflet

Example I'm trying to find the nearest markers on a map of a specific location with Leaflet, want to show popup info on user created marker which is find nearest point, popup info should be include with nearest point properties from the geojson data layer.
example maker.bindpopup(feature.properties.name).addTo(map)
(function() {
var geojosn1= 'url1';
var geojsonn2= 'url2';
var stations,
$body = $('body'),
$locate = $('#locate'),
$findNearest = $('#find-nearest'),
$status = $('#status');
$.getJSON(geojosn1, function(data) {
//$('#loader').fadeOut();
$body.addClass('loaded');
stations = L.geoJson(data, {
pointToLayer : function(feature, latlng) {
return L.circleMarker(latlng, {
stroke : false,
fillColor : 'orange',
fillOpacity : 1,
radius: 2
});
}
}).addTo(map);
$locate.fadeIn().on('click', function(e) {
$status.html('finding your location');
if (!navigator.geolocation){
alert("<p>Sorry, your browser does not support Geolocation</p>");
return;
}
$body.removeClass('loaded');
navigator.geolocation.getCurrentPosition(success, error);
$locate.fadeOut();
});
});
function success(position) {
$body.addClass('loaded');
var currentPos = [position.coords.latitude,position.coords.longitude];
map.setView(currentPos, zoomLevel);
var myLocation = L.marker(currentPos)
.addTo(map)
.bindTooltip("you are here")
.openTooltip();
$findNearest.fadeIn()
.on('click', function(e) {
$findNearest.fadeOut();
$status.html('finding your nearest locations')
queryFeatures(currentPos, 5);
myLocation.unbindTooltip();
});
};
function queryFeatures(currentPos, numResults) {
var distances = [];
stations.eachLayer(function(l) {
var distance = L.latLng(currentPos).distanceTo(l.getLatLng())/1000;
distances.push(distance);
});
distances.sort(function(a, b) {
return a - b;
});
var stationsLayer = L.featureGroup();
stations.eachLayer(function(l) {
var distance = L.latLng(currentPos).distanceTo(l.getLatLng())/1000;
if(distance < distances[numResults]) {
l.bindTooltip(distance.toLocaleString() + ' km from current location.');
L.polyline([currentPos, l.getLatLng()], {
color : 'orange',
weight : 2,
opacity: 1,
dashArray : "5, 10"
}).addTo(stationsLayer);
}
});
map.flyToBounds(stationsLayer.getBounds(), {duration : 3, easeLinearity: .1 });
map.on('zoomend', function() {
map.addLayer(stationsLayer);
})
}
})()
Try this:
function queryFeatures(currentPos, numResults) {
var stationsLayer = L.featureGroup();
var result = {
layer: null,
dis: 0,
marker: null
};
stations.eachLayer(function(l) {
var distance = L.latLng(currentPos).distanceTo(l.getLatLng())/1000;
if(result.layer == null || distance < result.dis) {
var line = L.polyline([currentPos, l.getLatLng()], {
color : 'orange',
weight : 2,
opacity: 1,
dashArray : "5, 10"
});
result = {
layer: line,
dis: distance,
marker: l
};
}
});
result.marker.bindTooltip(result.dis.toLocaleString() + ' km from current location.');
result.layer.addTo(stationsLayer);
map.flyToBounds(stationsLayer.getBounds(), {duration : 3, easeLinearity: .1 });
map.on('zoomend', function() {
map.addLayer(stationsLayer);
});
}

Uncaught TypeError: dashboard.draw is not a function - Google Graphs

I've been trying to get some old Google Graphs working which were working before. However, they are no longer showing. In the console I'm getting the following error...
Uncaught TypeError: dashboard.draw is not a function
However, after looking at the code and testing various things out I can't get it to work.
Can anyone see any issues with the code?
function downloadGraph(id){
var selected =jQuery('#anemometers_'+id+' :selected').val();
var data = {
action:"handleWindAjaxFunction",
function:"downloadGraph",
id:id,
selected:selected
}
jQuery.post("/wp-admin/admin-ajax.php", data, function(response) {
var file = jQuery.parseJSON(response);
if(file.file != "error"){ window.location.href = file.file; }
else { alert("No data found"); }
});
}
var is_mobile =
/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
var active_columns = new Array();
var maxData = 0;
var minData = 0;
var minPredictedData = 0;
var maxPredictedData = 0;
var currentData = '';
var pickedEnd = 0;
var pickedStart = 0;
var graph = 0;
var dataView = [];
var predictedView = [];
var running_initial = false;
function update_graph(){
var newData = getData(false);
//sort table by date
newData.data.sort({column: 0});
newData.predicted.sort({column: 0});
dataView = new google.visualization.DataView(newData.data);
dataView.setColumns(active_columns);
if(dataView.getViewColumns().length > 1){ dashboard.draw(dataView); }
predictedView = new google.visualization.DataView(newData.predicted);
predictedView.setColumns(active_columns);
if(predictedView.getViewColumns().length > 1){ predictedDashboard.draw(predictedView); }
if(jQuery("#poll_new_data").prop("checked")){
var start = data.getColumnRange(0).min;
var end = data.getColumnRange(0).max;
if(is_mobile){
jQuery("#control_mobile").dateRangeSlider("values",start,end);
} else {
control_range_slider.setState({"range":{"start":start,"end":end}});
}
}
}
function getChangedData(start,end,scale){
if(jQuery("#poll_new_data").prop("checked")){
var startSlider = data.getColumnRange(0).min;
var endSlider = data.getColumnRange(0).max;
if(is_mobile){
jQuery("#control_mobile").dateRangeSlider("values",startSlider,endSlider);
} else {
control_range_slider.setState({"range":{"start":startSlider,"end":endSlider}});
}
start = 0;
end = 0;
} else {
var startSlider = new Date(parseInt(start) * 1000);
var endSlider = new Date(parseInt(end) * 1000);
control_range_slider.setState({"range":{"start":startSlider,"end":endSlider}});
}
var params = {
action:"handleWindAjaxFunction",
function:"getGraphData",
graph_event:graph,
start:start,
end:end,
scale:scale
}
jQuery.post("/wp-admin/admin-ajax.php", params, function(response) {
eval("var o = "+response+";");
currentData = o;
running_initial = false;
update_graph();
});
}
function getGraphData(graphID, initial, start, end){
graph = graphID;
var params = {
action:"handleWindAjaxFunction",
function:"getGraphData",
graph_event:graphID,
start:start,
end:end,
scale:1,
initial:initial
}
jQuery.post("/wp-admin/admin-ajax.php", params, function(response) {
eval("var o = "+response+";");
currentData = o;
//currentData.hideHeadings = [];
if(initial == true){
run();
if(o.graph_settings != false){running_initial = true;}
} else {
running_initial = false;
}
});
}
function getData(initalise){
data = new google.visualization.DataTable();
predicted = new google.visualization.DataTable();
data.addColumn("datetime", "Timestamp");
predicted.addColumn("datetime", "Timestamp");
var counter = 1;
if(initalise == true){active_columns.push(0);}
var selectionHTML = '';
var headingsLength = currentData.headings.length * 3;
var inout = ["gust","average","direction"];
var count = 0;
for(var x in currentData.devices){
for(var i in inout){
if(initalise == true){
if(currentData.hideHeadings.indexOf(count) == -1){selectionHTML +="<input type=\"checkbox\" onclick=\"toggle("+(count + 1)+");\" checked />"+currentData.headings[x][i]+"<br />";}
else{selectionHTML +="<input type=\"checkbox\" onclick=\"toggle("+(count + 1)+");\" />"+currentData.headings[x][i]+"<br />";}
active_columns.push(count+1);
}
data.addColumn("number", currentData.headings[x][i]);
predicted.addColumn("number", currentData.headings[x][i]);
count++;
}
}
var rows = [];
headingsLength = headingsLength + 1;
for(var x in currentData.data.current){
var row = [];
var date = new Date(x*1000);
row.push(date);
for(var i in currentData.devices){
for(var y in inout){
if(currentData.data.current[x][i]){
if(y == 0){row.push(parseFloat(currentData.data.current[x][i].gust));}
else if(y == 1){row.push(parseFloat(currentData.data.current[x][i].average));}
else{row.push(parseFloat(currentData.data.current[x][i].direction));}
}else{row.push(null);}
}
}
data.addRows([row]);
}
for(var x in currentData.data.predicted){
var row = [];
var date = new Date(x*1000);
row.push(date);
for(var i in currentData.devices){
for(var y in inout){
if(currentData.data.predicted[x][i]){
if(y == 0){row.push(parseFloat(currentData.data.predicted[x][i].gust));}
else if(y == 1){row.push(parseFloat(currentData.data.predicted[x][i].average));}
else{row.push(parseFloat(currentData.data.predicted[x][i].direction));}
}else{row.push(null);}
}
}
predicted.addRows([row]);
}
if(initalise == true){
document.getElementById("controlsBox").innerHTML = selectionHTML;
minData = data.getColumnRange(0).min;
maxData = data.getColumnRange(0).max;
minPredictedData = predicted.getColumnRange(0).min;
maxPredictedData = predicted.getColumnRange(0).max;
}
return {data:data,predicted:predicted};
}
function drawChart() {
var alldata = getData(true);
var data = alldata.data;
var predicted = alldata.predicted;
data.sort({column: 0});
predicted.sort({column: 0});
dashboard = new google.visualization.Dashboard(document.getElementById('dashboard'));
//create Google Visualization Control Wrapper
control_range_slider = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'control_range',
'options' : {
'filterColumnIndex': 0,
'ui':{
'chartType': 'LineChart',
'chartOptions': {
'chartArea': {'left':85, 'width': '93%'},
'hAxis': { 'baselineColor': 'black'}
},
'chartView': {
'columns': [0,1]
},
'snapToData': false
}
},
//set initial range
'state': {'range': { 'start':new Date(data.getColumnRange(0).min), 'end' :new Date(data.getColumnRange(0).max) } }
});
//create Google Visualization Chart Wrapper
chart = new google.visualization.ChartWrapper({
'chartType':'LineChart',
'containerId': 'chart_div',
'options': {
'interpolateNulls': 'true',
'displayAnnotations': 'true',
'title': "graph",
'curveType': 'none',
'vAxis': {
'title': "Wind",
'gridlines': { 'count': 5},
'minorGridlines': {'count': 5}
},
'linewidth': 1,
'pointSize': 3,
'legend': {'position':'none' },
'chartArea': {'left': 85, 'top': 10, 'width': '93%', 'height':"85%" },
'focusTarget': 'category',
'hAxis': {
'title': 'Time',
'gridlines': {'count':10},
'minorGridlines': {'count':5}
},
'animation':{'duration':1000, 'easing': 'out' },
'view':{'columns': [0,1,2]}
}
});
//create Google Visualization Chart Wrapper for table
var table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'chart_table',
'options': {
'page':'enable',
'pageSize': 20,
'sortColumn': 0,
'sortAscending': false
}
});
dashboard.bind(control_range_slider, [chart, table]);
dataView = new google.visualization.DataView(data);
dataView.setColumns(active_columns);
//event to control range slider
google.visualization.events.addEventListener(control_range_slider, 'statechange', function(e) {
if(!e.inProgress){
//range changed
var start = new Date(Date.parse(control_range_slider.getState().range.start));
var end = new Date(Date.parse(control_range_slider.getState().range.end));
pickedStart = start.getTime() / 1000;
pickedEnd = end.getTime() / 1000;
//getChangedData(pickedStart,pickedEnd,jQuery("#measurement").find(":selected").val());
updateGraphSettings(pickedStart,pickedEnd);
}
});
//draw dashboard
if(dataView.getViewColumns().length > 1){ dashboard.draw(dataView); }
predictedDashboard = new google.visualization.Dashboard(document.getElementById('predictedDashboard'));
predicted_control_range_slider = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'predictedControl_range',
'options' : {
'filterColumnIndex': 0,
'ui':{
'chartType': 'LineChart',
'chartOptions': {
'chartArea': {'left':85, 'width': '93%'},
'hAxis': { 'baselineColor': 'black'}
},
'chartView': {
'columns': [0,1]
},
'snapToData': false
}
},
//set initial range
'state': {'range': { 'start':new Date(predicted.getColumnRange(0).min), 'end' :new Date(predicted.getColumnRange(0).max) } }
});
predictedChart = new google.visualization.ChartWrapper({
'chartType':'LineChart',
'containerId': 'predictedChart_div',
'options': {
'interpolateNulls': 'true',
'displayAnnotations': 'true',
'title': '',
'curveType': 'none',
'vAxis': {
'gridlines': { 'count': 5},
'minorGridlines': {'count': 5}
},
'linewidth': 1,
'pointSize': 3,
'legend': {'position':'none' },
'chartArea': {'left': 85, 'top': 10, 'width': '93%', 'height':"85%" },
'focusTarget': 'category',
'hAxis': {
'title': 'Time',
'gridlines': {'count':10},
'minorGridlines': {'count':5}
},
'animation':{'duration':1000, 'easing': 'out' },
'view':{'columns': [0,1]}
}
});
var predictedTable = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'predictedChart_table',
'options': {
'page':'enable',
'pageSize': 20,
'sortColumn': 0,
'sortAscending': true
}
});
predictedDashboard.bind(predicted_control_range_slider, [predictedChart, predictedTable]);
predictedView = new google.visualization.DataView(predicted);
predictedView.setColumns(active_columns);
if(predictedView.getViewColumns().length > 1){ predictedDashboard.draw(predictedView);}
//hide direction lines from the chart, but still display them in the table.
for(var x=0; x < currentData.hideHeadings.length; x++){
var key = active_columns.indexOf(currentData.hideHeadings[x] + 1);
active_columns.splice(key, 1);
}
predictedView.setColumns(active_columns);
dataView.setColumns(active_columns);
predictedChart.setView(active_columns);
chart.setView(active_columns);
//poll new data every minute
var chart_timer = setInterval(function(){
if(jQuery("#poll_new_data").prop("checked")){
getChangedData(pickedStart,pickedEnd,jQuery("#measurement").find(":selected").val());
}
var start = data.getColumnRange(0).min;
var end = data.getColumnRange(0).max;
if(is_mobile){jQuery("#control_mobile").dateRangeSlider("values",start,end);}
else {control_range_slider.setState({"range":{"start":start,"end":end}});}
}, 10000);
checkMobile();
google.visualization.events.addOneTimeListener(control_range_slider, 'ready', function(){
if(running_initial == true && currentData.graph_settings != false){
var start = new Date(parseInt(currentData.graph_settings.start) * 1000);
var end = new Date(parseInt(currentData.graph_settings.end) * 1000);
pickedStart = start.getTime() / 1000;
pickedEnd = end.getTime() / 1000;
control_range_slider.setState({"range":{"start":start,"end":end}});
if(is_mobile){jQuery("#control_mobile").dateRangeSlider("values",start,end);}
getChangedData(pickedStart,pickedEnd,jQuery("#measurement").find(":selected").val());
running_initial = false;
return true;
}
return false;
});
}
function update_dataView(){
active_columns.sort();
if(active_columns.length > 1){
chart.setView(active_columns);
//bind control wrapper to chart & table wrapper
dataView.setColumns(active_columns);
dashboard.bind(control_range_slider, [ ]);
dashboard.draw(dataView);
predictedView.setColumns(active_columns);
predictedChart.setView(active_columns);
//bind control wrapper to chart & table wrapper
predictedDashboard.bind(predicted_control_range_slider, [ ]);
predictedDashboard.draw(predictedView);
}
}
function toggle(c){
var c = parseInt(c);
var index = active_columns.indexOf(c);
if(index == -1){
active_columns.push(c);
} else {
while(index != -1){
active_columns.splice(index, 1);
index = active_columns.indexOf(c);
}
}
update_dataView();
}
function resizeHandler() {
dashboard.draw(dataView);
predictedDashboard.draw(predictedView);
}
if (window.addEventListener) {window.addEventListener('resize', resizeHandler, false);}
else if (window.attachEvent) {window.attachEvent('onresize', resizeHandler);}
function checkMobile(){
if (is_mobile){
jQuery("#dashboard").addClass("mobile_dashboard");
jQuery("#predictedChart_table").addClass("mobile_table");
jQuery("#chart_table").addClass("mobile_table");
jQuery("#predictedChart_div").addClass("mobile_chart");
jQuery("#chart_div").addClass("mobile_chart");
jQuery("#predictedDashboard").addClass("mobile_dashboard");
jQuery(".graph_anemometer").addClass("mobile_graph");
jQuery(".graph_anemometer").removeClass("graph");
jQuery(".graph_predicted").addClass("mobile_graph");
jQuery(".graph_predicted").removeClass("graph");
jQuery("#control_range").hide();
jQuery("#control_mobile").show();
jQuery("#control_mobile").dateRangeSlider({
bounds: {
min: new Date(minData),
max: new Date(maxData)
},
defaultValues: {
min: new Date(minData),
max: new Date(maxData)
},
arrows: true,
wheelMode: null
}).bind('valuesChanged', function(e, data) {
control_range_slider.setState({range: { start: data.values.min, end: data.values.max }});
control_range_slider.draw();
});
jQuery("#predictedControl_range").hide();
jQuery("#predictedControl_mobile").show();
jQuery("#predictedControl_mobile").dateRangeSlider({
bounds: {
min: new Date(minPredictedData),
max: new Date(maxPredictedData)
},
defaultValues: {
min: new Date(minPredictedData),
max: new Date(maxPredictedData)
},
arrows: true,
wheelMode: null
}).bind('valuesChanged', function(e, data) {
predicted_control_range_slider.setState({range: { start: data.values.min, end: data.values.max }});
predicted_control_range_slider.draw();
});
}
}
function changeScale(){
if(jQuery("#poll_new_data").prop("checked")){
getChangedData(pickedStart,pickedEnd,jQuery("#measurement").find(":selected").val());
}
}
function updateGraphSettings(start,end){
var params = {
action:"handleWindAjaxFunction",
function:"updateGraphSettings",
event:graph,
start:start,
end:end
}
jQuery.post("/wp-admin/admin-ajax.php", params, function(response) {});
}
function run() {
google.charts.load('current', {packages: ['table', 'controls', 'corechart', 'line']});
callback: drawChart;
google.charts.setOnLoadCallback(drawChart);
}
The code specifically references this function in the console error...
function resizeHandler() {
dashboard.draw(dataView);
predictedDashboard.draw(predictedView);
}
Thanks in advance for any help!

Get Variables from Qlik Sense to JavaScript

I'm new with JS and I have this extension from Qlik Sense that I'm trying to change, I need to point some pins according to a variable. If value of variable $type is 'A' I use some pin, if value is 'B' another and so on. But I really don't know how this extension get values from QS. Any help please?
Follow the JS:
require.config({
paths: {
async: '/extensions/GoogleMaps-Sense/lib/async',
markerclusterer: '/extensions/GoogleMaps-Sense/lib/markerclusterer'
},
shim: {
'markerclusterer': {
exports: 'MarkerClusterer'
}
}
});
define(['qlik', './src/properties', './src/styles', 'markerclusterer', './src/abbreviateNumber', 'qvangular', 'async!https://maps.googleapis.com/maps/api/js?key=AIzaSyASz5bdD789VzsLyki1JCKhSnCd5pEPY3Q'], function(qlik, properties, styles, MarkerClusterer, abbreviateNumber, qv) {
var BASE_URL = '/extensions/GoogleMaps-Sense/';
if (typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
}
if (typeof(Number.prototype.toDeg) === "undefined") {
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
}
}
return {
initialProperties: {
version: 1,
qHyperCubeDef: {
qSuppressZero: true,
qSuppressMissing: true
},
gmaps: {
cluster: {
oneStyle: false,
maxZoom: 10
},
map: {
mode: 'cluster',
customIcon: null,
iconUrl: '',
maxZoom: 18,
style: 'default'
}
}
},
definition: properties,
snapshot: {
canTakeSnapshot: true
},
paint: function($element, layout) {
$element.empty();
this.backendApi.cacheCube.enabled = false;
var _this = this;
var markers = [];
var selectedMarkers = [];
var rectangles = [];
var selectedRects = [];
var columns = layout.qHyperCube.qSize.qcx;
var totalheight = layout.qHyperCube.qSize.qcy;
var pageheight = Math.floor(10000 / columns);
var numberOfPages = Math.ceil(totalheight / pageheight);
var Promise = qv.getService('$q');
var promises = Array.apply(null, Array(numberOfPages)).map(function(data, index) {
var page = {
qTop: (pageheight * index) + index,
qLeft: 0,
qWidth: columns,
qHeight: pageheight
};
return this.backendApi.getData([page]);
}, this)
Promise.all(promises).then(function(data) {
render(data);
});
function render(data) {
var useCustomStyle = layout.gmaps.map.style !== 'default';
var hasMeasure = layout.qHyperCube.qMeasureInfo.length >= 1 ? true : false;
var hasPopup = layout.qHyperCube.qMeasureInfo.length === 2 ? true : false;
//The bounds object, used to determain which part of the map to show based on data
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
maxZoom: layout.gmaps.map.maxZoom,
panControl: true,
zoomControl: true,
overviewMapControl: false,
overviewMapControlOptions: {
opened: false
},
scaleControl: false,
streetViewControl: true,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.TERRAIN, google.maps.MapTypeId.HYBRID, 'map_style']
}
};
//Put the map on the page so give some visual feedback
var map = new google.maps.Map($element.get(0), mapOptions);
if (useCustomStyle) {
var selectedStyle = styles.filter(function(d) {
return d.key === layout.gmaps.map.style
});
var styledMap = new google.maps.StyledMapType(selectedStyle[0].data, {
name: layout.gmaps.map.style
});
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
};
//Create a marker for each row of data
data.forEach(function(obj) {
obj[0].qMatrix.forEach(function(row, index) {
if (row[0].qText == '-') return;
//Parse the dimension
var latlng = JSON.parse(row[0].qText);
//Reverse the order as QS sends long lat
var point = new google.maps.LatLng(latlng[1], latlng[0]);
//Create our marker - if we have a expression then use that otherwise default to just show locations
var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
var marker = new google.maps.Marker({
position: point,
title: '',
icon: image,
customData: hasMeasure ? row[1].qText : 1,
qElem: row[0].qElemNumber
});
//If we have popup values for each marker create the popup windows
if (hasPopup) {
marker.infoWindow = new google.maps.InfoWindow({
content: row[2].qText
});
google.maps.event.addListener(marker, 'mouseover', function() {
this.infoWindow.open(map, this);
});
google.maps.event.addListener(marker, 'mouseout', function() {
this.infoWindow.close();
});
};
//Add click handler
google.maps.event.addListener(marker, 'click', (function(value) {
return function() {
_this.selectValues(0, [value], true);
highlightMarkers(value)
}
})(row[0].qElemNumber));
bounds.extend(point);
markers.push(marker);
});
});
//Fit map to bounds
map.fitBounds(bounds);
//Clustering enabled
if (layout.gmaps.map.mode === 'cluster') {
if (layout.gmaps.cluster.oneStyle) {
var clusterStyles = [{
opt_textColor: 'black',
url: BASE_URL + 'images/singlecluster.png',
height: 56,
width: 55
}];
};
var mcOptions = {
imagePath: BASE_URL + 'images/m',
styles: clusterStyles,
maxZoom: layout.gmaps.cluster.maxZoom
};
//Draw clusters onto map
var markerCluster = new MarkerClusterer(map, markers, mcOptions);
markerCluster.setCalculator(function(markers, clusterStyles) {
var index = 0,
count = markers.length,
total = count;
while (total !== 0) {
//Create a new total by dividing by a set number
total = parseInt(total / 5, 10);
//Increase the index and move up to the next style
index++;
}
index = Math.min(index, clusterStyles);
var measure = 0;
for (var i = 0, k = count; i < k; i++) {
measure += parseInt(markers[i].customData)
}
var abbreviatedValue = abbreviateNumber(measure)
return {
text: abbreviatedValue,
index: index
};
});
};
if (layout.gmaps.map.mode === 'marker') {
markers.forEach(function(d) {
d.setMap(map);
})
};
if (layout.gmaps.map.mode === 'boxes') {
markers.forEach(function(d) {
var distance = d.customData > 1 ? d.customData : 10;
var lat = d.position.lat();
var lng = d.position.lng();
var boxbounds = new google.maps.LatLngBounds(box(lat, lng, 225, distance), box(lat, lng, 45, distance))
var rect = new google.maps.Rectangle({
strokeColor: layout.gmaps.boxes.strokeFill,
strokeOpacity: +layout.gmaps.boxes.strokeOpacity,
strokeWeight: +layout.gmaps.boxes.strokeWeight,
fillColor: layout.gmaps.boxes.fillColor,
fillOpacity: +layout.gmaps.boxes.fillOpacity,
qElem: d.qElem,
map: map,
bounds: boxbounds
});
//Add click handler
google.maps.event.addListener(rect, 'click', (function(value) {
return function() {
_this.selectValues(0, [value], true);
highlightRects(value)
}
})(d.qElem));
rectangles.push(rect);
})
};
};
//In selection mode - loop over markers to highlight markers scheduled for selection.
function highlightMarkers(qElem) {
var idx = selectedMarkers.indexOf(qElem);
if (idx > -1) {
selectedMarkers.splice(idx, 1)
} else {
selectedMarkers.push(qElem)
}
markers.forEach(function(marker) {
if (selectedMarkers.indexOf(marker.qElem) === -1) {
marker.setOpacity(0.5)
} else {
marker.setOpacity(1);
}
});
};
//In selection mode - loop over markers to highlight markers scheduled for selection.
function highlightRects(qElem) {
var idx = selectedRects.indexOf(qElem);
if (idx > -1) {
selectedRects.splice(idx, 1)
} else {
selectedRects.push(qElem)
}
rectangles.forEach(function(marker) {
if (selectedRects.indexOf(marker.qElem) === -1) {
marker.setOptions({
fillOpacity: +layout.gmaps.boxes.fillOpacity / 2,
strokeOpacity: +layout.gmaps.boxes.strokeOpacity / 2
})
} else {
marker.setOptions({
fillOpacity: +layout.gmaps.boxes.fillOpacity,
strokeOpacity: +layout.gmaps.boxes.strokeOpacity
})
}
});
};
function box(lat, lng, brng, dist) {
this._radius = 6371;
var dist = dist / this._radius;
var brng = brng.toRad();
var lat1 = lat.toRad();
var lon1 = lng.toRad();
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) +
Math.cos(lat1) * Math.sin(dist) *
Math.cos(brng));
var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist) *
Math.cos(lat1), Math.cos(dist) -
Math.sin(lat1) * Math.sin(lat2));
lon2 = (lon2 + 3 * Math.PI) % (2 * Math.PI) - Math.PI;
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
}
};
});
I think this might help
/**
* Retrieve the values of a list of variables.
*
* Since $q.all fails on the first error, we have to resolve all first
*
* #param {string[]} `varList` - The variable names.
* #param {object} `app` - The (Qlik Sense) app.
*
* #returns {Promise}
*
* #api public
*/
this.getEngineVarListValues = function ( app, varList ) {
if ( varList && Array.isArray( varList ) ) {
var promises = [];
varList.forEach( function ( variable ) {
promises.push( self.getEngineVarValue( app, variable ) )
} );
return $q.all( promises );
}
return $q.reject( new Error( 'getEngineVarListValues variable list passed.' ) );
};
Taken from https://github.com/stefanwalther/sense-extension-utils/blob/master/src/variable-utils.js
var app = qlik.currApp();
//get the variable content
app.variable.getContent('MYVAR',function ( reply ){
alert( JSON.stringify( reply ) );
});
source: http://help.qlik.com/en-US/sense-developer/June2017/Subsystems/APIs/Content/CapabilityAPIs/qlik-variable-interface.htm

Embedding a map inside a InfoWindow

I've attempted to embed a map inside an InfoWindow in order to create a pop up with a preview of the clustering. However once the InfoWindow is closed, the map div fails to render.
My attempt of a simplified jsfiddle, http://jsfiddle.net/behewur2/
function initialize() {
var mapOptions = {
center: {
lat: -34.9290,
lng: 138.6010
},
zoom: 8,
streetViewControl: false,
overviewMapControl: false
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var mcOptions = {
gridSize: 30,
zoomOnClick: false
};
var mcOptionsZoom = {
gridSize: 30,
zoomOnClick: true
};
var mc = new MarkerClusterer(map, [], mcOptions);
google.maps.event.addListener(mc, 'clusterclick',
function (cluster) {
if (typeof infowindow !== 'undefined') prevInfoWindow = infowindow;
infowindow = new google.maps.InfoWindow({
content: $('#inner-map-canvas')[0]
});
if (typeof prevInfoWindow !== 'undefined') prevInfoWindow.close();
infowindow.setPosition(cluster.getCenter());
infowindow.open(map);
google.maps.event.trigger(innermap, 'resize');
innermap.setZoom(innermap.getZoom());
for (var i = 0; i < cluster.getMarkers().length; i++) {
innermc.addMarker(
new google.maps.Marker({
position: cluster.getMarkers()[i].position,
map: innermap,
icon: cluster.getMarkers()[i].icon,
title: cluster.getMarkers()[i].title
}),
false);
}
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(mapOptions.center.lat, mapOptions.center.lng),
map: map,
icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=0|FF0000|000000'
});
mc.addMarker(marker, false);
var innermap = new google.maps.Map(document.getElementById("inner-map-canvas"), mapOptions);
var innermc = new MarkerClusterer(innermap, [], mcOptionsZoom);
}
google.maps.event.addDomListener(window, 'load', initialize);
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDKxl8sh1TEN61taio3wdbGwuSI8FVeQ5k"></script>
<script type="text/javascript" src="https://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer_packed.js"></script>
<div id="map-canvas"></div>
<div id="inner-map-canvas">
</dev>
It would be better to dynamically create the div node in the infowindow, it is destroyed when the infowindow is closed.
google.maps.event.addListener(mc, 'clusterclick', function (cluster) {
if (typeof infowindow !== 'undefined') prevInfoWindow = infowindow;
var innermapNode = document.createElement("div");
innermapNode.setAttribute("id", "inner-map-canvas");
innermapNode.style.height = "300px";
innermapNode.style.width = "300px";
infowindow = new google.maps.InfoWindow({
content: innermapNode
});
if (typeof prevInfoWindow !== 'undefined') prevInfoWindow.close();
infowindow.setPosition(cluster.getCenter());
infowindow.open(map);
innermap = new google.maps.Map(innermapNode, mapOptions);
innermc = new MarkerClusterer(innermap, [], mcOptionsZoom);
google.maps.event.addListener(infowindow, 'domready', function () {
google.maps.event.trigger(innermap, 'resize');
// innermap.setZoom(innermap.getZoom());
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < cluster.getMarkers().length; i++) {
innermc.addMarker(
new google.maps.Marker({
position: cluster.getMarkers()[i].position,
map: innermap,
icon: cluster.getMarkers()[i].icon,
title: cluster.getMarkers()[i].title,
keycount: cluster.getMarkers()[i].keycount
}),
false);
bounds.extend(cluster.getMarkers()[i].position);
}
google.maps.event.trigger(innermap, 'resize');
innermap.fitBounds(bounds);
});
});
proof of concept fiddle
code snippet:
function colorForCount(count) {
if (count == 1) return '4080FE';
if (count == 2) return 'F7C207';
if (count > 2 && count < 5) return 'F50D07';
if (count >= 5) return 'FF00F0';
else return 'B600FF';
}
var innermap;
var innermc;
function initialize() {
var mapOptions = {
center: {
lat: -34.9290,
lng: 138.6010
},
zoom: 8,
streetViewControl: false,
overviewMapControl: false
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var mcStyles = [{
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m1.png",
height: 53,
width: 53
}, {
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m2.png",
height: 53,
width: 53
}, {
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m3.png",
height: 53,
width: 53
}, {
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m4.png",
height: 53,
width: 53
}, {
url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m5.png",
height: 53,
width: 53
}];
var mcOptions = {
gridSize: 30,
zoomOnClick: false,
styles: mcStyles
};
var mcOptionsZoom = {
gridSize: 30,
zoomOnClick: true,
styles: mcStyles
};
var mc = new MarkerClusterer(map, [], mcOptions);
mc.setCalculator(function(markers, numStyles) {
var count = markers.length;
var total = 0;
var max = 0;
var index = 0;
if (max == 1) index = 0;
if (max == 2) index = 2;
if (max > 2 && max < 5) index = 3;
if (max >= 5) index = 4;
return {
text: count,
index: index
};
});
google.maps.event.addListener(mc, 'clusterclick',
function(cluster) {
if (typeof infowindow !== 'undefined') prevInfoWindow = infowindow;
var innermapNode = document.createElement("div");
innermapNode.setAttribute("id", "inner-map-canvas");
innermapNode.style.height = "300px";
innermapNode.style.width = "300px";
infowindow = new google.maps.InfoWindow({
content: innermapNode
});
if (typeof prevInfoWindow !== 'undefined') prevInfoWindow.close();
infowindow.setPosition(cluster.getCenter());
infowindow.open(map);
innermap = new google.maps.Map(innermapNode, mapOptions);
innermc = new MarkerClusterer(innermap, [], mcOptionsZoom);
google.maps.event.addListener(infowindow, 'domready', function() {
google.maps.event.trigger(innermap, 'resize');
// innermap.setZoom(innermap.getZoom());
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < cluster.getMarkers().length; i++) {
innermc.addMarker(
new google.maps.Marker({
position: cluster.getMarkers()[i].position,
map: innermap,
icon: cluster.getMarkers()[i].icon,
title: cluster.getMarkers()[i].title,
keycount: cluster.getMarkers()[i].keycount
}),
false);
bounds.extend(cluster.getMarkers()[i].position);
}
google.maps.event.trigger(innermap, 'resize');
innermap.fitBounds(bounds);
});
});
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
var mapBnds = map.getBounds();
var mapSpan = mapBnds.toSpan();
for (var i = 0; i < 25; i++) {
var latRan = (Math.random() * mapSpan.lat() / 2) + mapSpan.lat() / 4;
var lngRan = (Math.random() * mapSpan.lng() / 2) + mapSpan.lng() / 4;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(mapBnds.getSouthWest().lat() + latRan, mapBnds.getSouthWest().lng() + lngRan),
map: map,
icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=' + i + '|FF0000|000000'
});
mc.addMarker(marker, false);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
/**
* Pull out the unique keys and counts.
* #param {Object} json The Inventory object.
* #return {Array.<{portal:{portalGuid:string,portalLocation:string,
* portalImageUrl:string,portalTitle:string,portalAddress:string},
* count:number}>}
*/
function getKeys(json) {
// parse the json string
var inventory = json.gameBasket.inventory;
// loop over the inventory items to find keys
var keys = [];
var iitckeys = {};
for (var i = 0; i < inventory.length; i++) {
// if it's a key, attempt to add to the key list
var item = inventory[i];
if (item[2].resource && item[2].resource.resourceType == "PORTAL_LINK_KEY") {
addKey(keys, iitckeys, item[2].portalCoupler);
} else if (item[2].resource && (item[2].resource.resourceType == "CAPSULE" || item[2].resource.resourceType == "INTEREST_CAPSULE")) {
parseCapsule(keys, iitckeys, item[2].container.stackableItems);
}
}
// return back the keys
return {
keys: keys,
iitckeys: iitckeys
};
}
/**
* Parse the items within a capsule.
* #param {Array.<{portal:{portalGuid:string,portalLocation:string,
* portalImageUrl:string,portalTitle:string,portalAddress:string},
* count:number}>} keys The current key array.
* #param {Array.<Object>} items The capsule's contents.
*/
function parseCapsule(keys, iitckeys, items) {
for (var i = 0; i < items.length; i++) {
if (typeof items[i].exampleGameEntity[2].resource !== 'undefined') {
if (items[i].exampleGameEntity[2].resource.resourceType == "PORTAL_LINK_KEY") {
var count = items[i].itemGuids.length;
while (count > 0) {
addKey(keys, iitckeys, items[i].exampleGameEntity[2].portalCoupler);
count--;
}
}
}
}
}
/**
* Add a key def to the keys list.
* #param {Array.<{portal:{portalGuid:string,portalLocation:string,
* portalImageUrl:string,portalTitle:string,portalAddress:string},
* count:number}>} keys The current key array.
* #param {{portalGuid:string,portalLocation:string,portalImageUrl:string,
* portalTitle:string,portalAddress:string}} keyDef The key definition.
*/
function addKey(keys, iitckeys, keyDef) {
// try to find the key and increment the count
console.log("keyDef : " + keyDef);
for (var i = 0; i < keys.length; i++) {
if (keys[i].portal.portalGuid == keyDef.portalGuid) {
keys[i].count++;
iitckeys[keyDef.portalGuid] ++;
return;
}
}
// couldn't find the key, add it
keys.push({
portal: keyDef,
count: 1
});
iitckeys[keyDef.portalGuid] = 1;
}
function getLatLng(location) {
var newLoc = parseInt(location, 16);
//if MSB is set
if ((newLoc & 0x80000000) !== 0x00000000) {
console.log("neg");
return (newLoc - 0x100000000) / 1E6;
} else {
console.log("pos");
return newLoc / 1E6;
}
}
body,
html {
height: 100%;
width: 100%;
}
#map-canvas {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.cluster img {
width: 53px;
height: 53px;
}
#commands {
width: 100%;
}
#inner-map-canvas {
width: 300px;
height: 300px;
}
<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"></script>
<script src="https://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer.js"></script>
<div id="map-canvas"></div>
<div id="keyjson"></div>

Categories

Resources