When utilizing the Turf.nearPoint() function, it is important to consider the type of point being used. The documentation for Turf.nearestPoint() appears to be inaccurate

I have some code that needs to be transcribed from another system, so unfortunately I can't easily share it here. If I could, I would just post the entire project.

Recently, I attempted to integrate into our project but encountered 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 came across this thread turf.nearestPoint only returning the same point, where a user shared:

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 implementation, I am:

  • Utilizing a mouse click event to create a selectPoint using turf.point([lng, lat])

  • Generating my points from an array also created with the approach turf.point([lng, lat])

Unfortunately, I continue to receive the TS error mentioned above.

Furthermore, the Turf documentation indicates that targetPoint should be a Coord while the example code uses Turf.point which is a Feature.

Arguments

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

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

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

After spending over 8 hours trying to troubleshoot this issue, I'm feeling beyond frustrated and doubting all my efforts today.

If anyone can offer assistance or point me towards a reliable solution without cryptic jargon meant for tech experts, I would greatly appreciate it.

Answer №1

Are you familiar with the library called Leaflet.GeometryUtil? It could be a useful tool for your project.

If your points are represented as markers (L.Marker), you can utilize the following code:

map.on('click', function (e) {
var layersToSearch = [];
map.eachLayer(layer => {
    if (layer instanceof L.Marker) {
        layersToSearch.push(layer);}
})
nearestLayer = L.GeometryUtil.closestLayer(map, layersToSearch, e.latlng); 
nearestLayer.layer.bindPopup('Nearest Point').openPopup();
});

Answer №2

For anyone struggling with this issue, here is a helpful solution.

import * as Geospatial from '@geopackage/geospatial';

private handleMouseEvent(event: MapLeaflet.LeafletEvent) {
    const coordinates: MapLeaflet.LatLng = event.latlng;
    // Please note that in Geospatial systems, the order of longitude and latitude is reversed compared to standard lat, lng
    let clickLocationOnMap: Feature<Point> = Geospatial.point( [coordinates.lng, coordinates.lat] );

    let geoPoints: Array<Feature<Point>> = [];
    // Add your own geospatial points to the array, e.g.
    geoPoints.push(Geospatial.point([lng, lat], {'id': recordID});

    // Create a collection of points for use by Geospatial functions
    let pointCollection: FeatureCollection<Point> = Geospatial.featureCollection(geoPoints);

    // Find the nearest point to the clicked location
    let closestPoint: NearestPoint = Geospatial.nearestPoint(clickLocationOnMap,  pointCollection);

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

Exploring Angular 6: Unveiling the Secrets of Angular Specific Attributes

When working with a component, I have included the angular i18n attribute like so: <app-text i18n="meaning|description"> DeveloperText </app-text> I am trying to retrieve this property. I attempted using ElementRef to access nativeElement, bu ...

Encountered Typescript errors TS1110 and TS1005

Error in TypeScript: typings/node/node.d.ts(83,23): Type expected. TypeScript issue: typings/node/node.d.ts(1830,52): Expected '=' sign. My TypeScript compilation is failing at node.d.ts, despite multiple attempts to reinstall it. ...

Is it possible to define a unique function signature in a child class when implementing a method from a parent class?

In the process of developing a repository module that includes generic methods, I have found that as long as each derived class has the `tableName` configured, the basic query for creating, finding, or deleting records remains consistent across all child c ...

What are the steps to transpile NextJS to es5?

Is it possible to create a nextjs app using es5? I specifically require the exported static javascript to be in es5 to accommodate a device that only supports that version. I attempted using a babel polyfill, but after running es-check on the _app file, ...

Is there a function return type that corresponds to the parameter types when the spread operator is used?

Is it possible to specify a return type for the Mixin() function below that would result in an intersection type based on the parameter types? function Mixin(...classRefs: any[]) { return merge(class {}, ...classRefs); } function merge(derived: any, ... ...

"An error occurred: Uncaught SyntaxError - The import statement can only be used within a module. Including a TypeScript file into a

I need to integrate an Angular 10 TypeScript service into a jQuery file, but I am facing an issue. When I try to import the TypeScript service file into my jQuery file, I encounter the following error: Uncaught SyntaxError: Cannot use import statement outs ...

Issue with custom HTML5 video progress bar not syncing with video playback

Currently, I am working on a project using React with Typescript. I have implemented an HTML5 element range for a seek bar in the video player. The issue I am facing is that although the seek bar works correctly when manually dragged, it does not update as ...

Can you explain the variance between the (Record<string, unknown>) and object type?

Can you explain the distinction between type Record<string, unkown> and type object? Create a generic DeepReadonly<T> which ensures that every parameter of an object - and its nested objects recursively - is readonly. Here's the type I c ...

Typescript: The type 'Observable<{}>' cannot be assigned to the type 'Observable'

I'm encountering an issue with the Observable type, any thoughts on how to resolve it? import { PostModel } from '../model/postModel'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable&ap ...

Is there a way to trigger a request to the backend when the user closes or refreshes the browser?

My Objective: I am working on a lobby feature that updates automatically when a player leaves. Using backend requests and sockets, the lobby is updated to display the current list of players after someone exits. The Challenge: I am faced with the issue ...

After pushing to history in React, the rendered component fails to display on the screen

I am in the process of developing a React application. Here are the dependencies I am currently using: "react": "^17.0.2", "react-dom": "^17.0.2", "react-helmet": "^6.1.0", "react-router" ...

The Nest Scheduler - Cron decorator may encounter missing dependencies when used in conjunction with another decorator by applying multiple decorators

In my current project, I am developing a custom cron decorator that not only schedules tasks but also logs the name of the task when it is executed. To accomplish this, I have merged the default nestjs scheduling Cron decorator with a unique LogTask decora ...

Is there a way to customize Material UI theme types and make adjustments to existing types using Typescript?

One way to customize the material ui theme is by extending its type and adding new properties, as shown here: For example, if we want to add an appDrawer property, it can be done like this: declare module '@material-ui/core/styles/createMuiTheme&apos ...

Extracting PDF files using API within Angular services

I have set up a Java-based API on a server, with the URL being "ex.com". This API has an endpoint that returns a PDF file, with the URL set as "ex.com/pdf". For this endpoint, a POST request is required with a parameter specifying the requested PDF, like ...

Unpacking Objects in JavaScript and TypeScript: The Power of Destructuring

I have a variable called props. The type includes VariantTheme, VariantSize, VariantGradient, and React.DOMAttributes<HTMLOrSVGElement> Now I need to create another variable, let's name it htmlProps. I want to transfer the values from props to ...

Utilize MaterialUI's Shadows Type by importing it into your project

In our project, we're using Typescript which is quite particular about the use of any. There's a line of code that goes like this: const shadowArray: any = Array(25).fill('none') which I think was taken from StackOverflow. Everything s ...

Error Passing Data to Child Component in Typescript on Next.JS 14 Compilation

Although there are many similar questions, I am struggling to make my code work properly. I recently started learning typescript and am having trouble passing data to the child component. While the code runs fine in development (no errors or warnings), i ...

Experimenting with a Collection of Items - Jest

I need to conduct a test on an array of objects. During the test coverage analysis of the displayed array, I found that the last object with the key link has certain conditions that are not covered. export const relatedServicesList: IRelatedServiceItem[ ...

Hermes, the js engine, encountered an issue where it was unable to access the property 'navigate' as it was undefined, resulting

Whenever I switch from the initial screen to the language selection screen, I encounter this error and have exhausted all possible solutions. I attempted to utilize "useNavigation" but still encountered errors, so I resorted to using this method instead. T ...