Using Turf to measure how far a line travels through a polygon
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset=utf-8 /> | |
<title>A simple map</title> | |
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' /> | |
<script src='https://api.mapbox.com/mapbox.js/v2.2.2/mapbox.js'></script> | |
<link href='https://api.mapbox.com/mapbox.js/v2.2.2/mapbox.css' rel='stylesheet' /> | |
<script src='https://api.mapbox.com/mapbox.js/plugins/turf/v2.0.2/turf.min.js'></script> | |
<style> | |
body { margin:0; padding:0; } | |
#map { position:absolute; top:0; bottom:0; width:100%; } | |
p.distance-container { | |
position: absolute; | |
z-index: 10; | |
font-size: 2em; | |
margin: 1em; | |
right: 0em; | |
width: 8em; | |
background-color: #fff; | |
padding: 0.5em; | |
} | |
</style> | |
</head> | |
<body> | |
<div id='map'> | |
<p class='distance-container'>The line travels through the polygon for <span id="distance"></span> miles.</p> | |
</div> | |
<script> | |
L.mapbox.accessToken = 'pk.eyJ1IjoiZGFuc3dpY2siLCJhIjoiY2l1dTUzcmgxMDJ0djJ0b2VhY2sxNXBiMyJ9.25Qs4HNEkHubd4_Awbd8Og'; | |
var map = L.mapbox.map('map', 'mapbox.streets'); | |
var poly = { | |
"type": "Feature", | |
"properties": {}, | |
"geometry": { | |
"type": "Polygon", | |
"coordinates": [ | |
[ | |
[ | |
51.17431640625, | |
47.025206001585396 | |
], | |
[ | |
45.17578125, | |
43.13306116240612 | |
], | |
[ | |
54.5361328125, | |
41.85319643776675 | |
], | |
[ | |
51.17431640625, | |
47.025206001585396 | |
] | |
] | |
] | |
} | |
} | |
var line = { | |
"type": "Feature", | |
"properties": {}, | |
"geometry": { | |
"type": "LineString", | |
"coordinates": [ | |
[ | |
42.78076171875, | |
46.01222384063236 | |
], | |
[ | |
56.865234375, | |
44.26093725039923 | |
] | |
] | |
} | |
} | |
var polygon = L.mapbox.featureLayer(poly); | |
var polyline = L.mapbox.featureLayer(line).addTo(polygon); | |
polygon.addTo(map); | |
map.on('ready', function() { | |
map.fitBounds(polygon.getBounds()); | |
}); | |
var intersection = Math.round(turf.lineDistance(turf.intersect(poly, line), 'miles') * 100 / 100); | |
document.getElementById('distance').innerHTML = intersection; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment