Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src='https://unpkg.com/@turf/turf@6/turf.min.js'></script>
</head>
<body>
</body>
</html>
 
const sampleFeatureCollection = { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": {}, "geometry": { "type": "LineString", "coordinates": [ [ -8.404541015625, 43.3616313239934 ], [ -8.407974243164062, 43.352644787504495 ], [ -8.408660888671875, 43.345154990451135 ], [ -8.405914306640623, 43.337164854911094 ], [ -8.397674560546875, 43.33167102675838 ], [ -8.388748168945312, 43.33067209551502 ], [ -8.375701904296873, 43.32967314784175 ], [ -8.36334228515625, 43.32667620624288 ], [ -8.354415893554688, 43.32118142926661 ], [ -8.343429565429688, 43.321680974983344 ], [ -8.320770263671875, 43.32517767999296 ], [ -8.308410644531248, 43.31968276747214 ], [ -8.3001708984375, 43.320182325511006 ], [ -8.30360412597656, 43.33266994157184 ], [ -8.298797607421875, 43.34165943554058 ], [ -8.308410644531248, 43.3496489795891 ], [ -8.309097290039062, 43.35963443090036 ], [ -8.306350708007812, 43.369119087738554 ], [ -8.307037353515625, 43.37860226166394 ], [ -8.299484252929688, 43.38558891458754 ], [ -8.298797607421875, 43.38958092619001 ] ] } } ] };
const sampleUserLocations = { "type" : "FeatureCollection", "features" : [{ "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ -8.398189544677734, 43.33204562173882 ] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ -8.360080718994139, 43.32480304265438 ] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [ -8.316478729248047, 43.32055699134471 ] } }]};
// Looping over user locations (could be done in a geolocation call instead)
const sampleLine = sampleFeatureCollection.features[0]
sampleUserLocations.features.forEach(userLocation => {
  const nearestPoint = turf.nearestPointOnLine(sampleLine, userLocation);
  const distanceToLine = turf.distance(nearestPoint, userLocation);
  // normally here we'd check if the distance is close enough, but here we'll just allow it
  const slicedLine = turf.lineSlice(sampleLine.geometry.coordinates[0], nearestPoint, sampleLine);
  const length = turf.length(slicedLine);
  console.log(length); // Shows us the length in KM for each point we checked
})
Output 300px

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers