JSFiddle - React, Tailwind, and code Playground
by grant
HTML
<link rel="stylesheet" href="https://openlayers.org/en/v6.4.3/css/ol.css">
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.4.3/build/ol.js"></script>
<div id="map" class="map"></div>
<label>
Sea level
<input id="level" type="range" min="100" max="200" value="1"/>
+<span id="output"></span> m
</label>
<br>
Go to
<a class="location" data-center="-117.226,32.83" data-zoom="11">San Diego</a>,
<a class="location" data-center="-122.3267,37.8377" data-zoom="11">San Francisco</a>,
<a class="location" data-center="-73.9338,40.6861" data-zoom="11">New York</a>,
<a class="location" data-center="72.9481,18.9929" data-zoom="11">Mumbai</a>, or
<a class="location" data-center="120.831,31.160" data-zoom="9">Shanghai</a>
CSS
html, body {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
}
.map {
height: 80%;
width: 100%;
}
#level {
display: inline-block;
width: 150px;
vertical-align: text-bottom;
}
a.location {
cursor: pointer;
}
JavaScript
/* Disable minification (remove `.min` from URL path) for more info */
function flood(pixels, data) {
var pixel = pixels[0];
if (pixel[3]) {
var height = -10000 + ((pixel[0] * 256 * 256 + pixel[1] * 256 + pixel[2]) * 0.1);
if (height <= data.level) {
pixel[0] = 145;
pixel[1] = 175;
pixel[2] = 186;
pixel[3] = 255;
} else {
pixel[3] = 0;
}
}
return pixel;
}
var key = 'pk.eyJ1IjoiZ2VvY29kZXppcCIsImEiOiJjaWdtcnQyZzUwMDNnbmtrb2VvaXBsbnJuIn0.5UtgXcNHBy6JvtXudUQ3sA';
var elevation = new ol.source.XYZ({
url: 'https://api.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}.pngraw?access_token=' + key,
crossOrigin: 'anonymous',
transition: 0
});
var raster = new ol.source.Raster({ // RasterSource({
sources: [elevation],
operation: flood
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({ // TileLayer({
/* source: new ol.source.XYZ({
url: 'https://api.mapbox.com/styles/v1/tschaub/ciutc102t00c62js5fqd47kqw/tiles/256/{z}/{x}/{y}?access_token=' + key
}) */
source: new ol.source.OSM()
}),
new ol.layer.Image({ // ImageLayer({
opacity: 0.6,
source: raster
})
],
view: new ol.View({
center: ol.proj.fromLonLat([-122.3267, 37.8377]),
// center: ol.proj.fromLonLat([-116.09685, 43.76377]),
zoom: 11
})
});
var control = document.getElementById('level');
var output = document.getElementById('output');
control.addEventListener('input', function() {
output.innerText = control.value;
raster.changed();
});
output.innerText = control.value;
raster.on('beforeoperations', function(event) {
event.data.level =...