Calling multiple JSON data with Jquery Deferred - json

I am trying to get multiple JSON data with deferred object. I have JSON files for individual days. In each individual day, I have data for points, lines and polygons. I have jQueryUI Sliders to visualise for individual days. For example, if the slider has value of 1, only the day1 data (points, lines and polygons) need to be visualised, and for day2, all points, lines and polygons relating to day2 only should be visualised and so on.
I don't know what is problem with my code but it is not serving the required data. Latest data/merged data is shown.
Help me out here.
$(document).ready(function () {
var map = L.map("map", {
center: [27.6419412, 85.1224152],
zoom: 13,
doubleClickZoom: true
});
L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap'
}).addTo(map);
L.control.scale().addTo(map);
var markerCluster = L.markerClusterGroup({
showCoverageOnHover: false
});
function TableContent(jsonData) {
var content = $('<div></div>').addClass('table-content');
for (row in jsonData) {
var tableRow = $('<div></div>').addClass('table-row').append(function () {
var key = row;
if (!(key === "#uid" || key === "#changeset" || key === "#version" || key === "#timestamp" || key === "#id")) {
return jsonData[row] ? $("<div></div>").text(key).append($("<div></div>").text(jsonData[row])) : "";
}
});
tableRow.prependTo(content).addClass(row);
}
return $(content)[0];
}
function Table(json) {
return $('<div></div>').append($('<div class="title"></div>').text(json.type)).addClass('table-container').append(new TableContent(json.data));
}
var pointBuild = L.geoJson(null, {
pointToLayer: function (feature, latlng) {
var deferred = $.Deferred();
marker = L.marker(latlng, {
icon: L.icon({
iconUrl: 'img/marker.png',
iconSize: [30, 30],
iconAnchor: [15, 15]
}),
riseOnHover: true,
title: "This is a Point feature. Click to have a look at some of its attributes"
});
markerCluster.addLayer(marker);
deferred.resolve();
map.fire('cluster-hover');
return marker;
},
onEachFeature: function (feature, layer) {
var popup = L.popup();
layer.on('click', function (e) {
var deferred = $.Deferred();
popup.setLatLng(e.latlng);
popup.setContent(new TableContent(feature.properties));
popup.openOn(map);
deferred.resolve();
});
}
});
var myStyle = {
weight: 2,
opacity: 1,
color: '#FF0000',
dashArray: '3',
fillOpacity: 0.3,
fillColor: '#FA8072'
};
var wayBuild = L.geoJson(null, {
style: myStyle,
onEachFeature: function (feature, layer) {
var popup = L.popup();
layer.on('click', function (e) {
var deferred = $.Deferred();
popup.setLatLng(e.latlng);
popup.setContent(new TableContent(feature.properties));
popup.openOn(map);
deferred.resolve();
});
}
});
function pointLinePolygon(receivedPoints, receivedLines, receivedPolygon, day) {
var points_, lines_, polygon_;
var deferredPoint = $.Deferred();
var deferredLine = $.Deferred();
var deferredPolygon = $.Deferred();
$.getJSON(receivedPoints, function (data) {
setTimeout(function () {
pointBuild.addData(data);
points_ = markerCluster;
deferredPoint.resolve();
}, 0);
});
$.getJSON(receivedLines, function (data) {
setTimeout(function () {
lines_ = wayBuild.addData(data);
deferredLine.resolve();
}, 0);
});
$.getJSON(receivedPolygon, function (data) {
setTimeout(function () {
polygon_ = wayBuild.addData(data);
deferredPolygon.resolve();
}, 0);
});
$.when(deferredPoint, deferredLine, deferredPolygon).done(function () {
var featureGroup = L.layerGroup([points_, lines_, polygon_]);
featureGroup.addTo(map);
$.map(wayBuild._layers, function (layer, index) {
$(layer._container).find("path").attr("title", "This is a way feature. Click to have a look at some of its attributes.");
});
});
}
map.on('cluster-hover', function () {
setTimeout(function () {
$("#map").find("div.marker-cluster").attrByFunction(function () {
return {
title: "This is a Cluster of " + $(this).find("span").text() + " Point features. Click to zoom in and see the Point features and sub-clusters it contains."
}
});
}, 0);
});
var tooltip = $('<div id="toolTipSlider" />').hide();
$('#slider').slider({
min: 1,
max: 4,
slide: function (event, ui) {
if (ui.value === 1) {
tooltip.text("Day " + ui.value);
$.ajax({
type: 'post',
success: function () {
pointLinePolygon("data/day1/points.geojson", "data/day1/lines.geojson", "data/day1/polygon.geojson", "Day 1");
}
});
}
else if (ui.value === 2) {
tooltip.text("Day " + ui.value);
$.ajax({
type: 'post',
success: function () {
pointLinePolygon("data/day2/points.geojson", "data/day2/lines.geojson", "data/day2/polygon.geojson", "Day 2");
}
});
}
else if (ui.value === 3) {
tooltip.text("Day " + ui.value);
$.ajax({
type: 'post',
success: function () {
pointLinePolygon("data/day3/points.geojson", "data/day3/lines.geojson", "data/day3/polygon.geojson", "Day 3");
}
});
}
else if (ui.value === 4) {
tooltip.text("Day " + ui.value);
$.ajax({
type: 'post',
success: function () {
pointLinePolygon("data/day4/points.geojson", "data/day4/lines.geojson", "data/day4/polygon.geojson", "Day 4");
}
});
}
}
}).find(".ui-slider-handle").append(tooltip).hover(function () {
tooltip.show();
});
});
$.fn.attrByFunction = function (a) {
return $(this).each(function () {
$(this).attr(a.call(this));
});
};

