mapHelpers.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import * as turf from '@turf/turf';
  2. import { Feature } from '@turf/turf';
  3. interface RegionData {
  4. type?: string;
  5. name?: string;
  6. crs?: {
  7. type: string;
  8. properties: { name: string; };
  9. };
  10. features?: any;
  11. }
  12. export const findRegionInDataset = (dataset: RegionData, point: turf.helpers.Position | turf.helpers.Point | turf.helpers.Feature<turf.helpers.Point, turf.helpers.Properties>): Feature | undefined => {
  13. return dataset.features.find((region: any) => {
  14. const coordinates = region?.geometry?.coordinates;
  15. const type = region?.geometry?.type;
  16. if (!Array.isArray(coordinates) || coordinates.length === 0) {
  17. return false;
  18. }
  19. try {
  20. const polygon: any = type === 'Polygon'
  21. ? turf.polygon(coordinates)
  22. : turf.multiPolygon(coordinates);
  23. return turf.booleanPointInPolygon(point, polygon);
  24. } catch (error) {
  25. console.error('Error creating polygon:', error);
  26. return false;
  27. }
  28. });
  29. };
  30. export const calculateMapRegion = (bounds: turf.BBox): any => {
  31. const padding = 1;
  32. return {
  33. latitude: (bounds[1] + bounds[3]) / 2,
  34. longitude: (bounds[0] + bounds[2]) / 2,
  35. latitudeDelta: Math.abs(bounds[3] - bounds[1]) + padding,
  36. longitudeDelta: Math.abs(bounds[2] - bounds[0]) + padding,
  37. };
  38. };