ola-map-sdk 1.1.5 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,137 +1,215 @@
1
1
  # Ola Map SDK
2
- Ola Map SDK is a Node.js package that provides an easy-to-use interface for interacting with the Ola Maps API. This SDK allows you to perform various operations like geocoding, reverse geocoding, fetching map tiles, and getting routing directions.
2
+
3
+ Complete Ola Maps API client for **Node.js**. Covers all endpoints — Places, Routing, Roads, Geofencing, Elevation, and Tiles.
3
4
 
4
5
  ## Installation
5
- Install the package using npm:
6
6
 
7
7
  ```bash
8
8
  npm install ola-map-sdk
9
9
  ```
10
10
 
11
- ## Usage
12
- First, you need to require the SDK and create an instance of the OlaMapsClient class with your API key.
11
+ ## Quick Start
13
12
 
14
13
  ```javascript
15
14
  const OlaMapsClient = require('ola-map-sdk');
15
+ // or: import OlaMapsClient from 'ola-map-sdk';
16
+
17
+ const client = new OlaMapsClient('YOUR_API_KEY');
18
+
19
+ // Search for places
20
+ const results = await client.places.autocomplete('Koramangala, Bangalore');
16
21
 
17
- const apiKey = 'YOUR_API_KEY';
18
- const client = new OlaMapsClient(apiKey);
22
+ // Get directions
23
+ const route = await client.routing.getDirections(
24
+ { lat: 12.993103, lon: 77.543326 },
25
+ { lat: 12.972006, lon: 77.580085 }
26
+ );
19
27
  ```
20
28
 
21
- ### Places API
22
- API for accessing geolocation services such as places autocomplete, reverse geocode.
29
+ ---
23
30
 
24
- - **Autocomplete** - Provides Autocomplete suggestions for a given substring satisfying the given criteria.
31
+ ## API Reference
32
+
33
+ ### Places
25
34
 
26
35
  ```javascript
27
- try {
28
- const result = await client.places.autocomplete('Gauhati University');
29
- console.log('Autocomplete result:', result);
30
- } catch (error) {
31
- console.error('Error during autocomplete:', error);
32
- }
36
+ // Autocomplete
37
+ const results = await client.places.autocomplete('Bangalore', {
38
+ location: '12.93,77.61', radius: 5000, language: 'en'
39
+ });
40
+
41
+ // Geocode & Reverse Geocode
42
+ const geo = await client.places.geocode('Taj Mahal, Mumbai');
43
+ const reverse = await client.places.reverseGeocode(26.115103, 91.703239);
44
+
45
+ // Place Details
46
+ const details = await client.places.placeDetails('ola-platform:5000039498427');
47
+ const advDetails = await client.places.placeDetailsAdvanced('ola-platform:5000039498427');
48
+
49
+ // Nearby Search
50
+ const nearby = await client.places.nearbySearch('12.93,77.61', { types: 'restaurant', radius: 1000 });
51
+ const nearbyAdv = await client.places.nearbySearchAdvanced('12.93,77.61', { types: 'cafe' });
52
+
53
+ // Text Search
54
+ const text = await client.places.textSearch('Cafes in Koramangala');
55
+
56
+ // Address Validation
57
+ const validation = await client.places.addressValidation('7, Lok Kalyan Marg, New Delhi');
58
+
59
+ // Place Photo
60
+ const photo = await client.places.photo('photo_reference_id');
33
61
  ```
34
62
 
35
- - **Geocode** - Returns the geocoded address based on the provided parameters.
63
+ ### Routing
36
64
 
37
65
  ```javascript
38
- try {
39
- const result = await client.places.geocode('Taj Mahal, Mumbai');
40
- console.log('Geocode result:', result);
41
- } catch (error) {
42
- console.error('Error during geocoding:', error);
43
- }
66
+ // Directions (with options)
67
+ const directions = await client.routing.getDirections(
68
+ { lat: 12.993103, lon: 77.543326 },
69
+ { lat: 12.972006, lon: 77.580085 },
70
+ { mode: 'driving', steps: true, overview: 'full', traffic_metadata: true }
71
+ );
72
+
73
+ // Directions Basic (no traffic)
74
+ const basic = await client.routing.getDirectionsBasic(
75
+ { lat: 12.993103, lon: 77.543326 },
76
+ { lat: 12.972006, lon: 77.580085 }
77
+ );
78
+
79
+ // Distance Matrix
80
+ const matrix = await client.routing.getDistanceMatrix(
81
+ '12.993,77.543|12.972,77.580', '12.935,77.615', { mode: 'driving' }
82
+ );
83
+
84
+ // Distance Matrix Basic
85
+ const matrixBasic = await client.routing.getDistanceMatrixBasic(
86
+ '12.993,77.543', '12.935,77.615'
87
+ );
88
+
89
+ // Route Optimizer
90
+ const optimized = await client.routing.routeOptimizer(
91
+ '12.993,77.543|12.972,77.580|12.935,77.615',
92
+ { source: 'first', destination: 'last' }
93
+ );
94
+
95
+ // Fleet Planner
96
+ const fleet = await client.routing.fleetPlanner(
97
+ { packages: [...], vehicles: [...] }, 'optimal'
98
+ );
44
99
  ```
