Chart is not defined - javascript

i'm new to this pie chart. i tried all possibile solution available in the
internet. i have seperate .js file and html file in the same webapp folder.
i don't know where am i missing. Please help me to resolve this
issue. Thanks in advance.
i'm getting the error for creating new Chart in the console
piechart.js:48 Uncaught ReferenceError: Chart is not defined
at drawPieChart (piechart.js:48)
at validation (piechart.js:35)
Here is my html code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
<script type="text/javascript" src="piechart.js"></script>
</head>
<body>
<div>
<button onclick="makePieChart()">view to piechart</button>
</div>
<div>
<canvas id="chartContainer" style="height: 300px; width: 100%;margin-left: -313px;"></canvas>
</div>
</body>
</html>
Here is my pieChart.js code
if (typeof jQuery === "undefined") {
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-latest.min.js';
script.type = 'text/javascript';
script.srcOne="https://canvasjs.com/assets/script/canvasjs.min.js";
script.srcTwo="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
var details;
function makePieChart() {
console.log("in");
$.ajax({
url : 'http://localhost:8085/restcall/rest/details',
type : 'GET',
cache : false,
success : function(data) {
console.log(data);
details = data;
validation(details);
}
});
}
function validation(details) {
let pending = 0;
let completed = 0;
for (var i = 0; i < details.length; i++) {
if (details[i].flag == 0) {
pending++;
} else {
completed++;
}
}
drawPieChart(pending, completed);
}
function drawPieChart(count1, count2) {
var canvas = document.getElementById("chartContainer");
var ctx = canvas.getContext("2d");
var data = {
datasets : [ {
data : [ count1, count2 ],
backgroundColor : [ "#F7464A", "#46BFBD" ]
} ],
labels : [ "Completed", "Pending" ]
};
var myNewChart = new Chart(ctx, {
animationEnabled : true,
title : {
text : "status"
},
type : 'pie',
data : data
});
canvas.onclick = function(evt) {
var activePoints = myNewChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
var value = chartData.datasets[0].data[idx];
if (label === "Pending") {
pendingList(sample);
}
}
}
}
function pendingList(details) {
var pList = [];
var list = details;
console.log(list);
for (var i = 0; i < details.length; i++) {
if (details[i].flag == "0") {
pList.push(details[i].name);
} else {
//console.log(sample[i].name);
}
}
console.log(pList);
}

Related

How to draw graph with logarithmic scale by getting input from AJAX call in canvasjs

window.onload = function() {
var dataPoints = [];
// fetching the json data from api via AJAX call.
var X = [];
var Y = [];
var data = [];
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', ' https://api.myjson.com/bins/cixax', true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
}
xobj.send(null);
}
loadJSON(function(response) {
var response;
var field = JSON.parse(response);
var values = [];
//Iterating and storing leads & visits in a variable.
var $this = field;
for (var key in $this) {
if ($this.hasOwnProperty(key)) {
var data = $this[key].dates;
for (var val in data) {
values.push({
"X": data[val].visits,
"Y": data[val].leads
});
}
}
}
dataPoints = ({
"values": values
});
});
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Log Scale on Axis Y - Workaround using Linear Axis"
},
axisY: {
//valueFormatString: "0.## E0",
title: "In log scale",
labelFormatter: function(e) {
var lable = Math.pow(10, e.value);
if (lable >= 1000)
lable = CanvasJS.formatNumber(lable / 1000) + "k";
else
lable = CanvasJS.formatNumber(lable);
return lable;
},
interval: 1,
includeZero: false
},
toolTip: {
contentFormatter: function(e) {
var content = "Data Values";
for (var i = 0; i < e.entries.length; i++) {
content += "</br>" + e.entries[i].dataPoint.x + " : ";
content += CanvasJS.formatNumber(Math.round(Math.pow(10, e.entries[i].dataPoint.y)));
}
return content;
}
},
data: [{
type: "line",
dataPoints: []
}]
}); convertToLog(chart.options.data); chart.render();
function convertToLog(data) {
var dataPoints;
for (var j = 0; j < data.length; j++) {
dataPoints = data[j].dataPoints;
for (var i = 0; i < dataPoints.length; i++) {
dataPoints[i].y = Math.log10(dataPoints[i].y);
}
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
Here I am trying to draw the graph using canvasjs. I am getting the input from the external API using an AJAX call. And storing the variables X and Y in the array. Providing that as an input to that canvasjs library for drawing the graph. But I am not able to draw the graph. The above snippet is the one I have done.
The Chart wasn't getting rendered because the render method gets called before the data actually is loaded.
"x" & "y" should be in small instead of capital. The graph looks scrambled because the X Values in your JSON are not sorted.
Since the library now supports Logarithmic Scale on Y-Axis, you can use that instead of the work around.Here's a documentation link.
window.onload = function() {
//var dataPoints = [];
// fetching the json data from api via AJAX call.
var X = [];
var Y = [];
var data = [];
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'https://api.myjson.com/bins/cixax', true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
}
xobj.send(null);
}
loadJSON(function(response) {
var response;
var field = JSON.parse(response);
var values = [];
//Iterating and storing leads & visits in a variable.
var $this = field;
for (var key in $this) {
if ($this.hasOwnProperty(key)) {
var data = $this[key].dates;
for (var val in data) {
values.push({
"x": data[val].visits, // Should be "x" & "y"
"y": data[val].leads
});
}
}
}
//dataPoints = ({
// "values": values
//});
// Update the dataPoints & render the chart
// x values need to be in sorted order
chart.options.data[0].dataPoints = values;
chart.render();
});
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Log Scale on Axis Y - Workaround using Linear Axis"
},
axisY: {
//valueFormatString: "0.## E0",
title: "In log scale",
labelFormatter: function(e) {
var lable = Math.pow(10, e.value);
if (lable >= 1000)
lable = CanvasJS.formatNumber(lable / 1000) + "k";
else
lable = CanvasJS.formatNumber(lable);
return lable;
},
interval: 1,
includeZero: false
},
toolTip: {
contentFormatter: function(e) {
var content = "Data Values";
for (var i = 0; i < e.entries.length; i++) {
content += "</br>" + e.entries[i].dataPoint.x + " : ";
content += CanvasJS.formatNumber(Math.round(Math.pow(10, e.entries[i].dataPoint.y)));
}
return content;
}
},
data: [{
type: "line",
dataPoints: []
}]
}); //convertToLog(chart.options.data); chart.render();
function convertToLog(data) {
var dataPoints;
for (var j = 0; j < data.length; j++) {
dataPoints = data[j].dataPoints;
for (var i = 0; i < dataPoints.length; i++) {
dataPoints[i].y = Math.log10(dataPoints[i].y);
}
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

input text box does not updated properly for click event button

I have the following code which the cancel button is not working. I cannot figure out why, when the cancel button is hit, it does not render properly. The expected behavior is when the user hit cancel it would just rollback and hide the admin window. See the jsfiddle below.
Thanks for all the help
https://jsfiddle.net/launeric/y188v9bg/#&togetherjs=HrxmjAojcq
<!DOCTYPE html>
<!--
Created using JS Bin
http://jsbin.com
Copyright (c) 2017 by AH0HA (http://jsbin.com/hoqerih/6/edit)
Released under the MIT license: http://jsbin.mit-license.org
-->
<meta name="robots" content="noindex">
<html lang="en">
<head>
<meta name="description" content="udacity_catclicker_ben_admin_mod">
<meta charset="UTF-8">
<title>Cat Clicker</title>
<style id="jsbin-css">
img {
max-width:256px;
max-height:256px;;
width:auto;
height:auto;
}
</style>
</head>
<body>
<ul id="cat-list"></ul>
<div id="cat">
<h2 id="cat-name"></h2>
<div id="cat-count"></div>
<img id="cat-img" src="" alt="cute cat">
<br><button id="cat-admin-button-init" type="button">admin</button></br>
</div>
<div id="CatAdminDiv" style="display:none;">
<br>catName<input type="text" id="adminCatName" value="XXXXXX"></br>
<br>catURL<input type="text" id="adminCatURL" value="zzzzzz"></br>
<br>catCnt<input type="text" id="adminCatCnt" value="999"></br>
<br><button id="cat-admin-button-save" type="button">save</button></br>
<br><button id="cat-admin-button-cancel" type="button">cancel</button></br>
</div>
<script src="js/app.js"></script>
<script id="jsbin-javascript">
/* ======= Model ======= */
var model = {
currentCat: null,
cats: [
{
clickCount : 0,
name : 'Tabby',
imgSrc : 'https://static.pexels.com/photos/33358/cat-fold-view-grey-fur.jpg'
},
{
clickCount : 0,
name : 'Tiger',
imgSrc : 'https://static.pexels.com/photos/54632/cat-animal-eyes-grey-54632.jpeg',
},
{
clickCount : 0,
name : 'Scaredy',
imgSrc : 'http://1.bp.blogspot.com/-zAWnDj_hEeE/UjWq6heqF-I/AAAAAAAAB_8/iThTIziz7VA/s1600/cat.jpg',
},
{
clickCount : 0,
name : 'Shadow',
imgSrc : 'http://ravenclan.yolasite.com/resources/Dawnfleck.jpg',
},
{
clickCount : 0,
name : 'Sleepy',
imgSrc : 'https://i.ytimg.com/vi/aBSzB6qxisQ/0.jpg',
//imgSrc : 'img/9648464288_2516b35537_z.jpg',
//imgAttribution : 'https://www.flickr.com/photos/onesharp/9648464288'
}
]
};
/* ======= Octopus ======= */
var octopus = {
init: function() {
// set our current cat to the first one in the list
model.currentCat = model.cats[0];
// tell our views to initialize
catListView.init();
catView.init();
},
adminInit: function() {
var x = document.getElementById('CatAdminDiv');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
},
adminCancel: function(){
this.adminInit();
catView.render();
},
adminSave: function() {
var x = document.getElementById('cat-name');
var y = document.getElementById("adminCatName");
x.textContent = y.value;
},
getCurrentCat: function() {
return model.currentCat;
},
getCats: function() {
return model.cats;
},
// set the currently-selected cat to the object passed in
setCurrentCat: function(cat) {
model.currentCat = cat;
},
// increments the counter for the currently-selected cat
incrementCounter: function() {
model.currentCat.clickCount++;
catView.render();
}
};
/* ======= View ======= */
var catView = {
init: function() {
// store pointers to our DOM elements for easy access later
this.catElem = document.getElementById('cat');
this.catNameElem = document.getElementById('cat-name');
this.catImageElem = document.getElementById('cat-img');
this.countElem = document.getElementById('cat-count');
// on click, increment the current cat's counter
this.catImageElem.addEventListener('click', function(){
octopus.incrementCounter();
});
//admin begin
this.catAdminButtonInit = document.getElementById('cat-admin-button-init');
this.catAdminButtonCancel = document.getElementById('cat-admin-button-cancel');
this.catAdminButtonSave = document.getElementById('cat-admin-button-save');
this.AdminCatName = document.getElementById('AdminCatName');
this.AdminCatURL = document.getElementById('AdminCatURL');
this.AdminCatCnt = document.getElementById('AdminCatCnt');
this.AdminCatDiv = document.getElementById('CatAdminDiv');
this.catAdminButtonInit.addEventListener('click', function(){
octopus.adminInit();
});
this.catAdminButtonSave.addEventListener('click', function(){
octopus.adminSave();
});
this.catAdminButtonCancel.addEventListener('click', function(){
octopus.adminCancel();
});
//this.catAdminButtonCancel.addEventListener('click', function(){
// octopus.adminCancel();
//});
//admin end
// render this view (update the DOM elements with the right values)
this.render();
},
render: function() {
// update the DOM elements with values from the current cat
var currentCat = octopus.getCurrentCat();
this.countElem.textContent = currentCat.clickCount;
this.catNameElem.textContent = currentCat.name;
this.catImageElem.src = currentCat.imgSrc;
this.catNameElem.textContent = currentCat.name;
this.admincatName = document.getElementById("adminCatName");
this.admincatName.setAttribute("value", currentCat.name);
//document.getElementById("adminCatURL").setAttribute("value", currentCat.imgSrc);
//document.getElementById("adminCatCnt").setAttribute("value", currentCat.clickCount);
//var x = document.getElementById('AdminCatName');
// x.setAttribute("value",currentCat.name );
//x.value = 'xxx';//currentCat.name;
//var x2 = document.getElementById('adminCatName');
//x2.value=model.currentCat.name;
},
/*
renderAdmin: function(){
var currentCat = octopus.getCurrentCat();
//this.AdminCatName.value = currentCat.name;
var x = document.getElementById('AdminCatName')
x.setAttribute("value",currentCat.name );
}
*/
}
var catListView = {
init: function() {
// store the DOM element for easy access later
this.catListElem = document.getElementById('cat-list');
// render this view (update the DOM elements with the right values)
this.render();
},
render: function() {
var cat, elem, i;
// get the cats we'll be rendering from the octopus
var cats = octopus.getCats();
// empty the cat list
this.catListElem.innerHTML = '';
// loop over the cats
for (i = 0; i < cats.length; i++) {
// this is the cat we're currently looping over
cat = cats[i];
// make a new cat list item and set its text
elem = document.createElement('li');
elem.textContent = cat.name;
// on click, setCurrentCat and render the catView
// (this uses our closure-in-a-loop trick to connect the value
// of the cat variable to the click event function)
elem.addEventListener('click', (function(catCopy) {
return function() {
octopus.setCurrentCat(catCopy);
catView.render();
};
})(cat));
// finally, add the element to the list
this.catListElem.appendChild(elem);
}
}
};
// make it go!
octopus.init();
</script>
</body>
</html>

How to Handle Nested Dojo Deferreds

I am looking to query any attachments of layers based on the results of an Identify Task. If there are attachments on the layer, I would like to add the links to the bottom of the infoTemplate.
I am having trouble working the multiple dojo Deferred objects. I know they are being resolved because the return values are logged in the console, but my infoWindow is never populated.
So what is the proper way to deal with several nested deferreds? Deferred Lists seem to be a step in the right direction, but I am unsure how I would format one in this situation.
Thanks,
Joe
Update:
I have updated my working code below.
map.on('click',executeIdentify);
function executeIdentify(evt) {
identifyParams.width = map.width;
identifyParams.height = map.height;
identifyParams.geometry = evt.mapPoint;
identifyParams.mapExtent = map.extent;
var deferred = identifyTask.execute(identifyParams);
deferred.addCallback(function(deferredResult){
var promiseList = []
var features = array.map(deferredResult,function(result) {
var feature = result.feature;
var content = "";
array.forEach(Object.keys(feature.attributes),function(attr) {
content += attr + ": " + feature.attributes[attr] + "<br>"
});
var url = identifyTask.url + "/" + result.layerId + "/" + result.feature.attributes.OBJECTID + "/attachments?f=json"
var req = esriRequest({url:url}).then(function(newDef) {
if (Object.keys(newDef).toString() == "attachmentInfos,_ssl") {
content += "<br><b>Attachments:</b><hr>"
array.forEach(newDef.attachmentInfos,function(attach) {
content += "<a href=" + identifyTask.url + "/" + result.layerId + "/" + result.feature.attributes.OBJECTID + "/attachments/" + attach.id + " target='_blank'>" + attach.name + "</a><br>"
})
}
content += "<br><br>";
console.log(result)
feature.infoTemplate = new InfoTemplate(result.layerName + " " + result.feature.attributes.OBJECTID,content)
// console.log(feature)
return feature
},function(newDef) {
feature.infoTemplate = new InfoTemplate(result.layerName + " " + result.feature.attributes.OBJECTID,content);
// console.log(feature)
return feature
});
promiseList.push(req);
});
var promiseAll = new all(promiseList)
promiseAll.then(function(r) {promiseFun(r)})
})
function promiseFun(r) {
map.infoWindow.setFeatures(r);
map.infoWindow.show(evt.mapPoint);
}
}
You should look at using dojo/promise/all to handle multiple deferred results. Here's an example that uses it to return the results from multiple services, with some extra code to identify which service the result is coming from.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Identify with Popup</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.8/js/esri/css/esri.css">
<style>
html, body, #map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
</style>
<script>var dojoConfig = { parseOnLoad: true };</script>
<script src="http://js.arcgis.com/3.8/"></script>
<script>
var map;
var identifyTask, identifyParams, idPoint;
var identifyResults;
require([
"esri/map", "esri/dijit/Popup", "dojo/promise/all", "dojo/domReady!"
], function (
Map, Popup, All
) {
var popup = new Popup({
fillSymbol: new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 255, 0, 0.25]))
}, dojo.create("div"));
map = new Map("map", {
basemap: "satellite",
center: [-83.275, 42.573],
zoom: 18,
infoWindow: popup
});
dojo.connect(map, "onLoad", mapReady);
var landBaseLayer = new esri.layers.ArcGISDynamicMapServiceLayer("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/BloomfieldHillsMichigan/Parcels/MapServer", { opacity: .55 });
map.addLayer(landBaseLayer);
var militaryLayer = new esri.layers.ArcGISDynamicMapServiceLayer("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Military/MapServer", { opacity: .55 });
map.addLayer(militaryLayer);
function mapReady(map) {
dojo.connect(map, "onClick", runIdentifies);
}
function runIdentifies(evt) {
identifyResults = [];
idPoint = evt.mapPoint;
var layers = dojo.map(map.layerIds, function (layerId) {
return map.getLayer(layerId);
});
layers = dojo.filter(layers, function (layer) {
if (layer.visibleLayers[0] !== -1) {
return layer.getImageUrl && layer.visible
}
}); //Only dynamic layers have the getImageUrl function. Filter so you only query visible dynamic layers
var tasks = dojo.map(layers, function (layer) {
return new esri.tasks.IdentifyTask(layer.url);
}); //map each visible dynamic layer to a new identify task, using the layer url
var defTasks = dojo.map(tasks, function (task) {
return new dojo.Deferred();
}); //map each identify task to a new dojo.Deferred
var params = createIdentifyParams(layers, evt);
var promises = [];
for (i = 0; i < tasks.length; i++) {
promises.push(tasks[i].execute(params[i])); //Execute each task
}
var allPromises = new All(promises);
allPromises.then(function (r) { showIdentifyResults(r, tasks); });
}
function showIdentifyResults(r, tasks) {
var results = [];
var taskUrls = [];
r = dojo.filter(r, function (result) {
return r[0];
});
for (i = 0; i < r.length; i++) {
results = results.concat(r[i]);
for (j = 0; j < r[i].length; j++) {
taskUrls = taskUrls.concat(tasks[i].url);
}
}
results = dojo.map(results, function (result, index) {
var feature = result.feature;
var layerName = result.layerName;
var serviceUrl = taskUrls[index];
feature.attributes.layerName = result.layerName;
var template = new esri.InfoTemplate("", "Service Url: " + serviceUrl + "<br/><br/>Layer name: " + result.layerName + "<br/><br/> Object Id: ${OBJECTID}");
feature.setInfoTemplate(template);
var resultGeometry = feature.geometry;
var resultType = resultGeometry.type;
return feature;
});
if (results.length === 0) {
map.infoWindow.clearFeatures();
} else {
map.infoWindow.setFeatures(results);
}
map.infoWindow.show(idPoint);
return results;
}
function createIdentifyParams(layers, evt) {
var identifyParamsList = [];
identifyParamsList.length = 0;
dojo.forEach(layers, function (layer) {
var idParams = new esri.tasks.IdentifyParameters();
idParams.width = map.width;
idParams.height = map.height;
idParams.geometry = evt.mapPoint;
idParams.mapExtent = map.extent;
idParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_VISIBLE;
var visLayers = layer.visibleLayers;
if (visLayers !== -1) {
var subLayers = [];
for (var i = 0; i < layer.layerInfos.length; i++) {
if (layer.layerInfos[i].subLayerIds == null)
subLayers.push(layer.layerInfos[i].id);
}
idParams.layerIds = subLayers;
} else {
idParams.layerIds = [];
}
idParams.tolerance = 3;
idParams.returnGeometry = true;
identifyParamsList.push(idParams);
});
return identifyParamsList;
}
});
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