I solved the problem by clearing the map layer every time I am to add new one.
map.eachLayer(function (layer) {
if (layer.feature) {
map.removeLayer(layer);
}
});

Related

Create Chart of 2 temp readings from firebase to Google charts

I have 2 tempsensors that send their temp every ten min to firebase.
My firebase is structured like this:
{
AB: {
-K9kbKg4iqzaGP_mbKIC: {
date: "05 Feb 2016 08:47:27 +0000",
value: "013.2"
},
BattLevel: {}
},
AC: {
-K9kaqlycXMDbH-LpVrH: {
date: "05 Feb 2016 08:45:19 +0000",
value: "009.4"
},
BattLevel: {}
}
}
I would like to create a Google chart
But i don't seem to get the Json parsing wright.
I can add the temp of 1 sensor to display if i set the json path to
https://tempraspberry.firebaseio. com/AB.json
/<script>
// onload callback
function drawChart() {
// JSONP request
var jsonData = $.ajax({
url: 'https://tempraspberry.firebaseio.com/AB.json',
data: {page: 1},
dataType: 'jsonp',
}).done(function (results) {
var data1 = new google.visualization.DataTable();
data1.addColumn('datetime', 'Time');
data1.addColumn('number', 'Temp');
$.each(results, function (i, row) {
data1.addRow([
(new Date(row.date)),
parseFloat(row.value)
]);
});
//tweede chart
var jsonData = $.ajax({
url: 'https://tempraspberry.firebaseio.com/AC.json',
data: {page: 1},
dataType: 'jsonp',
}).done(function (results) {
var data2 = new google.visualization.DataTable();
data2.addColumn('datetime', 'Time');
data2.addColumn('number', 'Temp');
$.each(results, function (i, row) {
data2.addRow([
(new Date(row.date)),
parseFloat(row.value)
]);
});
});
//einde tweede chart
});
var joinedData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
chart.draw(joinedData, {
height: 300,
width: 600,
interpolateNulls: true
});
}
// load chart lib
google.load('visualization', '1', {
packages: ['corechart']
});
// call drawChart once google charts is loaded
google.setOnLoadCallback(drawChart);
</script>
I get can't find variable data1 with the above code.
Looks like a scope issue, declare the DataTable up front, something like this...
function drawChart() {
var data;
var sensors;
sensors = ['AB', 'AC'];
data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Temp');
// start process
requestData();
function requestData() {
var nextSensor;
if (sensors.length > 0) {
nextSensor = sensors.pop();
$.ajax({
url: 'https://tempraspberry.firebaseio.com/' + nextSensor + '.json',
data: {page: 1},
dataType: 'jsonp',
}).done(loadData);
} else {
loadChart();
}
}
function loadData(results) {
$.each(results, function (i, row) {
data.addRow([
(new Date(row.date)),
parseFloat(row.value)
]);
});
requestData();
}
function loadChart() {
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
chart.draw(data, {
height: 300,
width: 600,
interpolateNulls: true
});
}
}
google.load('visualization', '1', {
packages: ['corechart']
});
google.setOnLoadCallback(drawChart);
Thanks with small adjustments it works now.
I now have 2 datatables that show on one Google Chart.
I know the code probably isn't pretty but it works :-)
<script>
function drawChart() {
var data1;
var data2;
var sensors;
sensors = ['AB', 'AC'];
data1 = new google.visualization.DataTable();
data2 = new google.visualization.DataTable();
data1.addColumn('date', 'Tijd');
data1.addColumn('number', 'Paleis Zora');
data2.addColumn('date', 'Tijd');
data2.addColumn('number', 'Buiten');
// start process
requestData();
function requestData() {
$.ajax({
url: 'https://tempraspberry.firebaseio.com/AB.json',
data: {page: 1},
dataType: 'jsonp',
}).done(loadData);
}
//eerste datatable
function loadData(results) {
$.each(results, function (i, row) {
data1.addRow([
(new Date(row.date)),
parseFloat(row.value)
]);
});
requestData2();
}
//tweededatatable
function requestData2() {
$.ajax({
url: 'https://tempraspberry.firebaseio.com/AC.json',
data: {page: 1},
dataType: 'jsonp',
}).done(loadData2);
}
//eerste datatable
function loadData2(results) {
$.each(results, function (i, row) {
data2.addRow([
(new Date(row.date)),
parseFloat(row.value)
]);
});
loadChart();
}
function loadChart() {
var joinedData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
chart.draw(joinedData, {
height: 500,
width: 800,
interpolateNulls: true
});
}
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});

Select which columns from CSV to graph with HighChart

As I was looking at the question How do I select which columns from my CSV to chart with HighChart? I tried to apply it using a csv file but I could not get it to work!
What am I doing wrong? Thank you in advance:
$(function () {
//var data = "Year,Month,Day,Hour,Time,kWh,Savings,Total kWh\n2013,02,06,11,11:00,0,0,308135\n2013,02,06,11,11:59,15,1.875,308150\n2013,02,06,12,12:59,27,3.375,308177\n2013,02,06,13,13:59,34,4.25,308211\n2013,02,06,14,14:59,32,4,308243";
var options = {
chart: {
renderTo: 'EXAMPLE',
defaultSeriesType: 'line'
},
title: {
text: 'Current Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: hassayampa.csv',
x: -20
},
xAxis: {
type: 'datetime'
},
yAxis:{
title: {
text: 'Temperature (\xB0C)'
},
//min: 0
},
legend:{
layout: 'vertical',
//backgroundColor: '#FFFFFF',
//floating: true,
align: 'left',
//x: 100,
verticalAlign: 'top',
//y: 70,
borderWidth: 0
},
series: [{
name: 'PRIM OUT TEMP',
data: []
}, {
name: 'SEC OUT TEMP',
data: []
}]
};
// data is variable from $.get()
$.get('http://www.geoinc.org/Dropbox/geo/sites/GC_ROOM/EXAMPLE.csv', function(data){
var lines = data.split('\n');
$.each(lines, function (lineNo, line) {
var items = line.split(',');
if(lineNo !== 0) {
var x = + new Date(items[1]+'/'+items[2]+'/'+items[0]+' '+items[4]),
kwh = parseFloat(items[5]),
savings = parseFloat(items[6]);
if(!isNaN(kwh) && !isNaN(savings)){
options.series[0].data.push([x,kwh]);
options.series[1].data.push([x,savings])
}
}
});
});
new Highcharts.Chart(options);
});
Here is the jsfiddle:http://jsfiddle.net/tonystinge/3bQne/1223/
I got it now...
// data is variable from $.get()
$.get('http://www.geoinc.org/Dropbox/geo/sites/GC_ROOM/EXAMPLE.csv', function(data){
// parsing here...
});
new Highcharts.Chart(options);
});
Your problem is the placement of the new Highcharts.Chart(options) call. $.get (like most ajax calls) is asynchronous So the new Highcharts will be called before it completes.
Change it to this:
// data is variable from $.get()
$.get('http://www.geoinc.org/Dropbox/geo/sites/GC_ROOM/EXAMPLE.csv', function(data){
var lines = data.split('\n');
$.each(lines, function (lineNo, line) {
var items = line.split(',');
if(lineNo !== 0) {
var x = + new Date(items[1]+'/'+items[2]+'/'+items[0]+' '+items[4]),
kwh = parseFloat(items[5]),
savings = parseFloat(items[6]);
if(!isNaN(kwh) && !isNaN(savings)){
options.series[0].data.push([x,kwh]);
options.series[1].data.push([x,savings])
}
}
});
new Highcharts.Chart(options); // this is now in the $.get callback function
});

