I am working with the Vaadin framework (https://vaadin.com/home) integrating d3.js to my java code (analogous to http://www.rapidpm.org/2013/10/using-javascript-libraries-d3-in-vaadin.html). Basically, this Javascript code is bound to a Java class and reacts to a change of state in said Java class.
==================================================================================
So, when the state of the java diagram-class changes, this.conStateChange-method is called: javascript fetches a new String from the java class (var string = this.getState().string;), parses it to JSON and renders a graph.
A button click will trigger the state change by changing the String in the java class (!), thereby triggering the described method and rendering the new graph from the new JSON-parsed-String.
...THEORETICALLY... however, in reality, if I click that button once the graph disappears. Only if I click the button again, the new graph is rendered.
/*not so interesting code
var diagramElement = this.getElement();
var width = 960, height = 500;
var force = d3.layout.force().size([ width, height ])
.charge(-400)
.linkDistance(40)
.on("tick", tick);
var drag = force.drag()
.on("dragstart", dragstart);
var svg = d3.select(diagramElement)
.append("svg")
.attr("width", width)
.attr("height", height);
var link = svg.selectAll(".link"),
node = svg.selectAll(".node");*/
/*interesting code*/
this.onStateChange = function() {
link.remove(); //delete old graph
node.remove(); //delete old graph
var string = this.getState().string;
graph = JSON.parse(string);
force.nodes(graph.nodes).links(graph.links).start();
link = link.data(graph.links)
.enter().append("line")
.attr("class", "link");
node = node.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 12)
.on("dblclick", dblclick)
.call(drag);
};
So whats wrong with this (indeed not very elegant) code, and how can I achieve that a single click will [1] remove the graph displayed and [2] render a new graph?
Thanks in advance...
I'm not sure if you have found a solution and I'm still a noob in d3 but I would like to suggest as this solution helped me. However, my force layout derived its data from a csv and not JSON not sure if it makes much difference.
I included " graph = { "nodes": [], "links": [] }; " in the "this.onStateChange = function() {" as this will help fill up the arrays with new data. Hope it helps!
Related
I followed tutorial from this blog and want to create a tool like TransformationExtension.
I found that the model I selected was not immediately centered on the cursor and there was a gap when dragging it.
document.onmousemove = (event) => {
if (!event.ctrlKey) return;
let res = this.viewer.impl.hitTest(
event.clientX,
event.clientY,
true,
null,
[this.viewer.model.getModelId()]
);
let pt = null;
if (res) {
pt = res.intersectPoint;
} else {
pt = viewer.impl.intersectGround(event.clientX, event.clientY);
}
let tr = this.selectedModel.getPlacementTransform();
tr.elements[12] = pt.x;
tr.elements[13] = pt.y;
tr.elements[14] = pt.z;
this.selectedModel.setPlacementTransform(tr);
this.viewer.impl.invalidate(true, true, true);
};
As #AlexAR mentioned, when finding the cursor position relative to a specific DOM element using the clientX and clientY values, you have to remember subtracting the element's client bounding rect: Find mouse position relative to element.
Btw. I've recently built another sample Forge app that can be used to drag&drop new models into the viewer that you might find helpful: https://github.com/petrbroz/forge-assembly-configurator. The main drag&drop logic is implemented in the setupDragDrop function.
I know how to use the createAnchor to place a link in a panel, however I would like to launch a link from a button. Is this possible, if so how?
After some trail and error I found an easier way of achieving the goal.
I just create an image of the button showing my desired text and use thse setAttribute method of the anchor.
Unfortunally I stll require an AbsolutePanel.
function doGet()
{
// Problem with Google Apps :
// Not possible to click a Button and show a site
// Solutions found on StackOverflow mostly use :
// a) var panel = createAbsolutePanel --> Necessary to create an Absolute Panel
// b) var image = createImage --> The image to be shown
// c) var anchor = createAnchor --> Anchor making it possible to activate a url
// d) position the anchor on top of the image
// e) make anchor and image of same size
// f) make anchor invisible (by zIndex, opacity or visibility)
//
// One of the people showing how this works is http://stackoverflow.com/users/1368381/serge-insas who's
// efforts inspired me to have a look at other possibilities. (thanks !)
//
// Result : next step in making it easy to overcome a limitation of GAS --> no createImage required anymore
// How : using setAttribute('backgroundImage', Url) method of anchor
// Limitation : still required to create an Absolute panel instead of a Vertical panel --> who's next to improve ??
//
// Author : SoftwareTester, may 13th, 2014
var app = UiApp.createApplication().setTitle("Image Anchor");
var picButton = 'https://drive.google.com/uc?id=0BxjtiwHnjnkrTVJiR1g2SlZTLVE'; // Can on be accessed be a few people
var widthButton = 128;
var heightButton = 24;
var anchor = app.createAnchor("", "http://www.opasittardgeleen.nl")
.setHeight(heightButton).setWidth(widthButton)
// .setHeight("150").setWidth("128") // Nice effect !!
// .setHeight("150").setWidth("512") // Even more
.setStyleAttribute('backgroundImage', 'url(' + picButton + ')');
var panel = app.createAbsolutePanel().setWidth('50%').setHeight('50%');
panel.add(anchor,100,50); // I would like to avoid positioning like this and just add the anchor to a Grid or VerticalPanel
app.add(panel);
return app.close();
}
I have answered a similar post with a workaround that works nicely although it is, I admit, a bit complex in regard to what it does...
Here is a test app
and the code reproduced from the other post is below : I used an invisible anchor superimposed to the image but it could of course be anything else... a button or whatever you want.
function doGet(){
var app = UiApp.createApplication().setStyleAttribute("background", "#CCCCFF").setTitle('Anchor Test')
var top = '100PX';// define dimensions and position
var left = '100PX';
var width = '80PX';
var height = '80PX';
var mainPanel = app.createVerticalPanel();
var customAnchor = app.createHorizontalPanel().setId('usethisId')
addStyle(customAnchor,top,left,width,height,'1','1')
var image = app.createImage("https://dl.dropbox.com/u/211279/Time-change-clock_animated_TR80.gif")
addStyle(image,top,left,width,height,'1','1')
var realAnchor = app.createAnchor('This is the Anchor', 'https://sites.google.com/site/appsscriptexperiments/home')
addStyle(realAnchor,top,left,width,height,'2','0')
customAnchor.add(realAnchor);
customAnchor.add(image)
mainPanel.add(customAnchor);
app.add(mainPanel);
return app;
}
function addStyle(widget,top,left,width,height,z,visibility){
widget.setStyleAttributes(
{'position': 'fixed',
'top' : top,
'left' : left,
'width' : width,
'height':height,
'opacity' : visibility,
'zIndex' : z});
}
EDIT : I forgot to mention this post with a button example... exactly what you wanted : How do I open a web browser using google apps script?
EDIT 2
Following Software tester answer, here is a compact version that one can place in a grid or anywhere else... just place the widget called 'container'.
To illustrate I placed it in a grid in the example below/
link to test
code :
function doGet(){
var app = UiApp.createApplication().setTitle("Image Anchor");
var picButton = 'https://dl.dropboxusercontent.com/u/211279/ProgressSpinner.gif';
var img = app.createImage(picButton).setPixelSize(25,25);
var grid = app.createGrid(5,2);
for(n=0;n<5;n++){
grid.setText(n,0,'some text').setBorderWidth(1);
}
var anchor = app.createAnchor(" - ", "https://sites.google.com/site/appsscriptexperiments/").setStyleAttribute('opacity','0').setPixelSize(25,25);
var container = app.createAbsolutePanel().setPixelSize(25,25);
container.add(img,0,0).add(anchor,0,0);
grid.setWidget(4,1,container);
app.add(grid);
return app;
}
The answer EDIT 2 of Serge Insas provides extra flexibility using a grid.
Improving the world little by little by learning and using each others good ideas, also holds for software of course. Thanks again Serge!
I noticed a few differences that might or might not be of interest in certain situations.
I always try to specify constants (like width and height) and minimize using similar code like .setPixelSize(width, height) making it easier 'not to forget something while changing'. That's why I prefer to avoid creating a separate image object.
Serge Insas uses .setStyleAttribute('opacity','0'); while I'm using .setStyleAttribute('backgroundImage', url); . I don't know what are the pro's and con's of both possibilities.
Below is the generalized code
function doGet()
{ // Generalized version using : image + opacity + container
var app = UiApp.createApplication().setTitle("Image Anchor");
var width = 25;
var height = 25;
var urlImage = 'https://dl.dropboxusercontent.com/u/211279/ProgressSpinner.gif';
var urlAnchor = "https://sites.google.com/site/appsscriptexperiments/";
var grid = createImageAnchor(urlImage, urlAnchor, width, height);
app.add(grid);
return app;
}
and the function createImageAnchor can be
function createImageAnchor(urlImage, urlAnchor, width, height)
{ // Using backgroundImage
var app = UiApp.getActiveApplication();
var anchor = app.createAnchor("", urlAnchor).setPixelSize(width, height)
.setStyleAttribute('backgroundImage', 'url(' + urlImage + ')');
var panel = app.createAbsolutePanel().setPixelSize(width, height).add(anchor, 0, 0);
var grid = app.createGrid(1, 1).setWidget(0, 0, panel); // Create grid and put anchor in it
return grid;
}
or
function createImageAnchor(urlImage, urlAnchor, width, height)
{ // Using opacity
var = UiApp.getActiveApplication();
var image = app.createImage(urlImage).setPixelSize(width, height);
var anchor = app.createAnchor("", urlAnchor) .setPixelSize(width, height)
.setStyleAttribute('opacity','0');
var panel = app.createAbsolutePanel().setPixelSize(width, height)
.add(image, 0, 0).add(anchor, 0, 0); // Same position for image and anchor
var grid = app.createGrid(1, 1).setWidget(0, 0, panel); // Create grid and put image + anchor in it
return grid;
}
Using createImageAnchor makes it easier to use this 'combined object' anywhere in code, especially after adding it into a library.
As I'm new to GAS (started may 7th after 5 years of inactivity) I know I need to learn a lot and would like to know what the pro's and con's of different methods are.
I'm using Dart to develop a personal whiteboard Chrome app and it is sometimes useful to be able to quickly copy and paste an image (e.g. a slide from a presentation, a diagram or a handout) so that I can add notes over the image while teaching a class or giving a presentation.
How can I paste an image stored on the clipboard onto a canvas element in Dart?
Actually, this answer to the same question for JS is almost directly applicable. A Dart translation might look something like:
import 'dart:html';
void main() {
var can = new CanvasElement()
..width = 600
..height = 600
;
var con = can.getContext('2d');
document.onPaste.listen((e) {
var blob = e.clipboardData.items[0].getAsFile();
var reader = new FileReader();
reader.onLoad.listen((e) {
var img = new ImageElement()
..src = (e.target as FileReader).result;
img.onLoad.listen((_) {
con.drawImage(img, 0, 0);
});
});
reader.readAsDataUrl(blob);
});
document.body.children.add(can);
}
I am using OpenLayers to display dynamically loaded images. The code I am using is:
var map;
function init(strURL) {
map = new OpenLayers.Map('map');
var options = { numZoomLevels: 3,
isBaseLayer: true, };
var graphic = new OpenLayers.Layer.Image(
'City Lights',
strURL + "?sc=page",
new OpenLayers.Bounds(-180, -88.759, 180, 88.759),
new OpenLayers.Size(580, 288),
options
);
// graphic.events.on({
// loadstart: function () {
// OpenLayers.Console.log("loadstart");
// },
// loadend: function () {
// OpenLayers.Console.log("loadend");
// }
// });
var jpl_wms = new OpenLayers.Layer.WMS("NASA Global Mosaic",
"http://t1.hypercube.telascience.org/cgi-bin/landsat7",
{ layers: "landsat7" }, options);
map.addLayers([graphic, jpl_wms]);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.zoomToMaxExtent();
}
I am calling this function on a button click event and passing the strURL (sources of the images) at that time. The result is, with each click a different image is loaded and displayed on the web page but is not clearing the previous image. So I 5 different images on the webpage are shown with 5 clicks and so on.
My javascript knowledge is limited, so my apologies if this is a stupid question. How to stop this behavior? Thanks for any assistance.
Also, I didn't quite understand the lines:
var jpl_wms = new OpenLayers.Layer.WMS("NASA Global Mosaic",
"http://t1.hypercube.telascience.org/cgi-bin/landsat7",
{ layers: "landsat7" }, options);
But I know these lines are needed since I'm getting js error if I remove them.
So currently you are calling init(strURL) with each button click? Divide that code into two parts:
On page load, create map and layer objects
On button click, just update URL of existing image layer. Image layer has setUrl(url) method for that: http://dev.openlayers.org/apidocs/files/OpenLayers/Layer/Image-js.html#OpenLayers.Layer.Image.setUrl
Here is sample, that should explain it: http://jsfiddle.net/mEHrN/6/
About var jpl_wms = ... - it creates WMS layer, that should display Landsat imagery (but that URL doesn't seem to work). If you remove it, remember also to remove it from map.addLayers:
map.addLayers([graphic]);
Probably this was reason, why you got JS error.
i'm using OpenLayers to display custom OSM maps on my website.
I've some points to respect: the map have to be fix (meaning that we can't drag it or zoom it).
I have a problem with the zoom, i can't manage to disable zoom with the mouse. Does anyone has a tip?
map = new OpenLayers.Map('map');
map.events.remove("move");
map.events.remove("movestart");
map.events.remove("moveend");
map.events.remove("zoomend");
map.events.remove("mouseover");
map.events.remove("mouseout");
map.events.remove("mousemove");
map.events.remove("zoomstart");
var nav = new OpenLayers.Control.Navigation({
defaultDblClick: function(event) { return ; }
});
map[index].addControl(nav);
Also, if someone has a tip to remove all Navigation events easier than that, it would be greatly appreciated.
Disable the default controls on your map by passing an empty array:
var map = new OpenLayers.Map('map', { controls: [] });
For OpenLayers3 the interaction array also needs to be empty.
var map = new ol.Map({
controls: [],
interactions: []
});
Simplifying approach of Mahdi results in
var i, l, c = map.getControlsBy( "zoomWheelEnabled", true );
for ( i = 0, l = c.length; i < l; i++ ) {
c[i].disableZoomWheel();
}
This way disabling zoom on mouse wheel doesn't require to customize options on constructing map e.g. by creating map without any control (though this was somewhat requested by Lght). In addition re-enabling zoom works equivalently.
In addition, by searching controls matching enabled property zoomWheelEnabled rather than class name it's supporting custom controls derived from OpenLayers.Control.Navigation.
You can do the following also:
map = new OpenLayers.Map({
// options here ...
}
var Navigation = new OpenLayers.Control.Navigation({
'zoomWheelEnabled': false,
'defaultDblClick': function ( event ) {
return;
}
});
map.addControl(Navigation);
var NavigationControls = map.getControlsByClass('OpenLayers.Control.Navigation')
, i;
for ( i = 0; i < NavigationControls.length; i++ ) {
NavigationControls[i].disableZoomWheel();
}
Found here.
For other options like disable dragging, you can take a look at the documentation and customize the above code.
Here is another easy way to restrict the zoom event based on some logic. Because OpenLayers doesnt provide a 'beforezoom'
map.zoomToProxy = map.zoomTo;
map.zoomTo = function (zoom,xy){
// if you want zoom to go through call
map.zoomToProxy(zoom,xy);
//else do nothing and map wont zoom
};
How this works:
For any kind of zooming activity, OpenLayers API ultimately calls the function called zoomTo. So before overriding it, we copy that function to a new function called 'zoomToProxy'. The we override it and add our conditional zoom logic. If we want the zoom to happen we just call new proxy function :)
You could reset the controls array and then add the Zoom and TouchNavigation to it.
var map_controls = [];
map_controls.push( new OpenLayers.Control.Zoom() );
map_controls.push( new OpenLayers.Control.TouchNavigation() );
var map = new OpenLayers.Map({
div: "map",
controls: map_controls
});
Hope it helps ! :)