Openlayers map get layer group layer tile title and visibility status upon changing the visibility open layers - node.js

I'm new to open layers and currently trying to implement a map where i will display set of information when a layer has been check. currently i have this code to display the layer tiles
new LayerGroup({
title: 'Sample Layer Group',
fold: 'open',
layers: [
new Tile({
title: 'Layer 1',
visible: false,
source: new TileWMS({
url: '',
....
]
})
}),});
What i want to do is whenever i check or uncheck this layer I'll be able to get the state if it's visible or not.
I tried using map.getLayerGroup().getActive() but only receiving true every time.
thank you for the help!

If I understand you correctly, you are actually looking for getVisible method. Take a look at this example I made for you, based on some OL examples.
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.3.1/css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.3.1/build/ol.js"></script>
<title>Group Layer</title>
</head>
<body>
<div style="margin: 1rem;">
<input type="checkbox" id="groupVisible" checked>Group |
<input type="checkbox" id="layer1Visible" checked>Layer 1 |
<input type="checkbox" id="layer2Visible" checked>Layer 2
</div>
<div id="map" class="map"></div>
<script type="text/javascript">
const layer1 = new ol.layer.Tile({
source: new ol.source.TileWMS({
url: 'https://ahocevar.com/geoserver/wms',
params: {'LAYERS': 'ne:ne', 'TILED': true},
serverType: 'geoserver',
crossOrigin: 'anonymous'
})
});
const layer2 = new ol.layer.Tile({
extent: [-13884991, 2870341, -7455066, 6338219],
source: new ol.source.TileWMS({
url: 'https://ahocevar.com/geoserver/wms',
params: {'LAYERS': 'topp:states', 'TILED': true},
serverType: 'geoserver',
// Countries have transparency, so do not fade tiles:
transition: 0
})
});
const groupLayer = new ol.layer.Group({
layers: [layer1, layer2]
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
groupLayer
],
view: new ol.View({
center: [-10997148, 4569099],
zoom: 4
})
});
const groupChk = document.getElementById('groupVisible');
const layer1Chk = document.getElementById('layer1Visible');
const layer2Chk = document.getElementById('layer2Visible');
function log() {
console.log(
`group: ${groupLayer.getVisible()} layer1: ${layer1.getVisible()} layer2: ${layer2.getVisible()}`
);
}
groupChk.addEventListener('click', function () { groupLayer.setVisible(groupChk.checked); log(); });
layer1Chk.addEventListener('click', function () { layer1.setVisible(layer1Chk.checked); log(); });
layer2Chk.addEventListener('click', function () { layer2.setVisible(layer2Chk.checked); log(); });
</script>
</body>
</html>
Let me know if this is what you were looking for.

Related

Openlayer Map - Only shows after page refresh

Just about to launch a new hobby website. All working well apart from the maps! When a page containing a map first loads, the map typically doesn't show, instead it just shows a blank space and then a number of white rows/narrow bars. If I refresh the page, it works OK. Any ideas?
Thank you!
<div style="text-align:center">
<div id="search_map" class="map img-responsive" style="height: 30rem;width:100%;max-width:500px;text-align:center;margin: 0 auto;"></div>
<div id="popupmap" class="ol-popup" style="background-color: white;box-shadow: 0 1px 4px rgba(0,0,0,0.2);
border-width: 10px;padding: 8px;border-radius: 10px;border: 1px solid #cccccc;font-size: 8px;text-align:center" >
<div id="popup-contentmap"></div>
</div>
</div>
<script type="text/javascript">
var map = new ol.Map({
target: 'search_map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([<%= #record.long %>,<%= #record.lat %>]),
zoom: 15
})
});
{
var container1 = document.getElementById('popupmap');
var content1 = document.getElementById('popup-contentmap');
var overlay1 = new ol.Overlay({
element: container1
});
map.addOverlay(overlay1);
content1.innerHTML = '<p class="normaltext" style="padding:0px;margin:0px;font-size:8px;"><%= image_tag("photo.jpg", :size => "20x20", :crop => :fill, :style => "") %> <%= #record.eateryname %>' + '</p>';
overlay1.setPosition(ol.proj.fromLonLat([<%= #record.long %>,<%= #record.lat %>]));
}
var layer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [
new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([<%= #record.long %>,<%= #record.lat %>]))
})
]
})
});
map.addLayer(layer);
map.updateSize();
</script>
You can try wrapping the map initialization code in a function and calling that function after the DOM has finished loading.
window.onload = function() {
var map = new ol.Map({
target: 'search_map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([<%= #record.long %>,<%= #record.lat %>]),
zoom: 15
})
});
};

Cytoscape Cola Layout: How to restart the layout without any change of positions?

I'm trying to use the Cytoscape cola layout to render a graph that should apply a force directed layout while using it (so when dragging nodes around, they should act as if there is some gravity involved).
Relevant libraries:
https://github.com/cytoscape/cytoscape.js
https://github.com/tgdwyer/WebCola
https://github.com/cytoscape/cytoscape.js-cola
My first problem is that adding nodes to the graph via add(node) doesn't include them in the cola layout algorithm. The only way I found around that is to destroy the layout, re-initialize it and start it again. But this causes the nodes to jump in some cases.
I assumed that this was due to the fact that I completely destroyed the old layout but when setting up a minimal example, I realized that even just calling layout.stop() and layout.run() leads to nodes being repositioned.
In the following example, there is only one node. Moving the node via drag and drop, then pressing the "stop" button and then the "start" button causes the node to jump back to its initial position:
document.addEventListener('DOMContentLoaded', function(){
// Register cola layout
cytoscapeCola(cytoscape);
var nodes = [{ data: { id: 1, name: 1 } }]
var edges = [];
var cy = window.cy = cytoscape({
container: document.getElementById('cy'),
style: [
{
selector: 'node[name]',
style: {
'content': 'data(name)'
}
},
{
selector: 'edge',
style: {
'curve-style': 'bezier',
'target-arrow-shape': 'triangle'
}
},
],
elements: {
nodes: nodes,
edges: edges
}
});
var layout = cy.layout({
name: 'cola',
infinite: true,
fit: false,
});
layout.run();
document.querySelector('#start').addEventListener('click', function() {
layout.run();
});
document.querySelector('#stop').addEventListener('click', function() {
layout.stop();
});
document.querySelector('#add-node').addEventListener('click', function() {
var id = Math.random();
cy.add({ group: 'nodes', data: { id: id, name: id } });
cy.add({ group: 'edges', data: { source: id, target: _.head(nodes).data.id } });
layout.stop();
layout.destroy();
layout = cy.layout({
name: 'cola',
infinite: true,
fit: false,
});
layout.run();
});
});
body {
font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
font-size: 14px;
}
#cy {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 999;
}
h1 {
opacity: 0.5;
font-size: 1em;
font-weight: bold;
}
#buttons {
position: absolute;
right: 0;
bottom: 0;
z-index: 99999;
}
<!DOCTYPE>
<html>
<head>
<title>cytoscape-edgehandles.js demo for infinite layout</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
<script src="https://unpkg.com/webcola/WebCola/cola.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/cytoscape-cola#2.4.0/cytoscape-cola.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
<script src="cytoscape-edgehandles.js"></script>
</head>
<body>
<h1>cytoscape-edgehandles demo with an infinite layout</h1>
<div id="cy"></div>
<div id="buttons">
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="add-node">Add Node</button>
</div>
</body>
</html>
Is this a bug or am I doing something wrong? Does anyone know how to stop and restart the layout without the nodes changing their position?
Thanks a lot,
Jesse
Okay actually you were very close #Stephan.
The problem was that WebCola centers the nodes when calling start by default:
https://github.com/tgdwyer/WebCola/blob/78a24fc0dbf0b4eb4a12386db9c09b087633267d/src/layout.ts#L504
The cytoscape wrapper for WebCola does not currently support this option, so I forked it and added the option myself:
https://github.com/deje1011/cytoscape.js-cola/commit/f357b97aba900327e12f97b1530c4df624ff9d61
I'll open a pull request at some point.
Now you can smoothly restart the layout like this:
layout.stop();
layout.destroy(); // cleanup event listeners
layout = graph.layout({ name: 'cola', infinite: true, fit: false, centerGraph: false });
layout.run()
This way, the nodes keep their position 🎉

Is it possible to change color of one pixel inside rectangle created with KineticJS?

This is my code:
var Editor = {
layer: new Kinetic.Layer(),
map: null,
init: function () {
var stage = new Kinetic.Stage({
container: 'board',
width: 800,
height: 800
})
this.map = new Kinetic.Shape({
sceneFunc: function(context) {
context.beginPath();
context.moveTo(0, 0);
context.lineTo(mapWidth, 0);
context.lineTo(mapWidth, mapHeight);
context.lineTo(0, mapHeight);
context.closePath();
context.fillStrokeShape(this);
},
x: 0,
y: 0,
fill: 'green',
draggable: true
})
this.layer.add(this.map)
stage.add(this.layer)
}
}
I want to change the colors of the pixels in the rectangle. Colors of pixels will be generated by the "diamond-square" algorithm. Is it possible to change the colors of individual pixels? If so, how can I do this?
[ Changed answer ]
Use an offscreen html canvas to overlay the pixels in your "diamond-square" algorithm.
Demo: http://jsfiddle.net/m1erickson/6mDSm/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.1.min.js"></script>
<style>
body{padding:20px;}
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:350px;
height:350px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
var mapWidth=50;
var mapHeight=75;
// use an offscreen canvas as a pixel-map overlaying the green map
var pixelCanvas=document.createElement("canvas");
var ctx=pixelCanvas.getContext("2d");
pixelCanvas.width=mapWidth;
pixelCanvas.height=mapHeight;
pixelCanvas.pixels=[]
pixelCanvas.setPixel=function(x,y,color){
ctx.fillStyle=color;
ctx.fillRect(x,y,1,1);
};
// create a group
// that holds the green map background and pixel-map overlay
var mapGroup=new Kinetic.Group({
x:30,
y:30,
width:mapWidth,
height:mapHeight,
draggable:true
});
layer.add(mapGroup);
// the green background
var map=new Kinetic.Rect({
x:0,
y:0,
width:mapWidth,
height:mapHeight,
fill:"green"
});
mapGroup.add(map);
// an image overlay that
// gets "live-updates" from an offscreen canvas
var pixels=new Kinetic.Image({
x:0,
y:0,
image:pixelCanvas
});
mapGroup.add(pixels);
layer.draw();
// testing
var y=15;
$("#add").click(function(){
for(var i=0;i<5;i++){
pixelCanvas.setPixel(15,y,"red");
pixelCanvas.setPixel(25,y,"gold");
pixelCanvas.setPixel(35,y++,"blue");
}
pixels.draw();
});
}); // end $(function(){});
</script>
</head>
<body>
<button id="add">Add test Pixels</button>
<div id="container"></div>
</body>
</html>
Note: my previous answer using Kinetic.Shape was leaving an undesirable "ghost"