Static infowindow with Google Maps V3 (disable events temporarily) gmap3

I use jquery gmap3.
Is it possible to disable running event-listeners temporarily when I show an infowindow and enable them when I click the close-button on my infowindow?
Edit:
Here is the function that will be called when the "click"-event is fired (for big infowindow) or mouseover (then the variable "shortwindow" will be "s").
function infoWindow_open(thismap, marker, id, language, shortwindow) {
// Get InfoWindow with AJAX-Request
$.ajax({
type: "POST",
url: "getInformation_ajax.php",
data: "id="+encodeURIComponent(id)+"&language="+encodeURIComponent(language),
success: function(data) {
var json = $.parseJSON(data);
if(json.infownd === null || json.infowndshort === null) {
return;
}
var map = thismap.gmap3("get"),
infowindow = thismap.gmap3({get:{name:"infowindow"}});
if(shortwindow == "s") { // Short infowindow on mouseover
content_ = "<h class=name_gmap3'>"+json.infowndshort+"</h>";
$('#test1').gmap3({
map:{
events:{
zoom: 2,
minZoom: 1, // If 0: BUG!?
mapTypeId: google.maps.MapTypeId.SATELLITE,
//disableDefaultUI: true,
//panControl: true,
//zoomControl: true,
//scaleControl: true
}}});
if(infowindow) {
infowindow.open(map, marker);
//infowindow.setOptions({alignBottom: true});
infowindow.setContent(content_);
}
else {
thismap.gmap3({
infowindow: { anchor:marker, options:{content: content_} }
});
}
}
else {
if(infowindow) {
infowindow.setOptions({maxWidth:350/*, pixelOffet: new google.maps.Size(50,-50)*/});
infowindow.setContent(json.infownd);
infowindow.open(map, marker);
} else {
thismap.gmap3({
infowindow: { anchor:marker, options:{content: json.infownd/*, pixelOffet: new google.maps.Size(50,-50)*/} }
});
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// Do nothing!
//$("#erroutp#").html(textStatus);
}
});
}
Inside the mouseover-callback(that opens the small window) check the map-property of the big InfoWindow.
When it's not null the big infowindow is open, leave the mouseover-callback without opening the small infoWindow.
Modified code with some improvements(removed duplicate parts, caching of content):
function infoWindow_open(thismap, marker, id, language, shortwindow) {
//initialize infowindow on first run
var infowindow = thismap.gmap3({get:{name:"infowindow"}})
||
thismap.gmap3({infowindow: {options:{'shortwindow':'s'} }})
.gmap3({get:{name:"infowindow"}}),
key = (shortwindow==='s')
?'s':'l',
//options for the InfoWindow
iwOpts = {
//small
s:{maxWidth:350},
//large
l:{}
},
//options for the map
mapOpts = {
//small
s:{},
//large
l:{}
},
//function that sets the content
//and opens the window
setOpts = function(marker){
//set infowindow-options
infowindow.setOptions($.extend({},
iwOpts[key],
{
content:marker.get('content')[key],
//property to determine if it's
//a small or large window
shortwindow:shortwindow
}
)
);
//open the infowindow
infowindow.open(marker.getMap(),marker);
//set map-options
marker.getMap().setOptions(mapOpts[key]);
}
//leave the function onmouseover
//when a big infowindow is open
if(shortwindow==='s'
&& infowindow.get('shortwindow')!=='s'
&& infowindow.getMap()){
return;
}
if(marker.get('content')){
console.log('cached');
setOpts(marker);
return;
}
// Get InfoWindow-content with AJAX-Request
$.ajax({
type: "POST",
url: "getInformation_ajax.php",
data: "id="+encodeURIComponent(id)+"&language="+encodeURIComponent(language),
success: function(data) {
var json = $.parseJSON(data);
if(json.infownd === null || json.infowndshort === null) {
return;
}
//cache the content as marker-property
marker.set('content',
{s:"<h3 class=name_gmap3'>"+json.infowndshort+"</h3>",
l: json.infownd});
//open infoWindow
setOpts(marker);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// Do nothing!
//$("#erroutp#").html(textStatus);
}
});
}

Google map is not loading on a div hover

This code block is working well on page is loading--
<script type="text/javascript">
google.load("visualization", "1", { packages: ["map"] });
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = google.visualization.arrayToDataTable([
['Lat', 'Lon', 'Name'],
[22.1589, 90.1165, 'BARGUNA'],
[22.6953, 90.3538, 'BARISAL'],
]);
var options = {
showLine: false,
showTip: true,
zoomLevel: 7,
mapType: 'terrain'
};
var map = new google.visualization.Map(document.getElementById('map_canvas'));
map.draw(data, options);
}
</script>
This code block is for a specific div hover event. But it is not working--
<script>
$(function () {
$('#tab-dhakadivision').hover(function () {
google.load("visualization", "1", { packages: ["map"] });
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = google.visualization.arrayToDataTable([
['Lat', 'Lon', 'Name'],
[23.78069, 90.41932, 'DHAKA'],
[23.60113, 89.83923, 'FARIDPUR'],
[24.11119, 90.42584, 'GAZIPUR']
]);
var options = {
showLine: false,
showTip: true,
zoomLevel: 7,
mapType: 'terrain'
};
var dmap = new google.visualization.Map(document.getElementById('map_canvas'));
dmap.draw(data, options);
}
});
});
</script>
Any suggestion ?

Filtering gmap markers, how?

How can I filtering gmap markers from Json file?
$(function() {
demo.add(function() {
$('#map_canvas').gmap({'disableDefaultUI':false, 'callback': function() {
var self = this;
$.getJSON('demo.asp', function (data) {
$.each( data.markers, function(i, marker) {
self.addMarker({ 'position': new google.maps.LatLng(marker.latitude, marker.longitude), 'bounds':true } ).click(function() {
self.openInfoWindow({ 'content': marker.content }, this);
});
});
});
}});
}).load();
});
$(function() {
demo.add(function() {
$('#map_canvas').gmap({'disableDefaultUI':false, 'callback': function() {
var self = this;
$.getJSON('demo.asp', function (data) {
$.each( data.markers, function(i, marker) {
if(marker!="filtered data"){
self.addMarker({ 'position': new google.maps.LatLng(marker.latitude, marker.longitude), 'bounds':true } ).click(function() {
self.openInfoWindow({ 'content': marker.content }, this);
}
});
});
});
}});
}).load();
});
You can filter it there, or filter it on the logic that gets the json data.