Integrating tabletop.js with d3.js? - json

I want to reference a google spreadsheet using tabletop for for the data in my d3 visualization. The best solution I can come up with is this, but I know that it's not quite right.
window.onload = function() { init() };
var public_spreadsheet_url = 'https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html';
function init() {
Tabletop.init( { key: public_spreadsheet_url,
callback: showInfo,
simpleSheet: true } )
}
d3.json("showInfo", function(data) {
console.log(data);
});

The data comes as an array already (see output below); and so there is no need to apply d3.json. You can start using the array for your d3 visualization right away.
window.onload = function() { init() };
var public_spreadsheet_url = "https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE&output=html";
function init() {
Tabletop.init( { key: public_spreadsheet_url,
callback: showInfo,
simpleSheet: true } )
}
function showInfo(rows) {
console.log(rows);
// build your d3 vis here..
}

Related

Button for markupCore extension not showing in dockingpanel

I have followed Philippe Leefsma's tutorial on how to implement the markup tool, but without any luck. Link here: http://adndevblog.typepad.com/cloud_and_mobile/2016/02/playing-with-the-new-view-data-markup-api.html
and here: https://developer.api.autodesk.com/viewingservice/v1/viewers/docs/tutorial-feature_markup.html
I get errors that I need to include requireJS, but I don't want to use it. So instead I used this script in my html file:
<script src="https://autodeskviewer.com/viewers/2.2/extensions/MarkupsCore.js">
I don't know if this is the right way to go? I get no errors in the console, but the markup button doesn't show up in the dockingpanel.
This is my code for loading the extension in the viewer:
viewerApp = null;
function initializeViewer(containerId, urn, params) {
function getToken(url) {
return new Promise(function (resolve, reject) {
$.get(url, function (response) {
resolve(response.access_token);
});
});
}
var initOptions = {
documentId: 'urn:' + urn,
env: 'AutodeskProduction',
getAccessToken: function (onGetAccessToken) {
getToken(params.gettokenurl).then(function (val) {
var accessToken = val;
var expireTimeSeconds = 60 * 30;
onGetAccessToken(accessToken, expireTimeSeconds);
});
}
}
function onDocumentLoaded(doc) {
var rootItem = doc.getRootItem();
// Grab all 3D items
var geometryItems3d =
Autodesk.Viewing.Document.getSubItemsWithProperties(
rootItem, { 'type': 'geometry', 'role': '3d' }, true);
// Grab all 2D items
var geometryItems2d =
Autodesk.Viewing.Document.getSubItemsWithProperties(
rootItem, { 'type': 'geometry', 'role': '2d' }, true);
// Pick the first 3D item otherwise first 2D item
var selectedItem = (geometryItems3d.length ?
geometryItems3d[0] :
geometryItems2d[0]);
var domContainer = document.getElementById('viewerContainer');
var config = { extensions: ["Autodesk.Viewing.MarkupsCore"] };
// GUI Version: viewer with controls
var viewer = new Autodesk.Viewing.Private.GuiViewer3D(domContainer, config);
viewer.loadExtension("Autodesk.Viewing.MarkupsCore");
viewer.initialize();
viewer.loadModel(doc.getViewablePath(selectedItem));
var extension = viewer.getExtension("Autodesk.Viewing.MarkupsCore");
viewerApp = viewer;
}
function onEnvInitialized() {
Autodesk.Viewing.Document.load(
initOptions.documentId,
function (doc) {
onDocumentLoaded(doc);
},
function (errCode) {
onLoadError(errCode);
})
}
function onLoadError(errCode) {
console.log('Error loading document: ' + errCode);
}
Autodesk.Viewing.Initializer(
initOptions,
function () {
onEnvInitialized()
})
}
Any help is highly appreciated!
Unfortunately there has been a few changes to the API since I wrote that blog post. The MarkupCore.js is now included in the viewer3D.js source, so you don't need to reference any extra file or use requireJS if you use the latest version of the viewer API.
Keep in mind that this is an API-only feature, so even after loading the markup extension, you won't get any UI out of the box. You have to implemented it yourself, for example create a dialog with buttons that may eventually create markups by calling the API.
Some of the code from my blog post may still be valid and give you an idea about what you need to do.
Hope that helps.

How to save a completed polygon points leaflet.draw to mysql table