fusion table can not show two layers if we add different styles to the two layers

Due to the limit of 5 fusion table layers and 5 styles of one fusion table layer, I have to try it as: use 5 fusion table layers and each one use two styles, then I can get to my purpose: show 10 different styles in a map.
But after I implemented, I found it only show the first fusion table layer.
Then I wrote a testing case to check why. And found:
If we set styles in two layers, only the first layer can be displayed and the second one is gone. If I set style for one layer, it works well.
Below is my code, can someone help on it? Now only one layer is displayed. If we comment the style setting for them or one of them, both layers can be displayed.
Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#top-box {padding: 10px; background-color:#336699;}
.para-line {font-weight:bold;}
#map_canvas { height: 100% }
</style>
<script type="text/javascript"src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
map = new google.maps.Map(document.getElementById("map_canvas"));
map.setMapTypeId('roadmap');
map.setCenter(new google.maps.LatLng(38.4985464, -98.3834298));
map.setZoom(4);
var tableid1 = 4436842;
var style = [{
where: "State in('IL','PA')",
polygonOptions:
{
fillColor: "#rrggbb",
fillOpacity: 0.7
}
},{
where: "State in('AL')",
polygonOptions:
{
fillColor: "#006400",
fillOpacity: 0.7
}
}
];
var query1 = {
select: ['geometry','name'],
from: tableid1,
where: "State in('IL','PA')"
}
var query2 = {
select: ['geometry','name'],
from: tableid1,
where: "State in('AL')"
}
var layer1 = new google.maps.FusionTablesLayer({
query:query1,
styles: style,
suppressInfoWindows: false,
clickable:true
});
layer1.setMap(map);
var layer2 = new google.maps.FusionTablesLayer({
query:query2,
styles:style,
suppressInfoWindows: false,
clickable:true
});
layer2.setMap(map);
return;
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
The limit is (from the documentation "You can use the Maps API to add up to five Fusion Tables layers to a map, one of which can be styled with up to five styling rules."
You can style the layers using the FusionTable User Interface, but only one can be styled dynamically and that one can only have 5 styling rules.

How to create a "carousel"-like widget in spotify apps API?

Is it possible using the spotify apps API to create one of these widgets filled with my data of choice?
Yes, by using import/scripts/pager. Here's an example, extracted and simplified from the "What's New" app. Your pager.js:
"use strict";
sp = getSpotifyApi(1);
var p = sp.require('sp://import/scripts/pager');
var dom = sp.require('sp://import/scripts/dom');
exports.init = init;
function init() {
var pagerSection = dom.queryOne('#pager');
var datasource = new DataSource([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
var options = {
perPage: 5,
hidePartials: true,
orientation: 'vertical', // 'vertical', 'horizontal'
pagingLocation: 'top', // 'top', 'bottom'
bullets: false,
listType: 'list', // 'table', 'list'
context: 'aToplist' // some string unique for each pager
};
var pager = new p.Pager(datasource, options);
pager.h2.innerHTML = "Example Pager";
dom.adopt(pagerSection, pager.node);
}
function DataSource(data) {
var data = data;
this.count = function() {
return data.length;
};
this.makeNode = function(index) {
var dataItem = data[index];
var li = new dom.Element('li');
var nameColumn = new dom.Element('div', {
className: 'nameColumn',
html: '<div class="nameColumn">'+
'Name' + dataItem + ''+
'Creator' + dataItem +''+
'</div>'
});
dom.adopt(li, nameColumn);
return li;
};
}
Your index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="pager.css">
</head>
<body onload="sp = getSpotifyApi(1); sp.require('pager').init();">
<div id="wrapper">
<section class="toplists" id="bottomToplists">
<section id="pager" class="playlists playlistsTable toplist"></section>
</section>
</div>
</body>
</html>
And lastly, copy the whatsnew.css into your project and rename it to pager.css. You will of course need to clean up the css and modify the elements in your index.html to fit with your app but this is a good starting point.
The "What's New" app also has an example of a horizontal pager with album artwork. Take a look at this question and answer to figure out how to extract the source of the app.
Also note that I am not sure whether the pager.js will be part of the public API. If not then you can of course extract it into your own pager widget and use it anyway.

Resources