Warm tip: This article is reproduced from stackoverflow.com, please click
leaflet typescript turfjs

When using Turf.nearPoint() what kind of point should be used? Documentation for the Turf.nearestPoi

发布于 2020-04-07 10:22:13

Any code that I put here is something that I have to transcribe from another system so there is no easy way for me to just post my code. If there were I'd post the whole darn project.

I was trying to implement this https://turfjs.org/docs/#nearestPoint in our project but I keep getting error messages.

TS2345: Arguments of type 'FeatureCollection < Geometry | GeometryCollection, {[name:string]: any; } is not assignable to parameter of type 'FeatureCollection < Point, {[name:string]: any;} > '

Type Geometry is not assignable to type Point Type of property type are incompatible Type string is not assignable to type Point

I saw this post turf.nearestPoint only returning the same point Where in the post it has

map.on('click', function(e) {
  var coord = e.latlng;
  var lat = coord.lat;
  var lng = coord.lng;
  var targetPoint = turf.point([lng, lat]);
  var nearest = turf.nearestPoint(targetPoint, points);
    alert(JSON.stringify(nearest)); 
});

In my code I am

  • Using a mouse click event to create a selectPoint via the turf.point([lng, lat]}

  • Creating my points from an array of points I have also created by the same turf.point([lng, lat]) approach

But to no avail I always get the TS error mentioned above.

Also the documentation on the Turf page states the targetPoint is a Coord but the other posters code has a Turf.point which is a Feature

Arguments

Argument------Type------Description

targetPoint----Coord-----the reference point

points------FeatureCollection< Point >------against input point set

After 8+ hours of trying to get this to work I have no hair left to pull out and am left doubting everything that I have done today.

Can someone please assist or just point me to something out there that actually functions and does not have cryptic comments only intended for people who are already familiar with the technology?

Questioner
Elijah
Viewed
43
Elijah 2020-02-13 21:44

Just to help others out there who may be struggling with this.

import * as Turf from '@turf/turf';

private handleClickEvent(e: Leaflet.LeafletEvent) {
    const latLng: Leaflet.LatLng = e.latlng;
    // Note in Turf it is backwards longitude, latitude where normally its lat, lng
    let mapClickLocation: Feature<Point> = Turf.point( [latLng.lng, latLng.lat] );

    let allYourGeoPoints: Array<Feature<Point>> = [];
    // Values you'd set in the allYourGeoPoints e.g.
    allYourGeoPoints.push(Turf.point([lng, lat], {'id': idOfYourRecord});

    // Create a collection of points usable by Turf
    let collectionOfPoints: FeatureCollection<Point> = Turf.featureCollection(allYourGeoPoints);

    // Now find the nearest item
    let nearestPointFound: NearestPoint = Turf.nearestPoint(mapClickLocation,  collectionOfPoints);

}