I would like to use leaflet.draw to create outlines of regions. I have managed to get this working ok: https://www.mapbox.com/mapbox.js/example/v1.0.0/leaflet-draw/
Now I'd like to save the data for each polygon to a mysql table. Am a little stuck on how I would go about exporting the data and the format I should be doing it in.
If possible I'd like to pull the data back into a mapbox/leaflet map in the future so guess something like geojson would be good.
So you could use draw:created to capture the layer, convert it to geojson then stringify it to save in your database. I've only done this once and it was dirty but worked.
map.on('draw:created', function (e) {
var type = e.layerType;
var layer = e.layer;
var shape = layer.toGeoJSON()
var shape_for_db = JSON.stringify(shape);
});
If you want to collect the coordinates, you can do it this way:
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
drawnItems.addLayer(layer);
var shapes = getShapes(drawnItems);
// Process them any way you want and save to DB
...
});
var getShapes = function(drawnItems) {
var shapes = [];
drawnItems.eachLayer(function(layer) {
// Note: Rectangle extends Polygon. Polygon extends Polyline.
// Therefore, all of them are instances of Polyline
if (layer instanceof L.Polyline) {
shapes.push(layer.getLatLngs())
}
if (layer instanceof L.Circle) {
shapes.push([layer.getLatLng()])
}
if (layer instanceof L.Marker) {
shapes.push([layer.getLatLng()]);
}
});
return shapes;
};
map.on('draw:created', function (e) {
var type = e.layerType;
var layer = e.layer;
var shape = layer.toGeoJSON()
var shape_for_db = JSON.stringify(shape);
});
// restore
L.geoJSON(JSON.parse(shape_for_db)).addTo(mymap);
#Michael Evans method should work if you want to use GeoJSON.
If you want to save LatLngs points for each shape you could do something like this:
map.on('draw:created', function (e) {
var type = e.layerType;
var layer = e.layer;
var latLngs;
if (type === 'circle') {
latLngs = layer.getLatLng();
}
else
latLngs = layer.getLatLngs(); // Returns an array of the points in the path.
// process latLngs as you see fit and then save
}
Don't forget the radius of the circle
if (layer instanceof L.Circle) {
shapes.push([layer.getLatLng()],layer.getRadius())
}
PS that statement may not get the proper formatting but you see the point. (Or rather the radius as well as the point ;-)
Get shares as associative array + circle radius
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('Call Point!');
}
drawnItems.addLayer(layer);
var shapes = getShapes(drawnItems);
console.log("shapes",shapes);
});
var getShapes = function (drawnItems) {
var shapes = [];
shapes["polyline"] = [];
shapes["circle"] = [];
shapes["marker"] = [];
drawnItems.eachLayer(function (layer) {
// Note: Rectangle extends Polygon. Polygon extends Polyline.
// Therefore, all of them are instances of Polyline
if (layer instanceof L.Polyline) {
shapes["polyline"].push(layer.getLatLngs())
}
if (layer instanceof L.Circle) {
shapes["circle"].push([layer.getLatLng()])
}
if (layer instanceof L.Marker) {
shapes["marker"].push([layer.getLatLng()],layer.getRadius());
}
});
return shapes;
};
For me it worked this:
map.on(L.Draw.Event.CREATED, function (e) {
map.addLayer(e.layer);
var points = e.layer.getLatLngs();
puncte1=points.join(',');
puncte1=puncte1.toString();
//puncte1 = puncte1.replace(/[{}]/g, '');
puncte1=points.join(',').match(/([\d\.]+)/g).join(',')
//this is the field where u want to add the coordinates
$('#geo').val(puncte1);
});
For me it worked this:
after get coordinates send to php file with ajax then save to db
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
// Set the title to show on the polygon button
L.drawLocal.draw.toolbar.buttons.polygon = 'Draw a polygon!';
var drawControl = new L.Control.Draw({
position: 'topright',
draw: {
polyline: true,
polygon: true,
circle: true,
marker: true
},
edit: {
featureGroup: drawnItems,
remove: true
}
});
map.addControl(drawControl);
map.on(L.Draw.Event.CREATED, function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('');
}
drawnItems.addLayer(layer);
shape_for_db = layer.getLatLngs();
SEND TO PHP FILE enter code hereWITH AJAX
var form_data = new FormData();
form_data.append("shape_for_db",shape_for_db);
form_data.append("name", $('#nameCordinate').val());
$.ajax({
url: 'assets/map_create.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (php_script_response) {
var tmp = php_script_response.split(',');
alert(tmp );
}
});
});
map.on(L.Draw.Event.EDITED, function (e) {
var layers = e.layers;
var countOfEditedLayers = 0;
layers.eachLayer(function (layer) {
countOfEditedLayers++;
});
console.log("Edited " + countOfEditedLayers + " layers");
});
L.DomUtil.get('changeColor').onclick = function () {
drawControl.setDrawingOptions({rectangle: {shapeOptions: {color: '#004a80'}}});
};

knockout js polling not working

I am having difficulty with knockout refreshing.
Here's my viewModel;
$(document).ready(function () {
ko.applyBindings(new Task(), document.getElementById('taskSummary'));
setInterval(Task, 2000);
});
function task(name, description, project) {
var self = this;
self.name= ko.observable(name);
self.description = ko.observable(description);
self.project = ko.observable(project);
}
function Task() {
var self = this;
self.tasks = ko.observableArray([]);
self.tasks.removeAll;
$.getJSON("/api/tasks/5", function (data) {
$.each(data, function (key, val) {
self.tasks.push(new task(val.Name, val.Description, val.Project));
});
});
}
It returns data to the view but does not update when I change the data in the back end database.
any help appreciated. Im sure its something small that I'm missing.
For knockout, it might be better if you apply your model to a new Task instance, save that instance, then set up a setInterval loop that can modify the Task's "tasks" observableArray values.
$(document).ready(function () {
var oTask = new Task();
ko.applyBindings(oTask, document.getElementById('taskSummary'));
function onLoop() {
var self = oTask;
$.getJSON("/api/tasks/5", function (data) {
self.tasks.removeAll(); // not sure if you need this...
$.each(data, function (key, val) {
self.tasks.push(new task(val.Name, val.Description, val.Project));
});
});
}
setInterval(onLoop, 2000);
});

Combining AJAX/JSON call with iScroll

I am making a list form my JQM site from JSON data and are having no trouble with this. Now I want to add iScroll to the scene and if I use static list it works just fine, but when I get the list from JSON it won't fetch how many li I have and I can not scroll down to the bottom if I have lets say 20 li. I dont know how to combine my javascript so here is what i got so far [EDIT]:
var myScroll;
$(document).on('pageshow', function (){
var userid=1,
dataUrl = 'http://duefmun.dk/html5data/playermenu.php?callback=?&userid=' + userid,
dataCallback = function (data) {
var content = [];
$.each(data, function (i, val) {
content.push(val.list);
});
$('#games').html(content.join('')).listview('refresh');
},
fetchData = function () {
myScroll = new iScroll('wrapper');
if (myScroll.isReady()){
$.getJSON(dataUrl, dataCallback);
}
};
fetchData();
setInterval(fetchData, 20000);
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false);
});
Hope this makes sense and any help is appreciated :-)
EDIT: I have edited the post with something I think should be right but it is still not working? Please help :-/
My suggestion is that you should create iScroll after you get your data. So, your code should be:
...
fetchData = function () {
if (myScroll.isReady()){
$.getJSON(dataUrl, dataCallback);
}
};
fetchData();
setInterval(fetchData, 20000);
myScroll = new iScroll('wrapper');
...

Backbone using external js

Hi all I have a site developed in cakephp and I would to integrate backbone on it.
For my scope I would to use external js for backbone to reuse the code.
I have write some lines but I can't append results on my element.
I have tried to print the "el" in this modes:
console.log($(this.el));
console.log(this.el);
console.log(this.$el);
But nothing I can't enter into el to make a simple append!
The container #search-results already exist
This is my main view:
<script type="text/javascript">
var search = {};
search.product = {};
search.product.template = "#results-product-template";
search.product.container = "#search-results";
search.product.defaults = {
id:0,
type:"product",
};
$(function(){
var ProductList = new Search.Collections.Products();
var ProductView = new Search.Views.Product({
// new Search.Collections.Products();
collection:ProductList
,el:$("#search-results")
});
function parseResults () {
var json = {
//my data
}
for (var i = json.products.length - 1; i >= 0; i--) {
ProductList.add([new Search.Models.Product(json.products[i])]);
};
updateResults();
}
function updateResults () {
console.log('updateResults: Ritorno il risultato quando hunter riceve una risposta dal server');
if ($('#search-results').length == 0) {
$('div.main > section:first-child').before('<section id="search-results"> <ul id="product-results"> <li>Contenuto</li> </ul> </section>');
}
ProductView.render();
}
// search
$('#search-results .close').on('click', function () {
$('#search-results').animate({height:0}, 500, function () {
$(this).remove();
})
});
});
</script>
And this is my external js with backbone
var Search = {
Models: {},
Collections: {},
Views: {},
Templates:{}
}
Search.Models.Product = Backbone.Model.extend({
defaults: search.product.defaults || {},
toUrl:function (url) {
return url.replace(" ", "-").toLowerCase();
},
initialize:function () {
console.log("initialize Search.Models.Product");
this.on("change", function (){
console.log("chiamato evento change del Model Search.Models.Product");
});
this.on("change:text", function () {
console.log("chiamato evento change:text del Model Search.Models.Product");
});
}
});
Search.Collections.Products = Backbone.Collection.extend({
model: Search.Models.Product,
initialize:function () {
console.log("initialize Search.Collections.Products");
console.log(this);
console.log(this.length);
console.log(this.models);
}
});
Search.Views.Product = Backbone.View.extend({
initialize:function () {
console.log("initialize Search.Views.Product");
console.log($(search.product.template).html());
},
template:function (data) {
if (data == null) {
data = this.collection.toJSON();
}
var template = Handlebars.compile($(search.product.template).html());
template(data);
},
render:function () {
console.log($(this.el));
$(this.el.append("TEST"));
//HERE IS THE PROBLEM
// I have tried this.$el.append("TEST");
return this;
}
});
Does this change anything?
var ProductView = new Search.Views.Product({
// new Search.Collections.Products();
collection:ProductList,
el:$("#search-results")[0]
});
I think backbone can accept both jQuery wrapped or not wrapped object and be fine, but I don't know what Backbone version you are using, see if this works
EDIT: From backbone 1.0 sources, it seems backbone can indeed take either a jQuery wrapped object or a regular dom element, it should still work
this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
Do you have something online (JSFiddle?) I will be happy to take a look, but this.$el should work and be equal to $("#search-results") from your code in a quick glance.
Have you tried using ProductView.setElement($("#search-results")) instead? it should be the same, but worth a try as well.