0.0.1 • Published 9 months ago

@icgcat/utils v0.0.1

Weekly downloads
-
License
BSD-3-Clause
Repository
-
Last release
9 months ago

License Version LinkedIn

@icgcat/utils

Introduction

@icgcat/utils is a Node.js package designed for geospatial and data manipulation. It offers functions for coordinate conversions, data extraction, formatting, and generating map-related features. Designed for developers and data analysts, it simplifies working with geographic data and datasets for mapping and visualization.


Installation

To install the package, use npm or yarn:

npm install @icgcat/utils

Usage

Import and Basic Example

Here's how to use the stats functions in your application:

<script>

import { convertUTMToLonLat, convertLonLatToUTM, getGeoJSONPoint } from '@utils/data-processing';

// Example 1: Convert UTM to Longitude/Latitude
const coords = convertUTMToLonLat({ x: 432100, y: 4582000 });
console.log(coords); // [2.1734, 41.3851]

// Example 2: Convert Longitude/Latitude to UTM
const utm = convertLonLatToUTM({ x: 2.1734, y: 41.3851 });
console.log(utm); // [432100, 4582000]

// Example 3: Generate GeoJSON Point
const geoJSON = getGeoJSONPoint(2.1734, 41.3851);
console.log(geoJSON);
/*
{
  type: "FeatureCollection",
  features: [
    {
      type: "Feature",
      properties: {},
      geometry: {
        type: "Point",
        coordinates: [2.1734, 41.3851]
      }
    }
  ]
}
*/

// Example usage with map:
map.on('click', (e) => {
  const point = getGeoJSONPoint(e.lngLat.lng, e.lngLat.lat);
  console.log(point);
});


</script>

Component Functions

convertUTMToLonLat(coords) ⇒ Array

Converts UTM coordinates to longitude and latitude (WGS84).

Kind: global function
Returns: Array - The converted coordinates as longitude, latitude.

ParamTypeDescription
coordsObjectThe coordinates object with x (Easting) and y (Northing).

Example

const lonLat = convertUTMToLonLat({ x: 432100, y: 4582000 });
console.log(lonLat); // [2.1734, 41.3851]

convertLonLatToUTM(coords) ⇒ Array

Converts longitude and latitude (WGS84) to UTM coordinates.

Kind: global function
Returns: Array - The converted coordinates as Easting, Northing.

ParamTypeDescription
coordsObjectThe coordinates object with x (longitude) and y (latitude).

Example

const utm = convertLonLatToUTM({ x: 2.1734, y: 41.3851 });
console.log(utm); // [432100, 4582000]

treuAccents(s) ⇒ string

Removes accents from a given string.

Kind: global function
Returns: string - The string without accents.

ParamTypeDescription
sstringThe input string.

Example

console.log(treuAccents("avió")); // "avio"

getGeoJSONPoint(lng, lat) ⇒ Object

Generates a GeoJSON Point feature collection.

Kind: global function
Returns: Object - A GeoJSON FeatureCollection containing a single point feature.

ParamTypeDescription
lngnumberLongitude.
latnumberLatitude.

Example

const geoJSON = getGeoJSONPoint(2.1734, 41.3851);
console.log(geoJSON);
// {
//   type: "FeatureCollection",
//   features: [
//     {
//       type: "Feature",
//       properties: {},
//       geometry: {
//         type: "Point",
//         coordinates: [2.1734, 41.3851]
//       }
//     }
//   ]
// }

determinaZoom(coordStore) ⇒ number

Determines the zoom level based on the provided coordinates store.

Kind: global function
Returns: number - The zoom level (always returns 13 in the current implementation).

ParamTypeDescription
coordStoreObjectThe coordinate store object.

Example

console.log(determinaZoom({ nomTipus: "Comunicaci", b5m: true })); // 18
console.log(determinaZoom({ nomTipus: "Edificaci", b5m: false })); // 14
console.log(determinaZoom({ nomTipus: "Other" })); // 14
console.log(determinaZoom({})); // 14

checkIsMapLibreJsonStyle(param) ⇒ boolean

Checks if the given parameter is a valid MapLibre JSON Style.

Kind: global function
Returns: boolean - True if it is a valid MapLibre style, false otherwise.

ParamTypeDescription
paramObject | stringThe input parameter (JSON object or URL string).

Example

console.log(checkIsMapLibreJsonStyle({ layers: [], sources: {}, version: 8 })); // true
console.log(checkIsMapLibreJsonStyle("https://geoserveis.icgc.cat/contextmaps/example.json")); // true

getKeywordEvaluation(keyword) ⇒ Object

Evaluates a keyword and determines if it represents coordinates, a road, a cadastral reference, or something else.

Kind: global function
Returns: Object - An object containing the evaluation result and parsed values.

