ol-ext/examples/layer/map.layer.hexbin.html
2024-06-26 16:24:06 +02:00

465 lines
14 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<!--
Copyright (c) 2017-2018 Jean-Marc VIGLINO,
released under CeCILL-B (french BSD like) licence: http://www.cecill.info/
-->
<title>ol-ext: HexBin source</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="ol.source.HexBin is a source to display hexagonal binning on a map." />
<meta name="keywords" content="ol3, layer, hexbin, cluster, hexagon, binning, heatmap" />
<!-- jQuery -->
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<!-- FontAwesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Openlayers -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@latest/ol.css" />
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/ol@latest/dist/ol.js"></script>
<!-- ol-ext -->
<link rel="stylesheet" href="../../dist/ol-ext.css" />
<script type="text/javascript" src="../../dist/ol-ext.js"></script>
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<script src="https://unpkg.com/elm-pep"></script>
<!-- filesaver-js -->
<script type="text/javascript" src="https://cdn.rawgit.com/eligrey/FileSaver.js/aa9f4e0e/FileSaver.min.js"></script>
<link rel="stylesheet" href="../style.css" />
<style>
input {
vertical-align: middle;
}
#legend{
background: #fff;
padding: 0.5em 1em;
}
#legend li {
padding-left: 0.5em;
}
#legend li:first-child {
padding: 0 0 0.5em;
}
.legend {
display: inline-block;
width: 2em;
height: 1.5em;
vertical-align: middle;
background-color: orange;
}
.legend.mini {
background-color: green;
}
.legend.maxi {
background-color: #800;
}
.gradient .legend {
background-color: rgba(0,0,255, 0.25);
}
.gradient .legend.mini {
background-color: rgba(0,0,255, 0.05);
}
.gradient .legend.maxi {
background-color: rgba(0,0,255, 0.5);
}
.point .legend {
position: relative;
height: 1.3em;
margin: 0.1em 0;
background-color: rgba(0,0,255,0.5);
transform: scale(0.4);
}
.point .legend:before,
.point .legend:after {
content:"";
display: block;
position: absolute;
border-color: rgba(0,0,255,0.5) transparent;
border-width: 0.5em 1em;
border-style: solid;
}
.point .legend:before {
top: 100%;
border-bottom: 0;
}
.point .legend:after {
bottom: 100%;
border-top: 0;
}
.point .legend.mini {
transform: scale(0.2);
}
.point .legend.maxi {
transform: scale(0.7);
}
#map {
width: 600px;
height: 400px;
}
.fullscreen #map {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
}
.fullscreen .options {
position: fixed;
top: 0;
right: 0;
}
.fullscreen .info:last-child,
.fullscreen #legend {
display: none;
}
.waiting {
opacity: .5;
}
.waiting:before {
content: "Calculating...";
background: #fff;
padding: 1em;
font-size: 2em;
top: 30%;
left: 50%;
position: fixed;
transform: translate(-50%,-30%);
z-index: 999;
box-shadow: 1px 1px 2px 2px;
}
.fa-arrows-alt {
float: right;
cursor: pointer;
}
button {
font-size: 1em;
color: #fff;
background: #369;
border: 0;
padding: .2em 1em;
}
input[type="number"] {
width: 5em;
}
</style>
</head>
<body >
<a href="https://github.com/Viglino/ol-ext" class="icss-github-corner"><i></i></a>
<a href="../../index.html">
<h1>ol-ext: HexBin source</h1>
</a>
<div class="info">
Hexagonal binning is a convenient way for aggregating data into a coarser representation for display.
<br/>
In an hexbin map (hexagonal heatmap) features are scattered on hexagons.
<br/>
Hexbins can support a color encoding or point encoding.
You can use the color, density of the hexagon or its size to display
the value of the features aggregated in the hexagon.
<ul>
<li>
<i>ol.source.HexBin</i> is a ol.source.Vector, similar to a ol.source.Cluster
</li>
<li>
<i>ol.source.ImageHexBin</i> is a ol.source.ImageVector, more efficient to use with large data sets.
</li>
<li>
HexBin use a <i>ol.HexGrid</i> to compute hexagonal grid.
<br/>
For more information on hexgrid metrics, see
<a href="https://viglino.github.io/ol-games/examples/map.hexmap.html">the Hexmap example</a>.
</li>
</ul>
</div>
<!-- Map DIV -->
<div id="map"></div>
<div class="options">
<i class="fa fa-arrows-alt" title="fullscreen" onclick="$('body').toggleClass('fullscreen'); map.updateSize();"></i>
<h2>Options:</h2>
<ul>
<li>
Hexagon size: <input id="size" type="range" min="1000" max="300000" value="100000" onchange="reset();" step="1000" />
<button onclick="$('#size').attr('type')==='range' ? $('#size').attr('type','number') : $('#size').attr('type','range');">
<i class="fa fa-keyboard-o"></i> slide/number
</button>
</li>
<li>
Style:
<select id="style" onchange="hexbin.changed(); $('#legend').removeClass().addClass($(this).val())">
<option value="color">Color</option>
<option value="gradient">Gradient</option>
<option value="point">Point</option>
</select>
</li>
<li>
<input id="image" type="checkbox" onchange="reset()"/><label for="image"> layer image</label>
</li>
<li>
<div class="info">
<input id="showsource" type="checkbox" onchange="layerSource.setVisible($(this).prop('checked')); modify.setActive($(this).prop('checked'));" /><label for="showsource">
Display source features and move them around to see what happens to the bin!
</label>
</div>
</li>
<li>
<button onclick='save()'><i class="fa fa-download"></i> download result</button>
</li>
</ul>
<div>
<ul id="legend">
<li>
Legend:
</li>
<li>
<div class="legend mini"></div>
<span class="min"></span>-
</li>
<li>
<div class="legend"></div>
<span class="min"></span> - <span class="max"></span>
</li>
<li>
<div class="legend maxi"></div>
<span class="max"></span>+
</li>
<li>
Interval: <input class="interval imin" type="number"/>-<input class="interval imax" type="number"/>
</li>
</ul>
</div>
<div class="info">Selection: <span>0</span> feature(s)</div>
<div class="info">
<i class="fa fa-upload"></i> Drag'n'drop .geojson to calculate on your data!
<br/>
<label>
<input id="add" type="checkbox" />
add features when dropped
</label>
</div>
</div>
<div id="image"><img/></div>
<script type="text/javascript">
var osm = new ol.layer.Tile({ title: 'OSM', source: new ol.source.OSM() });
osm.addFilter(new ol.filter.Colorize({ operation: 'grayscale' }))
// The map
var map = new ol.Map({
target: 'map',
view: new ol.View({
zoom: 4,
center: [166326, 5992663]
}),
layers: [ osm ]
});
var select = new ol.interaction.Select();
map.addInteraction(select);
select.on('select', function(e){
if (e.selected.length){
var f = e.selected[0].get('features');
if (f) $(".options .info span").text(e.selected[0].get('features').length);
else $(".options .info span").text("0");
}
else $(".options .info span").text("0");
});
// Create a set of features on seed points
function addFeatures(nb){
var ssize = 20; // seed size
var ext = map.getView().calculateExtent(map.getSize());
var dx = ext[2]-ext[0];
var dy = ext[3]-ext[1];
var dl = Math.min(dx,dy);
var features=[];
for (var i=0; i<nb/ssize; ++i){
var seed = [ext[0]+dx*Math.random(), ext[1]+dy*Math.random()]
for (var j=0; j<ssize; j++){
var f = new ol.Feature(new ol.geom.Point([
seed[0] + dl/10*Math.random(),
seed[1] + dl/10*Math.random()
]));
f.set('id',i*ssize+j);
features.push(f);
}
}
source.clear(true);
source.addFeatures(features);
}
// Print control
/*
var printControl = new ol.control.Print({ copyToClipboard: true });
printControl.on('print', function(e) {
printControl.toClipboard(e, function(b) {
if (b) console.log('Map has been copied...')
});
});
map.addControl(printControl);
*/
// Vector source
var source = new ol.source.Vector();
// add 2000 features
addFeatures(2000);
// Interaction to move the source features
var modify = new ol.interaction.Modify({ source: source });
modify.setActive(false);
map.addInteraction(modify);
var layerSource = new ol.layer.Vector({ title: 'Source', source: source, visible:false })
map.addLayer(layerSource);
var hexbin, layer, binSize;
var style = $("#style");
var min, max, maxi;
var minRadius = 1;
var styleFn = function(f,res){
switch (style.val()){
// Display a point with a radius
// depending on the number of objects in the aggregate.
case 'point':{
var radius = Math.round(binSize/res +0.5) * Math.min(1,f.get('features').length/max);
if (radius < minRadius) radius = minRadius;
return [ new ol.style.Style({
image: new ol.style.RegularShape({
points: 6,
radius: radius,
fill: new ol.style.Fill({ color: [0,0,255] }),
rotateWithView: true
}),
geometry: new ol.geom.Point(f.get('center'))
})
//, new ol.style.Style({ fill: new ol.style.Fill({color: [0,0,255,.1] }) })
];
}
// Display the polygon with a gradient value (opacity)
// depending on the number of objects in the aggregate.
case 'gradient': {
var opacity = Math.min(1,f.get('features').length/max);
return [ new ol.style.Style({ fill: new ol.style.Fill({ color: [0,0,255,opacity] }) }) ];
}
// Display the polygon with a color
// depending on the number of objects in the aggregate.
case 'color':
default: {
var color;
if (f.get('features').length > max) color = [136, 0, 0, 1];
else if (f.get('features').length > min) color = [255, 165, 0, 1];
else color = [0, 136, 0, 1];
return [ new ol.style.Style({ fill: new ol.style.Fill({ color: color }) }) ];
}
}
};
// Create HexBin and calculate min/max
function reset() {
var size = Number($('#size').val());
if (layer) map.removeLayer(layer);
binSize = size;
var features;
hexbin = new ol.source.HexBin({
source: source, // source of the bin
size: size // hexagon size (in map unit)
});
var vClass = ($("#image").prop('checked') ? ol.layer.VectorImage : ol.layer.Vector)
layer = new vClass({
title: 'Bin',
source: hexbin,
opacity: .5,
style: styleFn
});
features = hexbin.getFeatures();
// Calculate min/ max value
min = Infinity;
max = 0;
for (var i=0, f; f = features[i]; i++) {
var n = f.get('features').length;
if (n<min) min = n;
if (n>max) max = n;
}
var dl = (max-min);
maxi = max;
min = Math.max(1,Math.round(dl/4));
max = Math.round(max - dl/3);
$(".min").text(min);
$(".max").text(max);
$('.imin').val(min);
$('.imax').val(max);
// Add layer
map.addLayer(layer);
}
reset (Number($("#size").val()));
$('.interval').on('change', function() {
min = Number($('.imin').val()) || min;
max = Number($('.imax').val()) || max;
$(".min").text(min);
$(".max").text(max);
hexbin.changed();
})
// Add feature on drop
var dd = new ol.interaction.DropFile();
map.addInteraction (dd);
dd.on('loadstart', function () { $('body').addClass('waiting'); });
dd.on('loadend', function () { $('body').removeClass('waiting'); });
dd.on ('addfeatures', function(event) {
var f = event.features;
if (!$("#add").prop('checked')) {
source.clear(true);
}
source.addFeatures(f);
});
// Save
function save () {
var format = new ol.format.GeoJSON();
var hexa = layer.getSource().getHexFeatures();
if (style.val()==='point'){
var size = hexa[0].getGeometry().getExtent();
size = map.getView().getResolution() / (size[2]-size[0]) ;
var minVal = minRadius * size;
console.log(minVal)
hexa.forEach(function(f){
var radius = Math.min(1,f.get('nb')/max);
if (radius < minVal) {
console.log(radius, minVal)
radius = minVal;
}
var geom = f.getGeometry().getCoordinates()[0];
var center = ol.extent.getCenter(f.getGeometry().getExtent());
geom.forEach(function(p) {
p[0] = center[0] + (p[0]-center[0])*radius;
p[1] = center[1] + (p[1]-center[1])*radius;
});
f.setGeometry(new ol.geom.Polygon([geom]));
});
}
var data = format.writeFeatures(hexa, {
dataProjection: 'EPSG:4326',
featureProjection: map.getView().getProjection()
});
var blob = new Blob([data], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hexmap.geojson");
}
</script>
</body>
</html>