Skip to content

Instantly share code, notes, and snippets.

@jbranigan
Last active May 25, 2023 18:35
Show Gist options
  • Save jbranigan/9fd06e4103ccae2335c35d16f2a8c351 to your computer and use it in GitHub Desktop.
Save jbranigan/9fd06e4103ccae2335c35d16f2a8c351 to your computer and use it in GitHub Desktop.
Find the nearest point on a highway to the mouse cursor
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Get nearest highway to the mouse pointer</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<link href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
<script src='https://cdn.jsdelivr.net/npm/@turf/turf@6/turf.min.js'></script>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiYnJhbmlnYW4iLCJhIjoiY2tlMWtmcndiMDA4bzJxbngzbm9zaDg3YyJ9.GvTC2gaBQE4H79yxpPPDCg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-107, 43],
zoom: 6.25
});
map.on('load', function () {
map.addSource('point', {
type: 'geojson',
data: { "type": "FeatureCollection", "features": [] }
});
map.addLayer({
id: 'nearest-point',
source: 'point',
type: 'circle',
paint: {
'circle-color': 'purple',
'circle-radius': 8,
'circle-opacity': 0.5
}
});
map.on('mousemove', function (e) {
// set some padding on the mouse cursor and find any highways nearby
const pixels = 20;
const features = map.queryRenderedFeatures([
[e.point.x - pixels, e.point.y - pixels],
[e.point.x + pixels, e.point.y + pixels]
], { layers: ['road-motorway-trunk', 'road-primary'] }
);
if (features.length > 0) {
// convert cursor location from pixel coordinates to lon/lat
const cursorLocation = turf.point(map.unproject(e.point).toArray());
// find the nearest place on the road to the cursor and add it to the map layer
const snappedPoint = turf.nearestPointOnLine(features[0], cursorLocation);
map.getSource('point').setData({ "type": "FeatureCollection", "features": [ snappedPoint ] });
} else {
map.getSource('point').setData({ "type": "FeatureCollection", "features": [] });
}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment