Get extent of geoJSON file - javascript

I am using the following code to calculate the extent of as KMLfile. How do I do this with a GeoJSON file?
let layer=new KMLLayer({ url:url });
map.add(app.layer);
app.mapView.whenLayerView(layer).then(function(layerView) {
watchUtils.whenFalseOnce(layerView, "updating", function() {
let polygons=layerView.allVisiblePolygons;
let lines=layerView.allVisiblePolylines;
let points=layerView.allVisiblePoints;
let images=layerView.allVisibleMapImages;
let extent=polygons.concat(lines).concat(points).concat(images)
.map(graphic => (graphic.extent ? graphic.extent : graphic.geometry.extent))
.reduce((previous, current) => previous.union(current));
});

You just need to use queryExtent of the GeoJSONLayerView. Take a look the example I made for you based on one of ArcGIS.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="initial-scale=1,maximum-scale=1,user-scalable=no"
/>
<title>GeoJSONLayer - 4.15</title>
<style>
html,
body,
#viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
p {
font: 1rem 'Fira Sans', sans-serif;
}
#extentSpan {
color:crimson;
font-style: italic;
}
</style>
<link
rel="stylesheet"
href="https://js.arcgis.com/4.15/esri/themes/light/main.css"
/>
</head>
<body>
<p>Extent: <span id="extentSpan">...</span></p>
<div id="viewDiv"></div>
<script src="https://js.arcgis.com/4.15/"></script>
<script>
require([
"esri/Map",
"esri/layers/GeoJSONLayer",
"esri/views/MapView"
], function(Map, GeoJSONLayer, MapView) {
const renderer = {
type: "simple",
field: "mag",
symbol: {
type: "simple-marker",
color: "orange",
outline: {
color: "white"
}
},
visualVariables: [
{
type: "size",
field: "mag",
stops: [
{
value: 2.5,
size: "4px"
},
{
value: 8,
size: "40px"
}
]
}
]
};
const geojsonLayer = new GeoJSONLayer({
url:
"https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson",
copyright: "USGS Earthquakes",
renderer: renderer
});
const map = new Map({
basemap: "gray",
layers: [geojsonLayer]
});
const view = new MapView({
container: "viewDiv",
center: [-168, 46],
zoom: 3,
map: map
});
view.whenLayerView(geojsonLayer).then(function(layerView) {
layerView.watch("updating", function(val) {
if (!val) {
layerView.queryExtent().then(function(response) {
const e = response.extent;
view.goTo(e);
document.querySelector('#extentSpan').textContent =
`${e.xmin} ${e.ymin} ${e.xmax} ${e.ymax}`;
});
}
});
});
});
</script>
</body>
</html>

Related

Showing Browse Features window on popup instead of Summary

I’m working with Arcgis version 4.25 (javascript) and using cluster. I used the sample https://developers.arcgis.com/javascript/latest/sample-code/sandbox/?sample=featurereduction-cluster and want to show Browse Features content window on opening popup instead of showing summary.
How can I do that programmatically?
enter image description here
Basically, you have to query the layer view with the aggregatedId. The aggregated id is the objectId of the selected cluster feature.
Here I put an example for you using the esri sample you use as base. The key part, is when the CustomContent is render (the creator method).
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<title>
Point clustering - basic configuration | Sample | ArcGIS Maps SDK for
JavaScript 4.25
</title>
<style>
html,
body,
#viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
background: rgba(50, 50, 50);
}
#infoDiv {
padding: 10px;
}
</style>
<link rel="stylesheet" href="https://js.arcgis.com/4.25/esri/themes/dark/main.css" />
<script src="https://js.arcgis.com/4.25/"></script>
<script>
require([
"esri/Map",
"esri/layers/FeatureLayer",
"esri/layers/GeoJSONLayer",
"esri/views/MapView",
"esri/widgets/Legend",
"esri/widgets/Expand",
"esri/widgets/Home",
"esri/popup/content/CustomContent"
], (Map, FeatureLayer, GeoJSONLayer, MapView, Legend, Expand, Home, CustomContent) => {
const layer = new GeoJSONLayer({
title: "Earthquakes from the last month",
url: "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson",
copyright: "USGS Earthquakes",
outFields: ["*"],
popupTemplate: {
title: "Magnitude {mag} {type}",
content: "Magnitude {mag} {type} hit {place} on {time}"
},
renderer: {
type: "simple",
field: "mag",
symbol: {
type: "simple-marker",
size: 4,
color: "#69dcff",
outline: {
color: "rgba(0, 139, 174, 0.5)",
width: 5
}
}
}
});
const baseLayer = new FeatureLayer({
portalItem: {
id: "2b93b06dc0dc4e809d3c8db5cb96ba69"
},
legendEnabled: false,
popupEnabled: false,
renderer: {
type: "simple",
symbol: {
type: "simple-fill",
color: [65, 65, 65, 1],
outline: {
color: [50, 50, 50, 0.75],
width: 0.5
}
}
},
spatialReference: {
wkid: 5936
}
});
const map = new Map({
layers: [baseLayer, layer]
});
const view = new MapView({
container: "viewDiv",
extent: {
spatialReference: {
wkid: 5936
},
xmin: 1270382,
ymin: -1729511,
xmax: 2461436,
ymax: -953893
},
spatialReference: {
// WGS_1984_EPSG_Alaska_Polar_Stereographic
wkid: 5936
},
constraints: {
minScale: 15469455
},
map: map
});
view.popup.viewModel.includeDefaultActions = false;
view.whenLayerView(layer).then(lv => {
const layerView = lv;
const customContentPromise = new CustomContent({
outFields: ["*"],
creator: (event) => {
const query = layerView.createQuery();
query.aggregateIds = [event.graphic.getObjectId()];
console.log(query);
return layerView.queryFeatures(query).then(result => {
console.log(result.features);
const contentDiv = document.createElement("div");
const featuresUl = document.createElement("ul");
let featureLi;
for (const feature of result.features) {
featureLi = document.createElement("li");
featureLi.innerText = `Magnitude ${feature.attributes.mag} ${feature.attributes.type} hit ${feature.attributes.place} on ${feature.attributes.time}`;
featuresUl.appendChild(featureLi);
}
contentDiv.appendChild(featuresUl);
return contentDiv
});
}
});
const clusterConfig = {
type: "cluster",
clusterRadius: "100px",
popupTemplate: {
title: "Cluster summary",
outFields: ["*"],
content: [customContentPromise],
actions: []
},
clusterMinSize: "24px",
clusterMaxSize: "60px",
labelingInfo: [
{
deconflictionStrategy: "none",
labelExpressionInfo: {
expression: "Text($feature.cluster_count, '#,###')"
},
symbol: {
type: "text",
color: "#004a5d",
font: {
weight: "bold",
family: "Noto Sans",
size: "12px"
}
},
labelPlacement: "center-center"
}
]
};
layer.featureReduction = clusterConfig;
const toggleButton = document.getElementById("cluster");
toggleButton.addEventListener("click", () => {
let fr = layer.featureReduction;
layer.featureReduction =
fr && fr.type === "cluster" ? null : clusterConfig;
toggleButton.innerText =
toggleButton.innerText === "Enable Clustering"
? "Disable Clustering"
: "Enable Clustering";
});
});
view.ui.add(
new Home({
view: view
}),
"top-left"
);
const legend = new Legend({
view: view,
container: "legendDiv"
});
const infoDiv = document.getElementById("infoDiv");
view.ui.add(
new Expand({
view: view,
content: infoDiv,
expandIconClass: "esri-icon-layer-list",
expanded: false
}),
"top-left"
);
});
</script>
</head>
<body>
<div id="viewDiv"></div>
<div id="infoDiv" class="esri-widget">
<button id="cluster" class="esri-button">Disable Clustering</button>
<div id="legendDiv"></div>
</div>
</body>
</html>

esri popupTemplate modify

How can i modify the popupTemplate in esri? is it possible for me to modify the popupTemplate according to my design?
I have a popupTemplate
popupTemplate: {
content: [{
type: "fields",
fieldInfos: [{
fieldName: "Name"
}, {
fieldName: "Owner"
}, {
fieldName: "Length"
}]
}]
}
this is the result
what i want design
resource https://totalapis.github.io/sample-code/popup-custom-action/index.html
Update, I am having trouble on my react , when i clicked the icon there is no popup template show
useEffect(() => {
if (mapDiv.current) {
esriConfig.apiKey = process.env.ARCGIS_API;
const map = new Map({
basemap: 'arcgis-light-gray'
});
const view = new MapView({
center: [123.5504, 12.3574], // Longitude, latitude
container: mapDiv.current,
map: map,
zoom: 13, // Zoom level
});
view
.when((r) => {})
.then(() => {
mapDiv.current = view;
setMapView(view);
});
var list= [{
type: "fields",
fieldInfos: [{
fieldName: "Name "
}, {
fieldName: "Owner"
}, {
fieldName: "Length"
}]
},
{
type: "text",
text: "<div class=\"icontain\"></><a class=\"ic\"><i class=\"bi bi-star\"></i></a><a class=\"ic\"><i class=\"bi bi-geo-alt-fill\"></i></a></div>"
}]
var Stack= {
content: list
}
var featureLayer = new FeatureLayer({
url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/ArcGIS/rest/services/Beverly%20Hills%20Trees%20By%20Block/FeatureServer/0",
popupTemplate: Stack,
outFields: ["*"]
});
map.add(featureLayer);
}
}, []);
const displayLocation = (locations) => {
mapView.center = [
locations.data[0].geoCode.longitude,
locations.data[0].geoCode.latitude,
];
locations.data.map((location) => {
const point = new Graphic({
geometry: {
latitude: location.geoCode.latitude,
longitude: location.geoCode.longitude,
type: 'point',
},
symbol: LocationPin,
});
mapView.graphics.add(point);
});
};
return <div className="mapDiv layers" ref={mapDiv}></div>;
}
Hello, a quick solution to modify the Popup template is to add another object with text and text type properties to the template array. the text value will be html code where we will create a div that will show the icons, these with their respective css classes. The most is CSS. Here is an example of the Popup template:
popupTemplate: {[{
type: "fields",
fieldInfos: [{
fieldName: "Name "
}, {
fieldName: "Owner"
}, {
fieldName: "Length"
}]
},
{
type: "text",
text: "<div class=\"icontain\"></><a class=\"ic\"><i class=\"bi bi-star\"></i></a><a class=\"ic\"><i class=\"bi bi-geo-alt-fill\"></i></a></div>"
}]
}
I put an example of this code in operation already with the css, for a better compression. Your remaining task is to play with CSS to make the icon div responsive. For a better visualization of the example, run it in full screen. Another detail is that the example takes time to load due to the multiple CDNs that it needs
require([
"esri/Map",
"esri/views/MapView",
"esri/layers/FeatureLayer",
"dojo/domReady!"
], function(Map, MapView, FeatureLayer) {
// Create the Map
var map = new Map({
basemap: "streets-navigation-vector"
});
var view = new MapView({
container: "mapDiv",
map: map,
center: [-118.399400711028, 34.08713590709093],
zoom: 16,
// Since there are many elements, it is best to dock the popup so
// the elements display better rather than have to scroll through them all.
popup: {
dockEnabled: true,
dockOptions: {
buttonEnabled: false,
breakpoint: false
}
}
});
var list= [{
type: "fields",
fieldInfos: [{
fieldName: "Name "
}, {
fieldName: "Owner"
}, {
fieldName: "Length"
}]
},
{
type: "text",
text: "<div class=\"icontain\"></><a class=\"ic\"><i class=\"bi bi-star\"></i></a><a class=\"ic\"><i class=\"bi bi-geo-alt-fill\"></i></a></div>"
}]
var Stack= {
content: list
}
var featureLayer = new FeatureLayer({
url: "https://services.arcgis.com/V6ZHFr6zdgNZuVG0/ArcGIS/rest/services/Beverly%20Hills%20Trees%20By%20Block/FeatureServer/0",
popupTemplate: Stack,
outFields: ["*"]
});
map.add(featureLayer);
});
html,
body,
#mapDiv {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
.esri-popup__main-container{
border: solid 1px gray;
border-radius: 10px;
}
.icontain{
position: absolute;
top: 0;
height: 100%;
left: -17px;
display: flex;
flex-direction: column;
/* margin-top: auto; */
/* margin-bottom: auto; */
/* align-items: center; */
justify-content: center;
}
.ic{
border: solid 1px gray;
border-radius: 50%;
width: 33px;
height: 33px;
display: flex;
justify-content: center;
align-items: center;
background: white;
margin-top: 4px;
margin-bottom: 4px;
}
<!DOCTYPE html>
<html dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"
/><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.7.2/font/bootstrap-icons.css">
<title>Multiple popup elements - 4.4</title>
<link rel="stylesheet" href="https://js.arcgis.com/4.4/esri/css/main.css">
<link rel="stylesheet" href="https://js.arcgis.com/4.4/dijit/themes/claro/claro.css">
<script src="https://js.arcgis.com/4.4/"></script></head>
<body>
<div id="mapDiv"></div>
</body>
</html>
Update
run this code in your environment. The popup should appear, you should only add the styles
useEffect(() => {
if (mapDiv.current) {
esriConfig.apiKey = process.env.ARCGIS_API_KEY;
const map = new Map({
basemap: 'arcgis-light-gray', // Basemap layer service
// portalItem:{
// id: "2d11c8164ce04843a38bfde68e00e6e7"
// }
});
const view = new MapView({
center: [123.5504, 12.3574], // Longitude, latitude
container: mapDiv.current,
map: map,
zoom: 13, // Zoom level
});
view
.when((r) => {})
.then(() => {
mapDiv.current = view;
setMapView(view);
});
}
}, []);
const displayLocation = (locations) => {
mapView.center = [
locations.data[0].geoCode.longitude,
locations.data[0].geoCode.latitude,
];
locations.data.map((location) => {
const point = new Graphic({
geometry: {
latitude: location.geoCode.latitude,
longitude: location.geoCode.longitude,
type: 'point',
},
symbol: LocationPin,
popupTemplate: {
title: "Sample",
content: [{
type: "fields",
fieldInfos: [{
fieldName: "Name"
}, {
fieldName: "Owner"
}, {
fieldName: "Length"
}]
},{
type: "text",
text: "<div class=\"icontain\"></><a class=\"ic\"><i class=\"bi bi-star\"></i></a><a class=\"ic\"><i class=\"bi bi-geo-alt-fill\"></i></a></div>"
}]
}
});
mapView.graphics.add(point);
});
};
update css for button close
.esri-popup__header-buttons{
position: absolute;
top: 100px;
margin: 0;
left: -17px;
padding: 0;
background: white;
border-radius: 50%;
border: solid 1px;
width: 32px;
height: 32px;
display: flex;
justify-content: center;
align-items: center;
}
.esri-popup__button {
z-index: 10;
}
try with this class and styles, to customize the close button