ParamTypeDescription
keywordstringThe input keyword.

Example

console.log(getKeywordEvaluation("41.3851 2.1734")); // { parsedX: "41.3851", parsedY: "2.1734", type: "coordinates" }
console.log(getKeywordEvaluation("C-58 km 12")); // { road: "C-58", km: "12", type: "road" }

getMapBounds(map)

Extracts the map bounds and generates a zip file containing a world file (.pgw) and a screenshot of the map.

Kind: global function

ParamTypeDescription
mapObjectThe MapLibre GL map instance.

Example

getMapBounds(mapInstance);
// Generates a ZIP file with output.pgw and output.png

getOpacitySlider(id, styleMap) ⇒ number

Retrieves the opacity value for a given map layer.

Kind: global function
Returns: number - The opacity value between 0-1.

ParamTypeDescription
idstringThe name of the layer to apply opacity.
styleMapObjectThe object containing all style properties of the loaded map.

Example

const opacity = getOpacitySlider("buildings", mapStyle);
console.log(opacity); // 0.5

formatarDecimal(value, language) ⇒ string

Formats numeric values with thousands and decimal separators based on the selected language.

Kind: global function
Returns: string - The formatted numeric value.

ParamTypeDescription
valuenumberThe numeric value to format.
languagestringThe selected language.

Example

console.log(formatDecimal(1234567.89, "en")); // "1,234,567.89"
console.log(formatDecimal(1234567.89, "es")); // "1.234.567,89"

submitPdfInfo(map, infoText) ⇒ void

Generates a PDF report with a map image and a table of values.

Kind: global function
Returns: void - Downloads the generated PDF.

ParamTypeDescription
mapObjectThe map object.
infoTextArrayAn array containing the information to populate the table.

Example

submitPdfInfo(mapInstance, [{ code: "A1", detail: "Main road" }]);

socrataJSONtoCSV(url) ⇒ Promise.<Object>

Fetches data from a Socrata API endpoint and returns the parsed JSON data.

Kind: global function
Returns: Promise.<Object> - A promise that resolves to the parsed JSON data from the API.
Throws:

  • Error Throws an error if the network response is not successful.
ParamTypeDescription
urlstringThe URL of the Socrata API endpoint to fetch the data from.

Example

socrataJSONtoCSV("https://blablabla.cat/xxxx-xxxx.json")
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error("Error fetching data:", error);
  });

arrayFromFieldJSON(datasetJson, fieldTematic, fieldId) ⇒ Object

Extracts specific fields from a dataset and returns them as arrays, along with their totals.

Kind: global function
Returns: Object - An object containing:

  • {Array} data - The extracted thematic data.
  • {number} dataTotal - The total number of thematic data entries.
  • {Array} code - The extracted code data.
  • {number} codeTotal - The total number of code data entries.
ParamTypeDescription
datasetJsonArrayThe JSON dataset to process.
fieldTematicstringThe field name to extract the thematic data from.
fieldIdstringThe field name to extract the code data from.

Example

arrayFromFieldJSON(dataset, "category", "id");

JSONToArray(json) ⇒ Array

Converts a JSON array of objects into a 2D array (CSV format).

Kind: global function
Returns: Array - A 2D array representing the JSON data in CSV format.

ParamTypeDescription
jsonArrayThe JSON array to convert.

Example

JSONToArray([{ name: "John", age: 30 }, { name: "Jane", age: 25 }]);

geoJsonToCsv(geojson) ⇒ string

Converts GeoJSON data into CSV format, including coordinates for Point geometries.

Kind: global function
Returns: string - A string representing the GeoJSON data in CSV format.

ParamTypeDescription
geojsonObjectThe GeoJSON object to convert.

Example

geoJsonToCsv({ features: [{ geometry: { type: "Point", coordinates: [1.1, 2.2] }, properties: { name: "Location" } }] });

normalitzaBounds(bounds, decimalsActius) ⇒ Array

Normalizes a range of bounds to a specific format with the desired number of decimal places.

Kind: global function
Returns: Array - An array of normalized bound ranges as strings.

ParamTypeDescription
boundsArrayAn array of bound values to normalize.
decimalsActiusnumberThe number of decimal places to use.

Example

normalitzaBounds([0, 10, 20], 2);

formatLangNumberLegend(strLegend, decimalsActius) ⇒ string

Formats a number for the language's number format with the specified number of decimal places.

Kind: global function
Returns: string - The formatted number as a string.

ParamTypeDescription
strLegendstringThe number to format.
decimalsActiusnumberThe number of decimal places to use.

Example

formatLangNumberLegend("10.5", 2);

Dependencies

@icgc/stats integrates the following libraries:

  • jszip
  • proj4

Developed by:

License

This project is licensed under the MIT License.