UNPKG

geo-polyline-tools

Version:

A javaScript library that provides utility functions to encode and decode polyline coordinates

93 lines (76 loc) 2.8 kB
# Geo Polyline Tools ## Description `geo-polyline-tools` is a lightweight JavaScript library that provides utility functions to encode and decode polyline coordinates, based on Google's Encoded Polyline Algorithm. It also supports converting between GeoJSON LineString features and polyline strings. ## Features - **Encode**: Convert an array of latitude and longitude coordinates into a polyline string. - **Decode**: Convert a polyline string back into an array of latitude and longitude coordinates. - **GeoJSON Support**: Encode and decode GeoJSON LineString features to and from polyline strings. - **Precision Control**: Specify the precision of the coordinates during encoding and decoding. ## Installation To install the package via npm, run the following command: ```bash npm install geo-polyline-tools ``` Or via yarn: ```bash yarn add geo-polyline-tools ``` ## Usage Here’s how to use the geo-polyline-tools package in your project: ### Importing the Library You can import the library into your project using ES modules or CommonJS: **ES Module** ```js import polyline from 'geo-polyline-tools'; ``` **CommonJS** ```js const polyline = require('geo-polyline-tools'); ``` ### Encoding Coordinates To encode an array of coordinates into a polyline string: ```js const coords = [[38.5, -120.2], [40.7, -120.95], [43.252, -126.453]]; const encoded = polyline.encode(coords, 5); console.log(encoded); // Example output: '_p~iF~ps|U_ulLnnqC_mqNvxq`@' ``` ### Decoding a Polyline String To decode a polyline string back into an array of coordinates: ```js const str = '_p~iF~ps|U_ulLnnqC_mqNvxq`@'; const decoded = polyline.decode(str, 5); console.log(decoded); // Example output: [[38.5, -120.2], [40.7, -120.95], [43.252, -126.453]] ``` ### Working with GeoJSON #### From GeoJSON to Polyline To convert a GeoJSON LineString to a polyline string: ```js const geojson = { type: 'Feature', geometry: { type: 'LineString', coordinates: [[38.5, -120.2], [40.7, -120.95], [43.252, -126.453]], }, }; const encoded = polyline.fromGeoJSON(geojson, 5); console.log(encoded); // Example output: '_p~iF~ps|U_ulLnnqC_mqNvxq`@' ``` #### From Polyline to GeoJSON To convert a polyline string back to a GeoJSON LineString: ```js const str = '_p~iF~ps|U_ulLnnqC_mqNvxq`@'; const geojson = polyline.toGeoJSON(str, 5); console.log(geojson); /* Example output: { type: 'LineString', coordinates: [[38.5, -120.2], [40.7, -120.95], [43.252, -126.453]], } */ ``` ## License This library is licensed under the MIT License. See the [LICENSE](https://www.npmjs.com/package/LICENSE) file for details. ## Support For any issues or questions, please contact [support@barikoi.com](mailto:support@barikoi.com). <img src="https://docs.barikoi.com/img/barikoi-logo-black.svg" height="30" />