Code doesn't work after updating chart.js versioning

I have this great code working here where I load the data in from an external file called test.csv.
Everything works great until I try to update the chart.js library link.
Can anyone tell me why this code doesn't work with more current versions of chart.js?
I want to update it so that I can install the plugin that lets you show the charts values. Alternatively some code that would facilitate this would work great as well!
Appreciate any help!
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Data project</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<div class="wrapper">
<h1>MY CHART</h1>
<h2>This is the subhead for my chart </h2>
<canvas id="myChart" width="350" height="250" style="background-color:white;"></canvas>
</div>
<script>
window.addEventListener('load', setup);
async function setup() {
var ctx = document.getElementById('myChart').getContext('2d');
var dollar = await getData();
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: dollar.years,
datasets: [
{
label: 'Voter support (%)',
data: dollar.vals,
backgroundColor: [
'#134D85',
'#134D85',
'#134D85',
'#134D85',
'#134D85',
],
}]
},
options: {
layout: {
padding: {
left: 0,
right: 0,
top: 8,
bottom: 0
}
},
responsive: true,
title: {
display: false
},
legend: {
display: true,
position: 'top',
usePointStyle: true,
padding: 1,
labels: {
boxWidth: 15,
}
},
scales: {
yAxes: [{
gridlines: {
display: true,
color: '#ffffff',
zeroLineColor: '#ffffff',
}
}],
xAxes: [{
gridLines: {
display: true,
drawOnChartArea: false
},
}],
}
}
});
}
async function getData() {
// const response = await fetch('testdata.csv');
var response = await fetch('data/test.csv');
var data = await response.text();
data = data.replace(/"/g, "");
var years = [];
var vals = [];
var rows = data.split('\n').slice(1);
rows = rows.slice(0, rows.length - 1);
rows = rows.filter(row => row.length !== 0)
rows.forEach(row => {
var cols = row.split(",");
years.push(cols[0]);
vals.push(0 + parseFloat(cols[1]));
});
console.log(years, vals);
return { years, vals };
}
</script>
</body>
</html><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Coding Train: Data and APIs Project 1</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<div class="wrapper">
<h1>MY CHART</h1>
<h2>This is the subhead for my chart </h2>
<canvas id="myChart" width="350" height="250" style="background-color:white;"></canvas>
</div>
<script>
// Data from: https://data.giss.nasa.gov/gistemp/
// Mean from: https://earthobservatory.nasa.gov/world-of-change/DecadalTemp
window.addEventListener('load', setup);
async function setup() {
var ctx = document.getElementById('myChart').getContext('2d');
var dollar = await getData();
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: dollar.years,
datasets: [
{
label: 'Voter support (%)',
data: dollar.vals,
backgroundColor: [
'#134D85',
'#134D85',
'#134D85',
'#134D85',
'#134D85',
],
}]
},
options: {
layout: {
padding: {
left: 0,
right: 0,
top: 8,
bottom: 0
}
},
responsive: true,
title: {
display: false
},
legend: {
display: true,
position: 'top',
usePointStyle: true,
padding: 1,
labels: {
boxWidth: 15,
}
},
scales: {
yAxes: [{
gridlines: {
display: true,
color: '#ffffff',
zeroLineColor: '#ffffff',
}
}],
xAxes: [{
gridLines: {
display: true,
drawOnChartArea: false
},
}],
}
}
});
}
async function getData() {
// const response = await fetch('testdata.csv');
var response = await fetch('data/test.csv');
var data = await response.text();
data = data.replace(/"/g, "");
var years = [];
var vals = [];
var rows = data.split('\n').slice(1);
rows = rows.slice(0, rows.length - 1);
rows = rows.filter(row => row.length !== 0)
rows.forEach(row => {
var cols = row.split(",");
years.push(cols[0]);
vals.push(0 + parseFloat(cols[1]));
});
console.log(years, vals);
return { years, vals };
}
</script>
</body>
</html>```
For a start next time might be a good idea to read the documentation and the migration guide.
Few things that are at least wrong:
Link name has changed to lower case so 2.9.4/Chart.js -> 3.5.0/chart.js
Scales have changed from 2 arrays to objects for each scale:
options: {
scales: {
x: {
// config for default x scale
},
x2: {
// config for second x scale
},
y: {
// config for default y scale
},
}
}
title and legend config have been moved to the plugins section so options.title -> options.plugins.title and options.legend -> options.plugins.legend.
Alternativly you could also just use an older release of the datalabels plugin that has been written for V2
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/1.0.0/chartjs-plugin-datalabels.js"></script>

Cytoscape.js Show/Hide labels on elements in the graph on button click

I have a node application using cytoscape v3.15.2. I have the styling set as follows
let cy = cytoscape({
container: document.getElementById('graph-div'),
style: [
{
selector: 'node',
style: {
'label': 'data(id)',
}
},
{
selector: 'edge',
style: {
'label': (ele) => {
if(ele.data('type') === '1') return 'data(category1)';
if(ele.data('type') === '2') return 'data(category2)';
return value;
}
}]
});
Now, using a checkbox, I am trying to show/hide the labels on the elements. I have tried doing the following:
cy.elements().style("label","");
But this doesnt work. The same thing works when I pass a random string instead an empty string, something like this : cy.elements().style("label","random");. Doing this sets the labels of all elements in the graph to hidden. Could you please help me how to do this. Thanks
You can manage showing/hiding labels by specifying a class in the stylesheet and then toggling it on button click as in the below example.
var cy = window.cy = cytoscape({
container: document.getElementById('cy'),
layout: {name: 'grid', rows: 2},
style: [{
selector: '.hasLabel',
css: {
'label': (ele) => {
if(ele.isNode()) return ele.data('id');
if(ele.isEdge()) return ele.data('weight');
}
}
}
],
elements: {
nodes: [{
data: {
id: 'n0'
}
},
{
data: {
id: 'n1'
}
},
{
data: {
id: 'n2'
}
},
{
data: {
id: 'n3'
}
}
],
edges: [{
data: {
id: 'n0n1',
source: 'n0',
target: 'n1',
weight: 3
}
},
{
data: {
id: 'n1n2',
source: 'n1',
target: 'n2',
weight: 5
}
},
{
data: {
id: 'n2n3',
source: 'n2',
target: 'n3',
weight: 7
}
}
]
}
});
document.getElementById("labelButton").addEventListener("click", function() {
cy.elements().toggleClass('hasLabel');
});
body {
font: 14px helvetica neue, helvetica, arial, sans-serif;
}
#button {
z-index = 1000;
}
#cy {
height: 95%;
width: 95%;
left: 0;
top: 50;
z-index = 900;
position: absolute;
}
<html>
<head>
<meta charset=utf-8 />
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
<script src="https://unpkg.com/cytoscape#3.10.0/dist/cytoscape.min.js">
</script>
</head>
<body>
<button id="labelButton" type="button">Show/Hide Labels</button>
<div id="cy"></div>
</body>
</html>

Can a edge in cytoscape have multiple colors

I am trying to create a edge with multiple colors, not sure how to go about it.
Ideally each half of the link would have their color updated independently.
Want to know if this is feasible.
Thanks a lot
:)
Looks like it is! Check https://js.cytoscape.org/#style/edge-line and https://js.cytoscape.org/#style/gradient.
The strategy would be to break the line-gradient into color-stop positions, each with an associated color like this:
var cy = (window.cy = cytoscape({
container: document.getElementById("cy"),
boxSelectionEnabled: false,
autounselectify: true,
style: [{
selector: "node",
css: {
"label": "data(id)",
"text-valign": "center",
"text-halign": "center",
"background-color": "data(faveColor)"
}
},
{
selector: "edge",
css: {
"line-fill": "radial-gradient",
"line-gradient-stop-colors": "red green blue",
"line-gradient-stop-positions": "25 50 75"
}
}
],
elements: {
nodes: [{
data: {
id: "a",
faveColor: "#2763c4"
}
},
{
data: {
id: "b",
faveColor: "#37a32d"
}
},
{
data: {
id: "c",
faveColor: "#37a32d"
}
}
],
edges: [{
data: {
source: "a",
target: "b"
}
},
{
data: {
source: "a",
target: "c"
}
}
]
},
layout: {
name: "dagre"
}
}));
cy.ready(function() {
cy.dblclick();
});
var nid = 0;
cy.bind('dblclick', function(evt) {
console.log('dblclick');
cy.add({
group: 'nodes',
data: {
id: nid,
faveColor: 'red'
},
position: {
x: evt.x,
y: evt.y
}
});
nid++;
});
cy.bind('click', 'node', function(evt) {
console.log('node clicked: ', evt.target.id());
});
body {
font: 14px helvetica neue, helvetica, arial, sans-serif;
}
#cy {
height: 100%;
width: 100%;
float: right;
position: absolute;
}
<html>
<head>
<meta charset=utf-8 />
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
<script src="https://unpkg.com/cytoscape#3.3.0/dist/cytoscape.min.js">
</script>
<!-- cyposcape dagre -->
<script src="https://unpkg.com/dagre#0.7.4/dist/dagre.js"></script>
<script src="https://cdn.rawgit.com/cytoscape/cytoscape.js-dagre/1.5.0/cytoscape-dagre.js"></script>
<script src="https://unpkg.com/cytoscape-dblclick/dist/index.js"></script>
</head>
<body>
<div id="cy"></div>
</body>
</html>

Categories