How to use @turf/length - 10 common examples

To help you get started, we’ve selected a few @turf/length examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sharedstreets / sharedstreets-js / test_core.ts View on Github external
test("sharedstreets -- bearing & distance", (t:any) => {
  const line = lineString([[-74.006449, 40.739405000000005], [-74.00790070000001, 40.7393884], [-74.00805100000001, 40.7393804]]);
  const lineLength = length(line);
  const inboundBearing = sharedstreets.inboundBearing(line, lineLength, lineLength);
  const outboundBearing = sharedstreets.outboundBearing(line, lineLength, 0);
  const distanceToNextRef = sharedstreets.distanceToNextRef(line);

  t.equal(outboundBearing, 269); // => 269 Java Implementation
  t.equal(inboundBearing, 269); // => 267 Java Implementation
  t.equal(distanceToNextRef, 13502); // => 13502 Java Implementation
  t.end();
});
github Turfjs / turf / packages / turf-directional-mean / index.ts View on Github external
function getLengthOfLineString(line: Feature, isPlanar: boolean) {
    if (isPlanar) {
        return segmentReduce(line, (previousValue?: number, segment?: Feature): number => {
            const coords = segment.geometry.coordinates; // the signatrue of segmentReduce has problem ?
            return previousValue + euclideanDistance(coords);
        }, 0);
    } else {
        return length(line, {
            units: "meters",
        });
    }
}
github FreemapSlovakia / freemap-v3-react / src / processors / trackViewerSetTrackDataProcessor.ts View on Github external
}

    // TODO add error handling for failed string-to-gpx and gpx-to-geojson parsing
    const gpxAsXml = new DOMParser().parseFromString(
      action.payload.trackGpx,
      'text/xml',
    );

    const trackGeojson = assertType(toGeoJSON.gpx(gpxAsXml));

    const startPoints: TrackPoint[] = []; // TODO
    const finishPoints: TrackPoint[] = []; // TODO

    for (const feature of trackGeojson.features) {
      if (feature.geometry.type === 'LineString') {
        const lengthInKm = turfLength(feature);
        const coords = feature.geometry.coordinates;
        const startLonlat = coords[0];
        let startTime: Date | undefined;
        let finishTime: Date | undefined;
        const times = assertType(
          feature.properties && feature.properties.coordTimes,
        );
        if (times) {
          startTime = new Date(times[0]);
          finishTime = new Date(times[times.length - 1]);
        }
        startPoints.push({
          lat: startLonlat[1],
          lon: startLonlat[0],
          lengthInKm: 0,
          startTime,
github FreemapSlovakia / freemap-v3-react / src / processors / elevationChartProcessor.ts View on Github external
async function resolveElevationProfilePointsViaApi(
  getState,
  trackGeojson,
  dispatch: Dispatch,
) {
  const totalDistanceInKm = turfLength(trackGeojson);
  const delta = Math.min(0.1, totalDistanceInKm / (window.innerWidth / 2));
  const elevationProfilePoints: {
    lat: number;
    lon: number;
    ele: number;
    distance: number;
  }[] = [];

  for (let dist = 0; dist <= totalDistanceInKm; dist += delta) {
    const [lon, lat] = getCoord(turfAlong(trackGeojson, dist));
    elevationProfilePoints.push({
      lat,
      lon,
      distance: dist * 1000,
      ele: Number.NaN, // will be filled later
    });
github conveyal / analysis-ui / lib / components / report / reroute.js View on Github external
// NB using indices here so we get an object even if fromStop or toStop is null
  // stops in pattern are in fact objects but they only have stop ID.
  const fromStop = feed.stopsById[pattern.stops[fromStopIndex].stop_id]
  const toStop = feed.stopsById[pattern.stops[toStopIndex].stop_id]

  const geometry = lineSlice(
    point([fromStop.stop_lon, fromStop.stop_lat]),
    point([toStop.stop_lon, toStop.stop_lat]),
    {
      type: 'Feature',
      geometry: pattern.geometry,
      properties: {}
    }
  )

  const removedLengthThisPattern = turfLength(geometry)

  return (
    <table>
      <tbody>
        <tr>
          <th>{message('report.patternName')}</th>
          <td>{pattern.name}</td>
        </tr>
        <tr>
          <th>{message('report.reroute.originalLength')}</th>
          <td>
            
          </td></tr></tbody></table>
github conveyal / analysis-ui / lib / components / report / reroute.js View on Github external
function Pattern(props) {
  const {modification, feedsById, pattern} = props
  const feed = feedsById[modification.feed]

  // all calculations below are in kilometers
  const patternLength = turfLength(pattern.geometry)
  const stops = getStops(modification.segments)
  const segmentLength = stops.slice(-1)[0].distanceFromStart / 1000
  const segmentDistances = modification.segments.map(seg =>
    turfLength(seg.geometry)
  )

  const {segmentSpeeds} = modification
  const totalDistance = sum(segmentDistances)
  const weightedSpeeds = segmentSpeeds.map((s, i) => s * segmentDistances[i])
  const speed =
    weightedSpeeds.reduce((total, speed) => total + speed, 0) / totalDistance

  // figure out removed segment length
  const fromStopIndex =
    modification.fromStop != null
      ? pattern.stops.findIndex(s => s.stop_id === modification.fromStop)
github developmentseed / observe / app / utils / traces.js View on Github external
export function getTraceLength (traceGeoJSON) {
  return turfLength(traceGeoJSON, { units: 'kilometers' }) * 1000
}
github conveyal / analysis-ui / lib / components / report / add-trips.js View on Github external
    const segmentDistances = segments.map(seg => turfLength(seg.geometry))
github noncomputable / AgentMaps / src / routing.js View on Github external
if (!intersection_indices.some(intersection_index =&gt; intersection_index === street_points.length - 1)) {
		intersection_indices.push(street_points.length - 1);
	}

	//Make a graph out of segments of the street between the start, intersections, and end of the street,
	//so that the nodes are the coordinates of the start, end, and intersection points, and the edges are
	//the segments between successive nodes. Each edge is associated with the geographic distance between its nodes.
	for (let i = 0; i &lt;= intersection_indices.length - 2; i++) {
		let node_a = street_points[intersection_indices[i]],
		node_b = street_points[intersection_indices[i + 1]],
		a_string = encodeLatLng(node_a),
		b_string = encodeLatLng(node_b),
		start_coords = L.A.pointToCoordinateArray(node_a),
		end_coords = L.A.pointToCoordinateArray(node_b),
		segment = lineSlice(start_coords, end_coords, street.toGeoJSON()),
		distance = length(segment);
		graph.addLink(a_string, b_string, {
			distance: distance,
			place: { type: "street",
				id: street_id } 
		});
	}
}
github noncomputable / AgentMaps / src / agents.js View on Github external
Agent.travel = function(override_speed) {
	let current_coords = L.A.pointToCoordinateArray(this.trip.current_point),
	sub_goal_distance = override_speed ||this.trip.speed,
	sub_goal_coords = destination(current_coords, sub_goal_distance * .001,this.trip.angle).geometry.coordinates,
	sub_goal_lat_lng = L.latLng(L.A.reversedCoordinates(sub_goal_coords));

	let segment_to_goal = lineString([this.trip.current_point, this.trip.goal_point].map(point =&gt; L.A.pointToCoordinateArray(point))),
	segment_to_sub_goal = lineString([this.trip.current_point, sub_goal_lat_lng].map(point =&gt; L.A.pointToCoordinateArray(point)));
	
	let goal_lat_dist = Math.abs(this.trip.current_point.lat - this.trip.goal_point.lat),
	goal_lng_dist = Math.abs(this.trip.current_point.lng - this.trip.goal_point.lng);
	
	let dist_to_goal = length(segment_to_goal) * 1000,
	dist_to_sub_goal = length(segment_to_sub_goal) * 1000,
	leftover_after_goal;
	
	//Check if the distance to the sub_goal is greater than the distance to the goal, and if so, make the sub_goal equal the goal
	//and change the number of meters to the sub_goal to the number of meters to the goal.
	if (dist_to_goal &lt; dist_to_sub_goal) {
		sub_goal_lat_lng = this.trip.goal_point,
		sub_goal_distance = dist_to_goal,
		leftover_after_goal = dist_to_sub_goal - dist_to_goal;
	}
	
	if (this.checkArrival(sub_goal_lat_lng, leftover_after_goal)) {
		return;
	}
	
	//Lat/Lng distance between current point and sub_goal point.

@turf/length

turf length module

MIT
Latest version published 3 years ago

Package Health Score

78 / 100
Full package analysis

Popular @turf/length functions