Send JS values to xively using XivelyJS

How can I send two Javascript values to a xively feed, One as the ID and one as the value. Current code is. I want to get those values in to a xively feed so I can access them via an arduino with wifi. Unfortunately getting the values directly from the website from JS does not seem straight forward so this is my workaround unless anyone has a better way of accessing this data from an arduino. Using this example for reference execept i want to send the data from website rather than retrieve it. http://xively.github.io/xively-js/tutorial/
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="parse-1.2.16.min.js"></script>
</head>
<body>
<script>
jQuery(function($){
xively.setKey( "APIKEY" );
Parse.initialize("APIKEY", "APIKEY");
var mValue = Parse.Object.extend("mValue");
var queryLngLat = new Parse.Query(mValue);
var classObject = new mValue();
var existingMarkers= [];
var databaseMarkers= [];
var counter = 0;
var div ;
var resultsLength;
setInterval(function update() {
queryLngLat.notEqualTo("longAndLat", null);
queryLngLat.find({
success: function(results) {
console.log("Successfully retrieved " + results.length + " scores.");
for (var j = 0; j < results.length; j++ ) {
databaseMarkers = (results[j].attributes.longAndLat);
resultsLength = results.length;
counter++;
var markerValueRead = results[j].attributes.Val;
CoordsPush = databaseMarkers.substring(1, databaseMarkers.length - 1);
div = document.createElement("div");
div.style.width = "400px;";
div.style.background = "white";
div.style.color = "black";
div.innerHTML = /*"Database LatLng: " + CoordsPush + " Marker Value: " + */markerValueRead;
div.setAttribute("id", CoordsPush);
document.body.appendChild(div);
//alert(div.id);
JSON.stringify(markerValueRead);
xively.setKey("UYby76Zocsur664I6sRd13BXKUKrpM3xDSntN5qB5fvPxMhG");
var feedID = 129375335,
datastreamID = "LatLng";
selector = "50.3754565, -4.14265649999993"
xively.datastream.get(feedID, datastreamID, function(datastream) {
$selector.html( datastream["current_value"] );
xively.datastream.subscribe(feedID, datastreamID, function( even, datastream_updated) {
$(selector).html(datastream_updated["current_value"]);
});
});
//console.log("(" + markers[d].getPosition().d + ", " + markers[d].getPosition().e +")");
console.log("Database LatLng: " + databaseMarkers + " Marker Value: " + markerValueRead);
}
counter = 0;
}
});
document.body.innerHTML = '';
}, 15000);
});
</script>
<script src="http://d23cj0cdvyoxg0.cloudfront.net/xivelyjs-1.0.4.min.js"></script>
</body>
</html>
Here's a simple example of sending a single value to each of two channels ("foo" and "bar") in a feed...
<!DOCTYPE HTML>
<html>
<head>
<title>Xively Test</title>
<script language="JavaScript" type="text/javascript" src="lib/jquery/jquery-1.10.2.min.js"></script>
<script language="JavaScript" type="text/javascript" src="lib/xively/xivelyjs-1.0.4.min.js"></script>
<script language="JavaScript" type="text/javascript">
var API_KEY = "YOUR_API_KEY";
var FEED_ID = "YOUR_FEED_ID";
$(document).ready(function() {
// Set your API key first
xively.setKey(API_KEY);
// build the data packet
var timestamp = new Date().toISOString();
var data = { "version" : "1.0.0",
"datastreams" : [
{ "id" : "foo", "datapoints" : [ {"at" : timestamp, "value" : 10} ] },
{ "id" : "bar", "datapoints" : [ {"at" : timestamp, "value" : 20} ] }
]
};
// upload the data
xively.feed.update(FEED_ID, data, function(response) {
if (response.status == "200") {
console.log("Yay, it worked!: " + JSON.stringify(response, null, 3));
}
else {
console.log("Boo, something went wrong!: " + JSON.stringify(response, null, 3));
}
});
});
</script>
</head>
<body>
Look in the console for output.
</body>
</html>

jquery html(array) doesn't insert all items in array

When I run the javascript code below, it load specified amount of images from Flickr.
By var photos = photoGroup.getPhotos(10) code, I get 10 images from cache.
Then, I can see the object has exactly 10 items by checking console.log(photos);
But actual image appeared on the page is less than 10 items...
I have no idea why this work this way..
Thank you in advance.
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
var PhotoGroup = function(nativePhotos, callback) {
var _cache = new Array();
var numberOfPhotosLoaded = 0;
var containerWidth = $("#contents").css('max-width');
var containerHeight = $("#contents").css('max-height');
$(nativePhotos).each(function(key, photo) {
$("<img src='"+"http://farm" + photo["farm"] + ".staticflickr.com/" + photo["server"] + "/" + photo["id"] + "_" + photo["secret"] + "_b.jpg"+"'/>")
.attr("alt", photo['title'])
.attr("data-cycle-title", photo['ownername'])
.load(function() {
if(this.naturalWidth >= this.naturalHeight) {
$(this).attr("width", containerWidth);
} else {
$(this).attr("height", containerHeight);
}
_cache.push(this);
if(nativePhotos.length == ++numberOfPhotosLoaded)
callback();
})
});
var getRandom = function(max) {
return Math.floor((Math.random()*max)+1);
}
this.getPhotos = function(numberOfPhotos) {
var photoPool = new Array();
var maxRandomNumber = _cache.length-1;
while(photoPool.length != numberOfPhotos) {
var index = getRandom(maxRandomNumber);
if($.inArray(_cache[index], photoPool))
photoPool.push(_cache[index]);
}
return photoPool;
}
}
var Contents = function() {
var self = this;
var contentTypes = ["#slideShowWrapper", "#video"];
var switchTo = function(nameOfContent) {
$(contentTypes).each(function(contentType) {
$(contentType).hide();
});
switch(nameOfContent) {
case("EHTV") :
$("#video").show();
break;
case("slideShow") :
$("#slideShowWrapper").show();
break;
default :
break;
}
}
this.startEHTV = function() {
switchTo("EHTV");
document._video = document.getElementById("video");
document._video.addEventListener("loadstart", function() {
document._video.playbackRate = 0.3;
}, false);
document._video.addEventListener("ended", startSlideShow, false);
document._video.play();
}
this.startSlideShow = function() {
switchTo("slideShow");
var photos = photoGroup.getPhotos(10)
console.log(photos);
$('#slideShow').html(photos);
}
var api_key = '6242dcd053cd0ad8d791edd975217606';
var group_id = '2359176#N25';
var flickerAPI = 'http://api.flickr.com/services/rest/?jsoncallback=?';
var photoGroup;
$.getJSON(flickerAPI, {
api_key: api_key,
group_id: group_id,
format: "json",
method: "flickr.groups.pools.getPhotos",
}).done(function(data) {
photoGroup = new PhotoGroup(data['photos']['photo'], self.startSlideShow);
});
}
var contents = new Contents();
</script>
</head>
<body>
<div id="slideShow"></div>
</body>
</html>
I fix your method getRandom() according to this article, and completely re-write method getPhotos():
this.getPhotos = function(numberOfPhotos) {
var available = _cache.length;
if (numberOfPhotos >= available) {
// just clone existing array
return _cache.slice(0);
}
var result = [];
var indices = [];
while (result.length != numberOfPhotos) {
var r = getRandom(available);
if ($.inArray(r, indices) == -1) {
indices.push(r);
result.push(_cache[r]);
}
}
return result;
}
Check full solution here: http://jsfiddle.net/JtDzZ/
But this method still slow, because loop may be quite long to execute due to same random numbers occurred.
If you care about performance, you need to create other stable solution. For ex., randomize only first index of your images sequence.

Categories