Created
December 1, 2022 23:11
-
-
Save chriswhong/f2cac4cc2181c1045bc1d466ced95b48 to your computer and use it in GitHub Desktop.
Mapbox Scrollytelling Example with Linestring Animation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.testCallback = () => { | |
let startTime; | |
const duration = 10000; | |
const frame = (time) => { | |
if (!startTime) startTime = time; | |
const animationPhase = (time - startTime) / duration; | |
// Reduce the visible length of the line by using a line-gradient to cutoff the line | |
// animationPhase is a value between 0 and 1 that reprents the progress of the animation | |
map.setPaintProperty("my-linestring-line", "line-gradient", [ | |
"step", | |
["line-progress"], | |
"red", | |
animationPhase, | |
"rgba(0, 0, 0, 0)" | |
]); | |
if (animationPhase > 1) { | |
return; | |
} | |
window.requestAnimationFrame(frame); | |
}; | |
window.requestAnimationFrame(frame); | |
} | |
var config = { | |
style: 'mapbox://styles/branigan/cjzsvonse027m1co4nkxp13b3', | |
accessToken: 'pk.eyJ1IjoibWJ4c29sdXRpb25zIiwiYSI6ImNrMm01aG9hdTBlZGwzbXQ1ZXVrNHNmejAifQ.QHQA0N6XPWddCXtvoODHZg', | |
showMarkers: false, | |
theme: 'light', | |
title: '', | |
subtitle: '', | |
byline: '', | |
footer: '', | |
chapters: [ | |
{ | |
id: 'phl', | |
alignment: 'right', | |
title: 'Philadelphia Bicycle Infrastructure', | |
image: '', | |
description: 'Getting around Philadelphia on two wheels is fast, fun, and cheap. As a typical East Coast large city, the urban core is dense, so there is a lot within reach of a 15 minute ride... even mountain bike trails. Paired with the public transit infrastructure, cycling can be more efficient and much less expensive than driving (and parking) a car.', | |
location: { | |
center: [-75.13080, 39.97790], | |
zoom: 9.83, | |
pitch: 0.00, | |
bearing: 0.00 | |
}, | |
onChapterEnter: [ | |
{ | |
layer: 'phl-city-limits', | |
opacity: .45 | |
}, | |
{ | |
layer: 'my-linestring-line', | |
opacity: 0 | |
} | |
], | |
onChapterExit: [ | |
{ | |
layer: 'phl-city-limits', | |
opacity: 0 | |
} | |
] | |
}, | |
{ | |
id: 'bike-lanes', | |
alignment: 'right', | |
title: 'Bike Lanes', | |
image: '', | |
description: 'Philadelphia has XX miles of bike lanes, XX miles of which are protected. Drivers are getting more used to sharing the road, but ride defensively.', | |
location: { | |
center: [-75.13901, 39.97085], | |
zoom: 11.62, | |
pitch: 55.50, | |
bearing: -7.20 | |
}, | |
onChapterEnter: [ | |
{ | |
layer: 'phl-bike-network', | |
opacity: 1 | |
}, | |
{ | |
layer: 'my-linestring-line', | |
opacity: 0.8 | |
} | |
], | |
onChapterExit: [], | |
rotateAnimation: true, | |
callback: 'testCallback' | |
}, | |
{ | |
id: 'indego', | |
alignment: 'right', | |
title: 'Indego Bike Share', | |
image: '', | |
description: 'Indego has been operating in Philadelphia since 20XX. The system initally was focused on Center City, but has expanded service to neighboring areas to support equitable mobility options to the city\'s residents.', | |
location: { | |
center: [-75.16468, 39.94503], | |
zoom: 13.15, | |
pitch: 60.00, | |
bearing: -16.80 | |
}, | |
onChapterEnter: [ | |
{ | |
layer: 'indego-stations', | |
opacity: 0.8 | |
} | |
], | |
onChapterExit: [ | |
{ | |
layer: 'indego-stations', | |
opacity: 0 | |
} | |
] | |
}, | |
{ | |
id: 'belmont', | |
alignment: 'right', | |
title: 'Belmont Plateau Trails', | |
image: '', | |
description: 'A short ride along the Schuylkill River Trail from the Art Museum, Belmont is a twisty, log-ridden rollercoaster of a trail network. It is easy to get turned around, the underbrush is at times impenetrable, and short steep sections come out of nowhere. In other words, it\'s really fun', | |
location: { | |
center: [-75.20325, 39.99574], | |
zoom: 14.99, | |
pitch: 44.00, | |
bearing: -40.00 | |
}, | |
onChapterEnter: [ | |
{ | |
layer: 'belmont', | |
opacity: 1 | |
} | |
], | |
onChapterExit: [ | |
{ | |
layer: 'belmont', | |
opacity: 0 | |
} | |
] | |
}, | |
{ | |
id: 'wiss', | |
alignment: 'right', | |
title: 'Wissahickon Park Trails', | |
image: '', | |
description: 'This steep, rocky gorge can be surprisingly technical. Follow the orange and yellow trails to repeatedly climb and descend through the schist hillsides (careful of the cliffs), or stick to the gravel Forbidden Drive for a relaxing ride along the creek. You\'ll forget you\'re in a city.', | |
location: { | |
center: [-75.21223, 40.05028], | |
zoom: 13.08, | |
pitch: 47.50, | |
bearing: 32.80 | |
}, | |
onChapterEnter: [ | |
{ | |
layer: 'wissahickon', | |
opacity: 1 | |
} | |
], | |
onChapterExit: [ | |
{ | |
layer: 'wissahickon', | |
opacity: 0 | |
} | |
] | |
}, | |
{ | |
id: 'pennypack', | |
alignment: 'right', | |
title: 'Pennypack Park Trails', | |
image: '', | |
description: 'Pennypack is a great introduction trail system. Not too steep and not too technical, the beautiful wooded park also provides a great escape from urban life. The south side trails are originally bridle trails, so be nice to equestrians and dismount when you approach them.', | |
location: { | |
center: [-75.05685, 40.06839], | |
zoom: 13.73, | |
pitch: 43.50, | |
bearing: 96.80 | |
}, | |
onChapterEnter: [ | |
{ | |
layer: 'pennypack', | |
opacity: 1 | |
} | |
], | |
onChapterExit: [ | |
{ | |
layer: 'pennypack', | |
opacity: 0 | |
} | |
] | |
} | |
], | |
onLoad: () => { | |
map.addSource('my-linestring', { | |
type: 'geojson', | |
lineMetrics: true, | |
data: | |
{ | |
"type": "Feature", | |
"properties": {}, | |
"geometry": { | |
"coordinates": [ | |
[ | |
-75.16397984494239, | |
39.951646746011164 | |
], | |
[ | |
-75.16523115022339, | |
39.952030438496166 | |
], | |
[ | |
-75.16506430951928, | |
39.9535651869125 | |
], | |
[ | |
-75.16331248212602, | |
39.95350123974967 | |
], | |
[ | |
-75.16239485825321, | |
39.953053607933526 | |
], | |
[ | |
-75.16264511930964, | |
39.95171069490789 | |
], | |
[ | |
-75.1636461635342, | |
39.95171069490789 | |
], | |
[ | |
-75.1653145705751, | |
39.951902541240315 | |
], | |
[ | |
-75.16506430951928, | |
39.9535651869125 | |
], | |
[ | |
-75.16498088916691, | |
39.95458833339106 | |
], | |
[ | |
-75.16639903515203, | |
39.95497200937447 | |
], | |
[ | |
-75.17006953064201, | |
39.957657680991076 | |
], | |
[ | |
-75.17015295099439, | |
39.958233168329684 | |
], | |
[ | |
-75.1712374155713, | |
39.95836105374727 | |
], | |
[ | |
-75.17690999951037, | |
39.963028707812896 | |
], | |
[ | |
-75.17665973845457, | |
39.964051712707516 | |
], | |
[ | |
-75.17699341986274, | |
39.96494682943393 | |
], | |
[ | |
-75.17957945077644, | |
39.9673763729015 | |
], | |
[ | |
-75.16072645121228, | |
39.96686489724141 | |
], | |
[ | |
-75.15780673889037, | |
39.97901141031275 | |
], | |
[ | |
-75.17223745203674, | |
39.98061257870182 | |
], | |
[ | |
-75.17048562464345, | |
39.979398052993446 | |
], | |
[ | |
-75.16548040352008, | |
39.971087561112796 | |
], | |
[ | |
-75.16030834169328, | |
39.966740132046965 | |
], | |
[ | |
-75.15905703641226, | |
39.96405481714797 | |
], | |
[ | |
-75.15755547007548, | |
39.961944852876655 | |
], | |
[ | |
-75.15521970021818, | |
39.95861992855268 | |
], | |
[ | |
-75.14879633310976, | |
39.95804444446844 | |
], | |
[ | |
-75.14203928459376, | |
39.95612612921113 | |
], | |
[ | |
-75.14112166072094, | |
39.95503906001247 | |
], | |
[ | |
-75.14112166072094, | |
39.95164985101479 | |
], | |
[ | |
-75.14203928459376, | |
39.94826047407301 | |
], | |
[ | |
-75.16397883718327, | |
39.950754560220105 | |
] | |
], | |
"type": "LineString" | |
} | |
} | |
}) | |
map.addLayer({ | |
id: 'my-linestring-line', | |
type: 'line', | |
source: 'my-linestring', | |
paint: { | |
'line-color': "rgba(0,0,0,0)", | |
'line-width': 8, | |
'line-opacity': 0.8 | |
} | |
}) | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset='utf-8' /> | |
<title>Mapbox Storytelling</title> | |
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' /> | |
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v2.0.0/mapbox-gl.js'></script> | |
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v2.0.0/mapbox-gl.css' rel='stylesheet' /> | |
<script src="https://unpkg.com/intersection-observer@0.5.1/intersection-observer.js"></script> | |
<script src="https://unpkg.com/scrollama"></script> | |
<style> | |
body { | |
margin:0; | |
padding:0; | |
font-family: sans-serif; | |
} | |
a, a:hover, a:visited { | |
color: #0071bc; | |
} | |
#map { | |
top:0; | |
height: 100vh; | |
width:100vw; | |
position: fixed; | |
} | |
#header { | |
margin: auto; | |
width: 100%; | |
position: relative; | |
z-index: 5; | |
} | |
#header h1, #header h2, #header p { | |
margin: 0; | |
padding: 2vh 2vw; | |
text-align: center; | |
} | |
#footer { | |
width: 100%; | |
min-height: 5vh; | |
padding-top: 2vh; | |
padding-bottom: 2vh; | |
text-align: center; | |
line-height: 25px; | |
font-size: 13px; | |
position: relative; | |
z-index: 5; | |
} | |
#features { | |
padding-top: 10vh; | |
padding-bottom: 10vh; | |
} | |
.hidden { | |
visibility: hidden; | |
} | |
.centered { | |
width: 50vw; | |
margin: 0 auto; | |
} | |
.lefty { | |
width: 33vw; | |
margin-left: 5vw; | |
} | |
.righty { | |
width: 33vw; | |
margin-left: 62vw; | |
} | |
.fully { | |
width: 100%; | |
margin: auto; | |
} | |
.light { | |
color: #444; | |
background-color: #fafafa; | |
} | |
.dark { | |
color: #fafafa; | |
background-color: #444; | |
} | |
.step { | |
padding-bottom: 50vh; | |
/* margin-bottom: 10vh; */ | |
opacity: 0.25; | |
} | |
.step.active { | |
opacity: 0.9; | |
} | |
.step div { | |
padding: 25px 50px; | |
line-height: 25px; | |
font-size: 13px; | |
} | |
.step img { | |
width: 100%; | |
} | |
@media (max-width: 750px) { | |
.centered, .lefty, .righty, .fully { | |
width: 90vw; | |
margin: 0 auto; | |
} | |
} | |
/* Fix issue on mobile browser where scroll breaks */ | |
.mapboxgl-canvas-container.mapboxgl-touch-zoom-rotate.mapboxgl-touch-drag-pan, | |
.mapboxgl-canvas-container.mapboxgl-touch-zoom-rotate.mapboxgl-touch-drag-pan .mapboxgl-canvas { | |
touch-action: unset; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="map"></div> | |
<div id="story"></div> | |
<script src="./config.js"></script> | |
<script> | |
var initLoad = true; | |
var layerTypes = { | |
'fill': ['fill-opacity'], | |
'line': ['line-opacity'], | |
'circle': ['circle-opacity', 'circle-stroke-opacity'], | |
'symbol': ['icon-opacity', 'text-opacity'], | |
'raster': ['raster-opacity'], | |
'fill-extrusion': ['fill-extrusion-opacity'], | |
'heatmap': ['heatmap-opacity'] | |
} | |
var alignments = { | |
'left': 'lefty', | |
'center': 'centered', | |
'right': 'righty', | |
'full': 'fully' | |
} | |
function getLayerPaintType(layer) { | |
var layerType = map.getLayer(layer).type; | |
return layerTypes[layerType]; | |
} | |
function setLayerOpacity(layer) { | |
var paintProps = getLayerPaintType(layer.layer); | |
paintProps.forEach(function(prop) { | |
var options = {}; | |
if (layer.duration) { | |
var transitionProp = prop + "-transition"; | |
options = { "duration": layer.duration }; | |
map.setPaintProperty(layer.layer, transitionProp, options); | |
} | |
map.setPaintProperty(layer.layer, prop, layer.opacity, options); | |
}); | |
} | |
var story = document.getElementById('story'); | |
var features = document.createElement('div'); | |
features.setAttribute('id', 'features'); | |
var header = document.createElement('div'); | |
if (config.title) { | |
var titleText = document.createElement('h1'); | |
titleText.innerText = config.title; | |
header.appendChild(titleText); | |
} | |
if (config.subtitle) { | |
var subtitleText = document.createElement('h2'); | |
subtitleText.innerText = config.subtitle; | |
header.appendChild(subtitleText); | |
} | |
if (config.byline) { | |
var bylineText = document.createElement('p'); | |
bylineText.innerText = config.byline; | |
header.appendChild(bylineText); | |
} | |
if (header.innerText.length > 0) { | |
header.classList.add(config.theme); | |
header.setAttribute('id', 'header'); | |
story.appendChild(header); | |
} | |
config.chapters.forEach((record, idx) => { | |
var container = document.createElement('div'); | |
var chapter = document.createElement('div'); | |
if (record.title) { | |
var title = document.createElement('h3'); | |
title.innerText = record.title; | |
chapter.appendChild(title); | |
} | |
if (record.image) { | |
var image = new Image(); | |
image.src = record.image; | |
chapter.appendChild(image); | |
} | |
if (record.description) { | |
var story = document.createElement('p'); | |
story.innerHTML = record.description; | |
chapter.appendChild(story); | |
} | |
container.setAttribute('id', record.id); | |
container.classList.add('step'); | |
if (idx === 0) { | |
container.classList.add('active'); | |
} | |
chapter.classList.add(config.theme); | |
container.appendChild(chapter); | |
container.classList.add(alignments[record.alignment] || 'centered'); | |
if (record.hidden) { | |
container.classList.add('hidden'); | |
} | |
features.appendChild(container); | |
}); | |
story.appendChild(features); | |
var footer = document.createElement('div'); | |
if (config.footer) { | |
var footerText = document.createElement('p'); | |
footerText.innerHTML = config.footer; | |
footer.appendChild(footerText); | |
} | |
if (footer.innerText.length > 0) { | |
footer.classList.add(config.theme); | |
footer.setAttribute('id', 'footer'); | |
story.appendChild(footer); | |
} | |
mapboxgl.accessToken = config.accessToken; | |
const transformRequest = (url) => { | |
const hasQuery = url.indexOf("?") !== -1; | |
const suffix = hasQuery ? "&pluginName=scrollytellingV2" : "?pluginName=scrollytellingV2"; | |
return { | |
url: url + suffix | |
} | |
} | |
var map = new mapboxgl.Map({ | |
container: 'map', | |
style: config.style, | |
center: config.chapters[0].location.center, | |
zoom: config.chapters[0].location.zoom, | |
bearing: config.chapters[0].location.bearing, | |
pitch: config.chapters[0].location.pitch, | |
interactive: false, | |
transformRequest: transformRequest, | |
projection: config.projection | |
}); | |
// Create a inset map if enabled in config.js | |
if (config.inset) { | |
var insetMap = new mapboxgl.Map({ | |
container: 'mapInset', // container id | |
style: 'mapbox://styles/mapbox/dark-v10', //hosted style id | |
center: config.chapters[0].location.center, | |
// Hardcode above center value if you want insetMap to be static. | |
zoom: 3, // starting zoom | |
hash: false, | |
interactive: false, | |
attributionControl: false, | |
//Future: Once official mapbox-gl-js has globe view enabled, | |
//insetmap can be a globe with the following parameter. | |
//projection: 'globe' | |
}); | |
} | |
if (config.showMarkers) { | |
var marker = new mapboxgl.Marker({ color: config.markerColor }); | |
marker.setLngLat(config.chapters[0].location.center).addTo(map); | |
} | |
// instantiate the scrollama | |
var scroller = scrollama(); | |
map.on("load", function() { | |
if (config.onLoad) { | |
config.onLoad() | |
} | |
if (config.use3dTerrain) { | |
map.addSource('mapbox-dem', { | |
'type': 'raster-dem', | |
'url': 'mapbox://mapbox.mapbox-terrain-dem-v1', | |
'tileSize': 512, | |
'maxzoom': 14 | |
}); | |
// add the DEM source as a terrain layer with exaggerated height | |
map.setTerrain({ 'source': 'mapbox-dem', 'exaggeration': 1.5 }); | |
// add a sky layer that will show when the map is highly pitched | |
map.addLayer({ | |
'id': 'sky', | |
'type': 'sky', | |
'paint': { | |
'sky-type': 'atmosphere', | |
'sky-atmosphere-sun': [0.0, 0.0], | |
'sky-atmosphere-sun-intensity': 15 | |
} | |
}); | |
}; | |
// As the map moves, grab and update bounds in inset map. | |
if (config.inset) { | |
map.on('move', getInsetBounds); | |
} | |
// setup the instance, pass callback functions | |
scroller | |
.setup({ | |
step: '.step', | |
offset: 0.5, | |
progress: true | |
}) | |
.onStepEnter(async response => { | |
var current_chapter = config.chapters.findIndex(chap => chap.id === response.element.id); | |
var chapter = config.chapters[current_chapter]; | |
response.element.classList.add('active'); | |
map[chapter.mapAnimation || 'flyTo'](chapter.location); | |
// Incase you do not want to have a dynamic inset map, | |
// rather want to keep it a static view but still change the | |
// bbox as main map move: comment out the below if section. | |
if (config.inset) { | |
if (chapter.location.zoom < 5) { | |
insetMap.flyTo({center: chapter.location.center, zoom: 0}); | |
} | |
else { | |
insetMap.flyTo({center: chapter.location.center, zoom: 3}); | |
} | |
} | |
if (config.showMarkers) { | |
marker.setLngLat(chapter.location.center); | |
} | |
if (chapter.onChapterEnter.length > 0) { | |
chapter.onChapterEnter.forEach(setLayerOpacity); | |
} | |
if (chapter.callback) { | |
window[chapter.callback](); | |
} | |
if (chapter.rotateAnimation) { | |
map.once('moveend', () => { | |
const rotateNumber = map.getBearing(); | |
map.rotateTo(rotateNumber + 180, { | |
duration: 30000, easing: function (t) { | |
return t; | |
} | |
}); | |
}); | |
} | |
if (config.auto) { | |
var next_chapter = (current_chapter + 1) % config.chapters.length; | |
map.once('moveend', () => { | |
document.querySelectorAll('[data-scrollama-index="' + next_chapter.toString() + '"]')[0].scrollIntoView(); | |
}); | |
} | |
}) | |
.onStepExit(response => { | |
var chapter = config.chapters.find(chap => chap.id === response.element.id); | |
response.element.classList.remove('active'); | |
if (chapter.onChapterExit.length > 0) { | |
chapter.onChapterExit.forEach(setLayerOpacity); | |
} | |
}); | |
if (config.auto) { | |
document.querySelectorAll('[data-scrollama-index="0"]')[0].scrollIntoView(); | |
} | |
}); | |
//Helper functions for insetmap | |
function getInsetBounds() { | |
let bounds = map.getBounds(); | |
let boundsJson = { | |
"type": "FeatureCollection", | |
"features": [{ | |
"type": "Feature", | |
"properties": {}, | |
"geometry": { | |
"type": "Polygon", | |
"coordinates": [ | |
[ | |
[ | |
bounds._sw.lng, | |
bounds._sw.lat | |
], | |
[ | |
bounds._ne.lng, | |
bounds._sw.lat | |
], | |
[ | |
bounds._ne.lng, | |
bounds._ne.lat | |
], | |
[ | |
bounds._sw.lng, | |
bounds._ne.lat | |
], | |
[ | |
bounds._sw.lng, | |
bounds._sw.lat | |
] | |
] | |
] | |
} | |
}] | |
} | |
if (initLoad) { | |
addInsetLayer(boundsJson); | |
initLoad = false; | |
} else { | |
updateInsetLayer(boundsJson); | |
} | |
} | |
function addInsetLayer(bounds) { | |
insetMap.addSource('boundsSource', { | |
'type': 'geojson', | |
'data': bounds | |
}); | |
insetMap.addLayer({ | |
'id': 'boundsLayer', | |
'type': 'fill', | |
'source': 'boundsSource', // reference the data source | |
'layout': {}, | |
'paint': { | |
'fill-color': '#fff', // blue color fill | |
'fill-opacity': 0.2 | |
} | |
}); | |
// // Add a black outline around the polygon. | |
insetMap.addLayer({ | |
'id': 'outlineLayer', | |
'type': 'line', | |
'source': 'boundsSource', | |
'layout': {}, | |
'paint': { | |
'line-color': '#000', | |
'line-width': 1 | |
} | |
}); | |
} | |
function updateInsetLayer(bounds) { | |
insetMap.getSource('boundsSource').setData(bounds); | |
} | |
// setup resize event | |
window.addEventListener('resize', scroller.resize); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment