npm package: @icgcat/utils
Description: Thematic-stats is a library to generate thematic styles for geospatial data visualization
Author: Institut Cartogràfic i Geològic de Catalunya
Latest version: 0.0.1

<div style="text-align:center">
<p>
  <img src="https://eines.icgc.cat/recursos/logos/icgc_logo_color.png"  alt="ICGC Logo" width="250px">
</p>
</div>

<div style="text-align:center">

  [![License](https://img.shields.io/badge/License-BSD_3--Clause-blue.svg?style=flat)](LICENSE.txt) 
  [![Version](https://img.shields.io/npm/v/@icgcat/utils?style=flat)](https://www.npmjs.com/package/@icgcat/utils) 
  [![LinkedIn](https://img.shields.io/badge/LinkedIn-icgcat-blue?style=flat)](https://www.linkedin.com/company/icgcat)
  <img src="https://eines.icgc.cat/recursos//images/JS-logo.svg" width="20px"/>
  <!--posar aqui svelte image -->
</div>


# @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:

```bash
npm install @icgcat/utils
```

---

## Usage

### Import and Basic Example
Here's how to use the stats functions in your application:

```svelte
<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) ⇒ <code>Array</code>
Converts UTM coordinates to longitude and latitude (WGS84).

**Kind**: global function  
**Returns**: <code>Array</code> - The converted coordinates as [longitude, latitude].  

| Param | Type | Description |
| --- | --- | --- |
| coords | <code>Object</code> | The coordinates object with x (Easting) and y (Northing). |

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


## convertLonLatToUTM(coords) ⇒ <code>Array</code>
Converts longitude and latitude (WGS84) to UTM coordinates.

**Kind**: global function  
**Returns**: <code>Array</code> - The converted coordinates as [Easting, Northing].  

| Param | Type | Description |
| --- | --- | --- |
| coords | <code>Object</code> | The coordinates object with x (longitude) and y (latitude). |

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


## treuAccents(s) ⇒ <code>string</code>
Removes accents from a given string.

**Kind**: global function  
**Returns**: <code>string</code> - The string without accents.  

| Param | Type | Description |
| --- | --- | --- |
| s | <code>string</code> | The input string. |

**Example**  
```js
console.log(treuAccents("avió")); // "avio"
```


## getGeoJSONPoint(lng, lat) ⇒ <code>Object</code>
Generates a GeoJSON Point feature collection.

**Kind**: global function  
**Returns**: <code>Object</code> - A GeoJSON FeatureCollection containing a single point feature.  

| Param | Type | Description |
| --- | --- | --- |
| lng | <code>number</code> | Longitude. |
| lat | <code>number</code> | Latitude. |

**Example**  
```js
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) ⇒ <code>number</code>
Determines the zoom level based on the provided coordinates store.

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

| Param | Type | Description |
| --- | --- | --- |
| coordStore | <code>Object</code> | The coordinate store object. |

**Example**  
```js
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) ⇒ <code>boolean</code>
Checks if the given parameter is a valid MapLibre JSON Style.

**Kind**: global function  
**Returns**: <code>boolean</code> - True if it is a valid MapLibre style, false otherwise.  

| Param | Type | Description |
| --- | --- | --- |
| param | <code>Object</code> \| <code>string</code> | The input parameter (JSON object or URL string). |

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


## getKeywordEvaluation(keyword) ⇒ <code>Object</code>
Evaluates a keyword and determines if it represents coordinates, a road, a cadastral reference, or something else.

**Kind**: global function  
**Returns**: <code>Object</code> - An object containing the evaluation result and parsed values.  

| Param | Type | Description |
| --- | --- | --- |
| keyword | <code>string</code> | The input keyword. |

**Example**  
```js
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  

| Param | Type | Description |
| --- | --- | --- |
| map | <code>Object</code> | The MapLibre GL map instance. |

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


## getOpacitySlider(id, styleMap) ⇒ <code>number</code>
Retrieves the opacity value for a given map layer.

**Kind**: global function  
**Returns**: <code>number</code> - The opacity value between 0-1.  

| Param | Type | Description |
| --- | --- | --- |
| id | <code>string</code> | The name of the layer to apply opacity. |
| styleMap | <code>Object</code> | The object containing all style properties of the loaded map. |

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


## formatarDecimal(value, language) ⇒ <code>string</code>
Formats numeric values with thousands and decimal separators based on the selected language.

**Kind**: global function  
**Returns**: <code>string</code> - The formatted numeric value.  

| Param | Type | Description |
| --- | --- | --- |
| value | <code>number</code> | The numeric value to format. |
| language | <code>string</code> | The selected language. |

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


## submitPdfInfo(map, infoText) ⇒ <code>void</code>
Generates a PDF report with a map image and a table of values.

**Kind**: global function  
**Returns**: <code>void</code> - Downloads the generated PDF.  

| Param | Type | Description |
| --- | --- | --- |
| map | <code>Object</code> | The map object. |
| infoText | <code>Array</code> | An array containing the information to populate the table. |

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


## socrataJSONtoCSV(url) ⇒ <code>Promise.&lt;Object&gt;</code>
Fetches data from a Socrata API endpoint and returns the parsed JSON data.

**Kind**: global function  
**Returns**: <code>Promise.&lt;Object&gt;</code> - A promise that resolves to the parsed JSON data from the API.  
**Throws**:

- <code>Error</code> Throws an error if the network response is not successful.


| Param | Type | Description |
| --- | --- | --- |
| url | <code>string</code> | The URL of the Socrata API endpoint to fetch the data from. |

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


## arrayFromFieldJSON(datasetJson, fieldTematic, fieldId) ⇒ <code>Object</code>
Extracts specific fields from a dataset and returns them as arrays, along with their totals.

**Kind**: global function  
**Returns**: <code>Object</code> - 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.  

| Param | Type | Description |
| --- | --- | --- |
| datasetJson | <code>Array</code> | The JSON dataset to process. |
| fieldTematic | <code>string</code> | The field name to extract the thematic data from. |
| fieldId | <code>string</code> | The field name to extract the code data from. |

**Example**  
```js
arrayFromFieldJSON(dataset, "category", "id");
```


## JSONToArray(json) ⇒ <code>Array</code>
Converts a JSON array of objects into a 2D array (CSV format).

**Kind**: global function  
**Returns**: <code>Array</code> - A 2D array representing the JSON data in CSV format.  

| Param | Type | Description |
| --- | --- | --- |
| json | <code>Array</code> | The JSON array to convert. |

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


## geoJsonToCsv(geojson) ⇒ <code>string</code>
Converts GeoJSON data into CSV format, including coordinates for Point geometries.

**Kind**: global function  
**Returns**: <code>string</code> - A string representing the GeoJSON data in CSV format.  

| Param | Type | Description |
| --- | --- | --- |
| geojson | <code>Object</code> | The GeoJSON object to convert. |

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


## normalitzaBounds(bounds, decimalsActius) ⇒ <code>Array</code>
Normalizes a range of bounds to a specific format with the desired number of decimal places.

**Kind**: global function  
**Returns**: <code>Array</code> - An array of normalized bound ranges as strings.  

| Param | Type | Description |
| --- | --- | --- |
| bounds | <code>Array</code> | An array of bound values to normalize. |
| decimalsActius | <code>number</code> | The number of decimal places to use. |

**Example**  
```js
normalitzaBounds([0, 10, 20], 2);
```


## formatLangNumberLegend(strLegend, decimalsActius) ⇒ <code>string</code>
Formats a number for the language's number format with the specified number of decimal places.

**Kind**: global function  
**Returns**: <code>string</code> - The formatted number as a string.  

| Param | Type | Description |
| --- | --- | --- |
| strLegend | <code>string</code> | The number to format. |
| decimalsActius | <code>number</code> | The number of decimal places to use. |

**Example**  
```js
formatLangNumberLegend("10.5", 2);
```



---

## Dependencies 
`@icgc/stats` integrates the following libraries: 
- <a href="https://www.npmjs.com/package/jszip" target="_blank"> jszip </a>
- <a href="https://www.npmjs.com/package/proj4" target="_blank"> proj4 </a>

## Developed by:

 <a href="https://www.icgc.cat/" target="_blank"><img src="https://eines.icgc.cat/recursos/logos/ICGC_color_norma.svg"  alt="ICGC Logo" width="150"></img></a>      

  <a href="https://web.gencat.cat/" target="_blank"><img src="https://eines.icgc.cat/recursos/logos/gencat_logo_color.png"  alt="Gencat Logo" width="190"></img></a>


## License
This project is licensed under the MIT License.