45
100
 
46
- - **Reverse Geocode** - Provides information of a place based on the location provided satisfying the given criteria.
101
+ ### Roads
47
102
 
48
103
  ```javascript
49
- try {
50
- const result = await client.places.reverseGeocode(26.115103, 91.703239);
51
- console.log('Reverse Geocode result:', result);
52
- } catch (error) {
53
- console.error('Error during reverse geocoding:', error);
54
- }
104
+ const snapped = await client.roads.snapToRoad('12.999,77.673|12.992,77.658', true);
105
+ const nearest = await client.roads.nearestRoads('12.999,77.673|12.992,77.658', 'DRIVING', 500);
106
+ const speeds = await client.roads.speedLimits('13.063,77.593|13.063,77.593');
55
107
  ```
56
108
 
57
- ### Direction API
58
-
59
- - **Get Directions** - Provides routable path between two or more points. Accepts coordinates in lat,long format.
109
+ ### Geofencing
60
110
 
61
111
  ```javascript
62
- try {
63
- const result = await client.routing.getDirections(
64
- { lat: 12.993103152916301, lon: 77.54332622119354 },
65
- { lat: 12.972006793201695, lon: 77.5800850011884 },
66
- {
67
- alternatives: false,
68
- steps: true,
69
- overview: 'full',
70
- language: 'en',
71
- traffic_metadata: false
72
- }
73
- );
74
- console.log('Directions result:', result);
75
- } catch (error) {
76
- console.error('Error fetching directions:', error);
77
- }
112
+ // Create
113
+ const fence = await client.geofencing.create({
114
+ name: 'Warehouse', type: 'circle', coordinates: [[12.931, 77.615]],
115
+ radius: 100, status: 'active', projectId: 'my-project'
116
+ });
117
+
118
+ // Read, Update, Delete
119
+ const get = await client.geofencing.getById('fence-id');
120
+ const update = await client.geofencing.update('fence-id', { name: 'Updated' });
121
+ const del = await client.geofencing.deleteById('fence-id');
122
+
123
+ // List & Status Check
124
+ const list = await client.geofencing.list('my-project', 1, 10);
125
+ const status = await client.geofencing.checkStatus('fence-id', '12.93,77.61');
78
126
  ```
79
127
 
128
+ ### Elevation
80
129
 
81
- ### Tiles API
82
- API for accessing geolocation services such as places autocomplete, reverse geocode, turn by turn directions, map tiles in vector or image format.
130
+ ```javascript
131
+ const elev = await client.elevation.getElevation(12.93126, 77.61638);
132
+ const multi = await client.elevation.getMultiElevation(['12.93126,77.61638', '12.89731,77.65136']);
133
+ ```
83
134
 
84
- - **Get Data TileJSON** - Get array of data's TileJSONs.
135
+ ### Tiles
85
136
 
86
137
  ```javascript
87
- try {
88
- const result = await client.tiles.getDataTileJSON('planet');
89
- console.log('Data TileJSON result:', result);
90
- } catch (error) {
91
- console.error('Error fetching Data TileJSON:', error);
92
- }
138
+ const styles = await client.tiles.getStyles();
139
+ const styleDetail = await client.tiles.getStyleDetail('default-light-standard');
140
+ const tileJSON = await client.tiles.getDataTileJSON('planet');
141
+ const pbf = await client.tiles.getPBFFile('planet', 14, 110, 1010);
142
+ const glyphs = await client.tiles.getFontGlyphs('Noto Sans Bold', 0, 255);
143
+
144
+ // Static map images
145
+ const img = await client.tiles.getStaticMapByCenter(
146
+ 'default-light-standard', 77.61, 12.93, 15, 800, 600, 'png',
147
+ { marker: '77.61,12.93|red' }
148
+ );
149
+ const bbox = await client.tiles.getStaticMapByBBox(
150
+ 'default-light-standard',
151
+ { minx: 77.5, miny: 12.9, maxx: 77.7, maxy: 13.0 }, 800, 600, 'png'
152
+ );
153
+ const auto = await client.tiles.getStaticMapAuto('default-light-standard', 800, 600, 'png');
154
+ const tileset3d = await client.tiles.get3DTileset();
93
155
  ```
94
156
 
95
- - **Get PBF File** - Returns the PBF file for data.
157
+ ---
96
158
 
97
- ```javascript
98
- try {
99
- const result = await client.tiles.getPBFFile('planet', 14, 110, 1010);
100
- console.log('PBF File result:', result);
101
- } catch (error) {
102
- console.error('Error fetching PBF file:', error);
103
- }
159
+ ## Map Display (with MapLibre GL)
160
+
161
+ The SDK includes helper methods to simplify MapLibre GL integration. Install `maplibre-gl` alongside:
162
+
163
+ ```bash
164
+ npm install maplibre-gl
104
165
  ```
105
166
 
106
- - **Get Styles** - Returns the styles for the map.
167
+ ### Using `getMapOptions()` (recommended)
107
168
 
108
169
  ```javascript
109
- try {
110
- const result = await client.tiles.getStyles();
111
- console.log('Styles result:', result);
112
- } catch (error) {
113
- console.error('Error fetching Styles:', error);
114
- }
170
+ import maplibregl from 'maplibre-gl';
171
+ import 'maplibre-gl/dist/maplibre-gl.css';
172
+ import OlaMapsClient from 'ola-map-sdk';
173
+
174
+ const client = new OlaMapsClient('YOUR_API_KEY');
175
+
176
+ // One-liner — handles style URL + API key injection automatically
177
+ const map = new maplibregl.Map(client.getMapOptions({
178
+ container: 'map',
179
+ style: 'default-light-standard',
180
+ center: [77.61, 12.93],
181
+ zoom: 14,
182
+ }));
115
183
  ```
116
184
 
117
- - **Get Style Detail** - Returns the style detail for the map.
185
+ ### Individual helpers
118
186
 
119
187
  ```javascript
120
- try {
121
- const result = await client.tiles.getStyleDetail('default-light-standard');
122
- console.log('Style Detail result:', result);
123
- } catch (error) {
124
- console.error('Error fetching Style Detail:', error);
125
- }
188
+ // Get the full style URL
189
+ client.getStyleURL('default-dark-standard');
190
+ // → "https://api.olamaps.io/tiles/vector/v1/styles/default-dark-standard/style.json"
191
+
192
+ // Get a pre-configured transformRequest function
193
+ const transformRequest = client.getTransformRequest();
194
+
195
+ // Switch styles at runtime
196
+ map.setStyle(client.getStyleURL('eclipse-light-standard'));
126
197
  ```
127
198
 
128
- - **Get Font Glyphs** - Returns the font glyphs for the map.
199
+ ### Available map styles
129
200
 
130
- ```javascript
131
- try {
132
- const result = await client.tiles.getFontGlyphs('Noto Sans Bold', 0, 255);
133
- console.log('Font Glyphs result:', result);
134
- } catch (error) {
135
- console.error('Error fetching font glyphs:', error);
136
- }
137
- ```
201
+ | Category | Styles |
202
+ |---|---|
203
+ | **Default Light** | `default-light-lite`, `default-light-standard`, `default-ultra-light-standard`, `default-light-full` + 11 language variants |
204
+ | **Default Dark** | `default-dark-lite`, `default-dark-standard`, `default-dark-full`, `default-dark-standard-satellite` + language variants |
205
+ | **Eclipse** | `eclipse-light-lite`, `eclipse-light-standard`, `eclipse-light-full`, `eclipse-dark-lite`, `eclipse-dark-standard`, `eclipse-dark-full` |
206
+ | **Bolt** | `bolt-light`, `bolt-dark` |
207
+ | **Vintage** | `vintage-light`, `vintage-dark` |
208
+ | **Earth** | `default-earth-lite`, `default-earth-standard`, `default-earth-full` |
209
+ | **OSM** | `positron`, `osm-bright`, `osm-basic`, `dark-matter`, `fiord-color`, `silver-osm` |
210
+
211
+ ---
212
+
213
+ ## License
214
+
215
+ MIT © Kunal Kongkan Kashyap
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ola-map-sdk",
3
- "version": "1.1.5",
4
- "description": "A Node.js SDK for Ola Maps API",
3
+ "version": "1.3.0",
4
+ "description": "Complete Ola Maps API SDK for Node.js — Places, Routing, Roads, Geofencing, Elevation, Tiles",
5
5
  "main": "src/index.js",
6
6
  "keywords": [
7
7
  "ola",
@@ -11,12 +11,27 @@
11
11
  "maps api",
12
12
  "ola maps sdk",
13
13
  "ola maps api",
14
- "ola maps sdk for node.js"
14
+ "maplibre",
15
+ "geocoding",
16
+ "routing",
17
+ "geofencing",
18
+ "elevation",
19
+ "places api",
20
+ "distance matrix",
21
+ "snap to road"
15
22
  ],
16
23
  "author": "Kunal Kongkan Kashyap",
17
24
  "license": "MIT",
18
25
  "dependencies": {
19
26
  "axios": "^1.7.2",
20
27
  "uuid": "^10.0.0"
21
- }
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/kunalkcube/ola-map-sdk"
32
+ },
33
+ "bugs": {
34
+ "url": "https://github.com/kunalkcube/ola-map-sdk/issues"
35
+ },
36
+ "homepage": "https://github.com/kunalkcube/ola-map-sdk#readme"
22
37
  }
package/src/client.js CHANGED
@@ -3,6 +3,9 @@ const { v4: uuidv4 } = require('uuid');
3
3
  const Places = require('./endpoints/places');
4
4
  const Tiles = require('./endpoints/tiles');
5
5
  const Routing = require('./endpoints/routing');
6
+ const Roads = require('./endpoints/roads');
7
+ const Geofencing = require('./endpoints/geofencing');
8
+ const Elevation = require('./endpoints/elevation');
6
9
 
7
10
  class OlaMapsClient {
8
11
  constructor(apiKey) {
@@ -31,6 +34,61 @@ class OlaMapsClient {
31
34
  this.places = new Places(this.client, this.apiKey);
32
35
  this.tiles = new Tiles(this.client, this.apiKey);
33
36
  this.routing = new Routing(this.client, this.apiKey);
37
+ this.roads = new Roads(this.client, this.apiKey);
38
+ this.geofencing = new Geofencing(this.client, this.apiKey);
39
+ this.elevation = new Elevation(this.client, this.apiKey);
40
+ }
41
+
42
+ // ── Map Helpers ──────────────────────────────────
43
+
44
+ /**
45
+ * Get the full style URL for use with MapLibre GL.
46
+ * @param {string} [styleName='default-light-standard']
47
+ * @returns {string}
48
+ */
49
+ getStyleURL(styleName = 'default-light-standard') {
50
+ return `https://api.olamaps.io/tiles/vector/v1/styles/${styleName}/style.json`;
51
+ }
52
+
53
+ /**
54
+ * Get a transformRequest function pre-configured with your API key.
55
+ * Pass this directly to MapLibre GL's map options.
56
+ * @returns {Function}
57
+ */
58
+ getTransformRequest() {
59
+ const apiKey = this.apiKey;
60
+ return (url, resourceType) => {
61
+ url = url.replace('app.olamaps.io', 'api.olamaps.io');
62
+ const separator = url.includes('?') ? '&' : '?';
63
+ return { url: `${url}${separator}api_key=${apiKey}`, resourceType };
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Get a complete options object for new maplibregl.Map().
69
+ * Just pass the result directly:
70
+ * const map = new maplibregl.Map(client.getMapOptions({ container: 'map' }));
71
+ *
72
+ * @param {Object} options
73
+ * @param {string|HTMLElement} options.container - DOM element or element ID
74
+ * @param {[number, number]} [options.center=[77.61, 12.93]] - [lng, lat]
75
+ * @param {number} [options.zoom=14] - Zoom level
76
+ * @param {string} [options.style='default-light-standard'] - Ola Maps style name
77
+ * @returns {Object} Ready-to-use MapLibre GL map options
78
+ */
79
+ getMapOptions(options = {}) {
80
+ return {
81
+ container: options.container,
82
+ style: this.getStyleURL(options.style || 'default-light-standard'),
83
+ center: options.center || [77.61, 12.93],
84
+ zoom: options.zoom ?? 14,
85
+ transformRequest: this.getTransformRequest(),
86
+ ...options,
87
+ // Override style again in case user passed style as string name
88
+ ...(typeof options.style === 'string' && !options.style.startsWith('http')
89
+ ? { style: this.getStyleURL(options.style) }
90
+ : {}),
91
+ };
34
92
  }
35
93
  }
36
94
 
@@ -0,0 +1,58 @@
1
+ class Elevation {
2
+ constructor(client, apiKey) {
3
+ this.client = client;
4
+ this.apiKey = apiKey;
5
+ }
6
+
7
+ /**
8
+ * Get elevation for a single location.
9
+ * @param {number} lat - Latitude
10
+ * @param {number} lng - Longitude
11
+ */
12
+ async getElevation(lat, lng) {
13
+ if (typeof lat !== 'number' || typeof lng !== 'number') {
14
+ throw new TypeError('Latitude and longitude must be numbers');
15
+ }
16
+ try {
17
+ const { data } = await this.client.get('/places/v1/elevation', {
18
+ params: { location: `${lat},${lng}`, api_key: this.apiKey },
19
+ headers: { 'Accept': 'application/json' },
20
+ });
21
+ return data;
22
+ } catch (error) {
23
+ const errorMessage = error.response
24
+ ? `Elevation API Error: ${error.response.status} - ${error.response.data.message}`
25
+ : `Elevation API Error: ${error.message}`;
26
+ console.error(errorMessage);
27
+ throw new Error(errorMessage);
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Get elevations for multiple locations.
33
+ * @param {string[]} locations - Array of "lat,lng" strings (max 25)
34
+ */
35
+ async getMultiElevation(locations) {
36
+ if (!Array.isArray(locations) || locations.length === 0) {
37
+ throw new Error('locations must be a non-empty array of "lat,lng" strings');
38
+ }
39
+ if (locations.length > 25) {
40
+ throw new Error('Maximum 25 locations allowed per request');
41
+ }
42
+ try {
43
+ const { data } = await this.client.post('/places/v1/elevation', { locations }, {
44
+ params: { api_key: this.apiKey },
45
+ headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
46
+ });
47
+ return data;
48
+ } catch (error) {
49
+ const errorMessage = error.response
50
+ ? `Elevation API Error: ${error.response.status} - ${error.response.data.message}`
51
+ : `Elevation API Error: ${error.message}`;
52
+ console.error(errorMessage);
53
+ throw new Error(errorMessage);
54
+ }
55
+ }
56
+ }
57
+
58
+ module.exports = Elevation;
@@ -0,0 +1,118 @@
1
+ class Geofencing {
2
+ constructor(client, apiKey) {
3
+ this.client = client;
4
+ this.apiKey = apiKey;
5
+ }
6
+
7
+ async getRequest(endpoint, params = {}) {
8
+ try {
9
+ const { data } = await this.client.get(endpoint, {
10
+ params: { ...params, api_key: this.apiKey },
11
+ headers: { 'Accept': 'application/json' },
12
+ });
13
+ return data;
14
+ } catch (error) {
15
+ const errorMessage = error.response
16
+ ? `Geofencing API Error: ${error.response.status} - ${error.response.data.message}`
17
+ : `Geofencing API Error: ${error.message}`;
18
+ console.error(errorMessage);
19
+ throw new Error(errorMessage);
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Create a new geofence.
25
+ * @param {Object} data - { name, type ('polygon'|'circle'), coordinates, radius, status ('active'|'inactive'), projectId }
26
+ */
27
+ async create(geofenceData) {
28
+ if (!geofenceData) throw new Error('geofence data is required');
29
+ try {
30
+ const { data } = await this.client.post('/places/v1/geofence', geofenceData, {
31
+ params: { api_key: this.apiKey },
32
+ headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
33
+ });
34
+ return data;
35
+ } catch (error) {
36
+ const errorMessage = error.response
37
+ ? `Geofencing API Error: ${error.response.status} - ${error.response.data.message}`
38
+ : `Geofencing API Error: ${error.message}`;
39
+ console.error(errorMessage);
40
+ throw new Error(errorMessage);
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Update an existing geofence.
46
+ * @param {string} id - Geofence ID
47
+ * @param {Object} data - Updated geofence data
48
+ */
49
+ async update(id, geofenceData) {
50
+ if (!id || !geofenceData) throw new Error('id and geofence data are required');
51
+ try {
52
+ const { data } = await this.client.put(`/places/v1/geofence/${encodeURIComponent(id)}`, geofenceData, {
53
+ params: { api_key: this.apiKey },
54
+ headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
55
+ });
56
+ return data;
57
+ } catch (error) {
58
+ const errorMessage = error.response
59
+ ? `Geofencing API Error: ${error.response.status} - ${error.response.data.message}`
60
+ : `Geofencing API Error: ${error.message}`;
61
+ console.error(errorMessage);
62
+ throw new Error(errorMessage);
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Get a geofence by ID.
68
+ * @param {string} id - Geofence ID
69
+ */
70
+ getById(id) {
71
+ if (!id) throw new Error('id is required');
72
+ return this.getRequest(`/places/v1/geofence/${encodeURIComponent(id)}`);
73
+ }
74
+
75
+ /**
76
+ * Delete a geofence by ID.
77
+ * @param {string} id - Geofence ID
78
+ */
79
+ async deleteById(id) {
80
+ if (!id) throw new Error('id is required');
81
+ try {
82
+ const { data } = await this.client.delete(`/places/v1/geofence/${encodeURIComponent(id)}`, {
83
+ params: { api_key: this.apiKey },
84
+ headers: { 'Accept': 'application/json' },
85
+ });
86
+ return data;
87
+ } catch (error) {
88
+ const errorMessage = error.response
89
+ ? `Geofencing API Error: ${error.response.status} - ${error.response.data.message}`
90
+ : `Geofencing API Error: ${error.message}`;
91
+ console.error(errorMessage);
92
+ throw new Error(errorMessage);
93
+ }
94
+ }
95
+
96
+ /**
97
+ * List geofences for a project.
98
+ * @param {string} projectId - Project ID
99
+ * @param {number} page - Page number
100
+ * @param {number} size - Records per page
101
+ */
102
+ list(projectId, page = 1, size = 10) {
103
+ if (!projectId) throw new Error('projectId is required');
104
+ return this.getRequest('/places/v1/geofences', { projectId, page, size });
105
+ }
106
+
107
+ /**
108
+ * Check if coordinates are inside/outside a geofence.
109
+ * @param {string} geofenceId - Geofence ID
110
+ * @param {string} coordinates - lat,lng format
111
+ */
112
+ checkStatus(geofenceId, coordinates) {
113
+ if (!geofenceId || !coordinates) throw new Error('geofenceId and coordinates are required');
114
+ return this.getRequest('/places/v1/geofence/status', { geofenceId, coordinates });
115
+ }
116
+ }
117
+
118
+ module.exports = Geofencing;
@@ -19,19 +19,87 @@ class Places {
19
19
  }
20
20
  }
21
21
 
22
- autocomplete(input) {
23
- return this.request('/places/v1/autocomplete', { input });
22
+ autocomplete(input, options = {}) {
23
+ const params = { input };
24
+ if (options.location) params.location = options.location;
25
+ if (options.radius != null) params.radius = options.radius;
26
+ if (options.strictbounds != null) params.strictbounds = options.strictbounds;
27
+ if (options.language) params.language = options.language;
28
+ if (options.types) params.types = options.types;
29
+ return this.request('/places/v1/autocomplete', params);
24
30
  }
25
31
 
26
- geocode(address) {
27
- return this.request('/places/v1/geocode', { address });
32
+ geocode(address, language) {
33
+ const params = { address };
34
+ if (language) params.language = language;
35
+ return this.request('/places/v1/geocode', params);
28
36
  }
29
37
 
30
- reverseGeocode(lat, lng) {
38
+ reverseGeocode(lat, lng, language) {
31
39
  if (typeof lat !== 'number' || typeof lng !== 'number') {
32
40
  throw new TypeError('Latitude and longitude must be numbers');
33
41
  }
34
- return this.request('/places/v1/reverse-geocode', { latlng: `${lat},${lng}` });
42
+ const params = { latlng: `${lat},${lng}` };
43
+ if (language) params.language = language;
44
+ return this.request('/places/v1/reverse-geocode', params);
45
+ }
46
+
47
+ placeDetails(placeId, language) {
48
+ if (!placeId) throw new Error('place_id is required');
49
+ const params = { place_id: placeId };
50
+ if (language) params.language = language;
51
+ return this.request('/places/v1/details', params);
52
+ }
53
+
54
+ placeDetailsAdvanced(placeId, language) {
55
+ if (!placeId) throw new Error('place_id is required');
56
+ const params = { place_id: placeId };
57
+ if (language) params.language = language;
58
+ return this.request('/places/v1/details/advanced', params);
59
+ }
60
+
61
+ nearbySearch(location, options = {}) {
62
+ if (!location) throw new Error('location is required (lat,lng format)');
63
+ const params = { location };
64
+ if (options.types) params.types = options.types;
65
+ if (options.language) params.language = options.language;
66
+ if (options.radius != null) params.radius = options.radius;
67
+ if (options.withCentroid != null) params.withCentroid = options.withCentroid;
68
+ if (options.rankBy) params.rankBy = options.rankBy;
69
+ if (options.limit != null) params.limit = options.limit;
70
+ return this.request('/places/v1/nearbysearch', params);
71
+ }
72
+
73
+ nearbySearchAdvanced(location, options = {}) {
74
+ if (!location) throw new Error('location is required (lat,lng format)');
75
+ const params = { location };
76
+ if (options.types) params.types = options.types;
77
+ if (options.language) params.language = options.language;
78
+ if (options.radius != null) params.radius = options.radius;
79
+ if (options.withCentroid != null) params.withCentroid = options.withCentroid;
80
+ if (options.rankBy) params.rankBy = options.rankBy;
81
+ if (options.limit != null) params.limit = options.limit;
82
+ return this.request('/places/v1/nearbysearch/advanced', params);
83
+ }
84
+
85
+ textSearch(input, options = {}) {
86
+ if (!input) throw new Error('input text is required');
87
+ const params = { input };
88
+ if (options.location) params.location = options.location;
89
+ if (options.radius != null) params.radius = options.radius;
90
+ if (options.types) params.types = options.types;
91
+ if (options.size != null) params.size = options.size;
92
+ return this.request('/places/v1/textsearch', params);
93
+ }
94
+
95
+ addressValidation(address) {
96
+ if (!address) throw new Error('address is required');
97
+ return this.request('/places/v1/addressvalidation', { address });
98
+ }
99
+
100
+ photo(photoReference) {
101
+ if (!photoReference) throw new Error('photo_reference is required');
102
+ return this.request('/places/v1/photo', { photo_reference: photoReference });
35
103
  }
36
104
  }
37
105
 
@@ -0,0 +1,57 @@
1
+ class Roads {
2
+ constructor(client, apiKey) {
3
+ this.client = client;
4
+ this.apiKey = apiKey;
5
+ }
6
+
7
+ async request(endpoint, params = {}) {
8
+ try {
9
+ const { data } = await this.client.get(endpoint, {
10
+ params: { ...params, api_key: this.apiKey },
11
+ headers: { 'Accept': 'application/json' },
12
+ });
13
+ return data;
14
+ } catch (error) {
15
+ const errorMessage = error.response
16
+ ? `Roads API Error: ${error.response.status} - ${error.response.data.message}`
17
+ : `Roads API Error: ${error.message}`;
18
+ console.error(errorMessage);
19
+ throw new Error(errorMessage);
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Snap coordinates to the nearest road segments.
25
+ * @param {string} points - Pipe-separated lat,lng pairs (max 50)
26
+ * @param {boolean} [enhancePath=false] - Add intermediate points for road curvature
27
+ */
28
+ snapToRoad(points, enhancePath = false) {
29
+ if (!points) throw new Error('points are required');
30
+ return this.request('/routing/v1/snapToRoad', { points, enhancePath });
31
+ }
32
+
33
+ /**
34
+ * Find nearest roads for each coordinate.
35
+ * @param {string} points - Pipe-separated lat,lng pairs (max 100)
36
+ * @param {string} mode - DRIVING, WALKING, BICYCLING, or TRANSIT
37
+ * @param {number} [radius=500] - Search radius in meters
38
+ */
39
+ nearestRoads(points, mode, radius) {
40
+ if (!points || !mode) throw new Error('points and mode are required');
41
+ const params = { points, mode };
42
+ if (radius != null) params.radius = radius;
43
+ return this.request('/routing/v1/nearestRoads', params);
44
+ }
45
+
46
+ /**
47
+ * Get speed limits for snapped road segments.
48
+ * @param {string} points - Pipe-separated lat,lng pairs (max 50)
49
+ * @param {string} [snapStrategy='snaptoroad'] - snaptoroad or nearestroad
50
+ */
51
+ speedLimits(points, snapStrategy = 'snaptoroad') {
52
+ if (!points) throw new Error('points are required');
53
+ return this.request('/routing/v1/speedLimits', { points, snapStrategy });
54
+ }
55
+ }
56
+
57
+ module.exports = Roads;
@@ -4,32 +4,153 @@ class Routing {
4
4
  this.apiKey = apiKey;
5
5
  }
6
6
 
7
- async getDirections(origin, destination, options = {}) {
7
+ async postRequest(endpoint, params) {
8
+ try {
9
+ const { data } = await this.client.post(endpoint, null, {
10
+ params: { ...params, api_key: this.apiKey },
11
+ headers: { 'Accept': 'application/json' },
12
+ });
13
+ return data;
14
+ } catch (error) {
15
+ const errorMessage = error.response
16
+ ? `Routing API Error: ${error.response.status} - ${error.response.data.message}`
17
+ : `Routing API Error: ${error.message}`;
18
+ console.error(errorMessage);
19
+ throw new Error(errorMessage);
20
+ }
21
+ }
22
+
23
+ async getRequest(endpoint, params) {
24
+ try {
25
+ const { data } = await this.client.get(endpoint, {
26
+ params: { ...params, api_key: this.apiKey },
27
+ headers: { 'Accept': 'application/json' },
28
+ });
29
+ return data;
30
+ } catch (error) {
31
+ const errorMessage = error.response
32
+ ? `Routing API Error: ${error.response.status} - ${error.response.data.message}`
33
+ : `Routing API Error: ${error.message}`;
34
+ console.error(errorMessage);
35
+ throw new Error(errorMessage);
36
+ }
37
+ }
38
+
39
+ getDirections(origin, destination, options = {}) {
8
40
  const { lat: originLat, lon: originLon } = origin;
9
41
  const { lat: destLat, lon: destLon } = destination;
10
42
 
11
43
  const params = {
12
- api_key: this.apiKey,
13
44
  origin: `${originLat},${originLon}`,
14
45
  destination: `${destLat},${destLon}`,
15
46
  alternatives: options.alternatives ?? false,
16
- steps: options.steps ?? false,
47
+ steps: options.steps ?? true,
17
48
  overview: options.overview ?? 'full',
18
49
  language: options.language ?? 'en',
19
50
  traffic_metadata: options.traffic_metadata ?? false,
20
51
  };
52
+ if (options.waypoints) params.waypoints = options.waypoints;
53
+ if (options.mode) params.mode = options.mode;
54
+ if (options.route_preference) params.route_preference = options.route_preference;
55
+
56
+ return this.postRequest('/routing/v1/directions', params);
57
+ }
58
+
59
+ getDirectionsBasic(origin, destination, options = {}) {
60
+ const { lat: originLat, lon: originLon } = origin;
61
+ const { lat: destLat, lon: destLon } = destination;
62
+
63
+ const params = {
64
+ origin: `${originLat},${originLon}`,
65
+ destination: `${destLat},${destLon}`,
66
+ alternatives: options.alternatives ?? false,
67
+ steps: options.steps ?? true,
68
+ overview: options.overview ?? 'full',
69
+ language: options.language ?? 'en',
70
+ };
71
+ if (options.waypoints) params.waypoints = options.waypoints;
72
+ if (options.route_preference) params.route_preference = options.route_preference;
73
+
74
+ return this.postRequest('/routing/v1/directions/basic', params);
75
+ }
76
+
77
+ getDistanceMatrix(origins, destinations, options = {}) {
78
+ if (!origins || !destinations) {
79
+ throw new Error('origins and destinations are required');
80
+ }
81
+ const params = {
82
+ origins,
83
+ destinations,
84
+ mode: options.mode ?? 'driving',
85
+ };
86
+ if (options.route_preference) params.route_preference = options.route_preference;
87
+
88
+ return this.getRequest('/routing/v1/distanceMatrix', params);
89
+ }
90
+
91
+ getDistanceMatrixBasic(origins, destinations, options = {}) {
92
+ if (!origins || !destinations) {
93
+ throw new Error('origins and destinations are required');
94
+ }
95
+ const params = { origins, destinations };
96
+ if (options.route_preference) params.route_preference = options.route_preference;
97
+
98
+ return this.getRequest('/routing/v1/distanceMatrix/basic', params);
99
+ }
100
+
101
+ routeOptimizer(locations, options = {}) {
102
+ if (!locations) throw new Error('locations are required');
103
+
104
+ const params = {
105
+ locations,
106
+ source: options.source ?? 'first',
107
+ destination: options.destination ?? 'last',
108
+ round_trip: options.round_trip ?? false,
109
+ mode: options.mode ?? 'driving',
110
+ steps: options.steps ?? true,
111
+ overview: options.overview ?? 'full',
112
+ language: options.language ?? 'en',
113
+ traffic_metadata: options.traffic_metadata ?? false,
114
+ };
115
+ if (options.route_preference) params.route_preference = options.route_preference;
116
+
117
+ return this.postRequest('/routing/v1/routeOptimizer', params);
118
+ }
119
+
120
+ async fleetPlanner(inputData, strategy, options = {}) {
121
+ if (!inputData || !strategy) {
122
+ throw new Error('inputData and strategy are required');
123
+ }
124
+
125
+ const FormData = require('form-data');
126
+ const form = new FormData();
127
+
128
+ if (typeof inputData === 'string') {
129
+ const fs = require('fs');
130
+ form.append('input', fs.createReadStream(inputData));
131
+ } else {
132
+ form.append('input', Buffer.from(JSON.stringify(inputData)), {
133
+ filename: 'input.json',
134
+ contentType: 'application/json',
135
+ });
136
+ }
137
+
138
+ const params = {
139
+ strategy,
140
+ api_key: this.apiKey,
141
+ };
142
+ if (options.route_preference) params.route_preference = options.route_preference;
21
143
 
22
144
  try {
23
- const { data } = await this.client.post('/routing/v1/directions', null, {
145
+ const { data } = await this.client.post('/routing/v1/fleetPlanner', form, {
24
146
  params,
25
- headers: { 'Accept': 'application/json' },
147
+ headers: { ...form.getHeaders() },
26
148
  });
27
-
28
149
  return data;
29
150
  } catch (error) {
30
151
  const errorMessage = error.response
31
- ? `Routing API Error: ${error.response.status} - ${error.response.data.message}`
32
- : `Routing API Error: ${error.message}`;
152
+ ? `Fleet Planner API Error: ${error.response.status} - ${error.response.data.message}`
153
+ : `Fleet Planner API Error: ${error.message}`;
33
154
  console.error(errorMessage);
34
155
  throw new Error(errorMessage);
35
156
  }
@@ -50,6 +50,66 @@ class Tiles {
50
50
  'arraybuffer'
51
51
  );
52
52
  }
53
+
54
+ /**
55
+ * Get a static map image centered on a specific point.
56
+ * @param {string} styleName - e.g. 'default-light-standard'
57
+ * @param {number} lon - Longitude
58
+ * @param {number} lat - Latitude
59
+ * @param {number} zoom - Zoom level (0-23)
60
+ * @param {number} width - Image width (1-2048)
61
+ * @param {number} height - Image height (1-2048)
62
+ * @param {string} format - 'png' or 'jpg'
63
+ * @param {Object} [options] - { marker, path }
64
+ */
65
+ getStaticMapByCenter(styleName, lon, lat, zoom, width, height, format, options = {}) {
66
+ const endpoint = `/tiles/v1/styles/${encodeURIComponent(styleName)}/static/${lon},${lat},${zoom}/${width}x${height}.${format}`;
67
+ const params = {};
68
+ if (options.marker) params.marker = options.marker;
69
+ if (options.path) params.path = options.path;
70
+ return this.request(endpoint, params, {}, 'arraybuffer');
71
+ }
72
+
73
+ /**
74
+ * Get a static map image for a bounding box.
75
+ * @param {string} styleName
76
+ * @param {{ minx: number, miny: number, maxx: number, maxy: number }} bbox
77
+ * @param {number} width
78
+ * @param {number} height
79
+ * @param {string} format
80
+ * @param {Object} [options]
81
+ */
82
+ getStaticMapByBBox(styleName, bbox, width, height, format, options = {}) {
83
+ const { minx, miny, maxx, maxy } = bbox;
84
+ const endpoint = `/tiles/v1/styles/${encodeURIComponent(styleName)}/static/${minx},${miny},${maxx},${maxy}/${width}x${height}.${format}`;
85
+ const params = {};
86
+ if (options.marker) params.marker = options.marker;
87
+ if (options.path) params.path = options.path;
88
+ return this.request(endpoint, params, {}, 'arraybuffer');
89
+ }
90
+
91
+ /**
92
+ * Get a static map image with auto-fit bounds.
93
+ * @param {string} styleName
94
+ * @param {number} width
95
+ * @param {number} height
96
+ * @param {string} format
97
+ * @param {Object} [options]
98
+ */
99
+ getStaticMapAuto(styleName, width, height, format, options = {}) {
100
+ const endpoint = `/tiles/v1/styles/${encodeURIComponent(styleName)}/static/auto/${width}x${height}.${format}`;
101
+ const params = {};
102
+ if (options.marker) params.marker = options.marker;
103
+ if (options.path) params.path = options.path;
104
+ return this.request(endpoint, params, {}, 'arraybuffer');
105
+ }
106
+
107
+ /**
108
+ * Get 3D tileset JSON.
109
+ */
110
+ get3DTileset() {
111
+ return this.request('/tiles/vector/v1/3dtiles/tileset.json');
112
+ }
53
113
  }
54
114
 
55
115
  module.exports = Tiles;
package/src/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const OlaMapsClient = require('./client');
2
2
 
3
3
  module.exports = OlaMapsClient;
4
-
4
+ module.exports.OlaMapsClient = OlaMapsClient;
5
+ module.exports.default = OlaMapsClient;