0
# Result Formatting
1
2
Transform geocoding results into different output formats including GPX XML and custom string templates.
3
4
## Capabilities
5
6
### GPX Formatter
7
8
Converts geocoding results into GPX (GPS Exchange Format) XML for use with GPS devices and mapping applications.
9
10
```javascript { .api }
11
/**
12
* GPX formatter configuration
13
*/
14
interface GpxFormatterConfig {
15
/** Formatter type */
16
formatter: 'gpx';
17
}
18
19
/**
20
* GPX formatter class
21
*/
22
class GpxFormatter {
23
constructor();
24
/**
25
* Format geocoding results as GPX XML
26
* @param {GeocodeResult[]} data - Array of geocoding results
27
* @returns {string} GPX XML string
28
*/
29
format(data: GeocodeResult[]): string;
30
}
31
```
32
33
**Usage Examples:**
34
35
```javascript
36
const NodeGeocoder = require('node-geocoder');
37
38
// Create geocoder with GPX formatter
39
const geocoder = NodeGeocoder('google', {
40
apiKey: 'YOUR_API_KEY',
41
formatter: 'gpx'
42
});
43
44
// Geocode and get GPX output
45
const gpxResult = await geocoder.geocode([
46
'Eiffel Tower, Paris',
47
'Big Ben, London',
48
'Colosseum, Rome'
49
]);
50
51
console.log(gpxResult);
52
// Output: GPX XML string with waypoints
53
54
// Save to file
55
const fs = require('fs');
56
fs.writeFileSync('locations.gpx', gpxResult);
57
```
58
59
**GPX Output Format:**
60
61
```xml
62
<?xml version="1.0" encoding="UTF-8"?>
63
<gpx version="1.1" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" creator="geocoder.js">
64
<wpt lat="48.8583701" lon="2.2944813">
65
<name></name>
66
</wpt>
67
<wpt lat="51.5007292" lon="-0.1246254">
68
<name></name>
69
</wpt>
70
</gpx>
71
```
72
73
### String Formatter
74
75
Formats geocoding results using customizable string patterns with placeholder substitution.
76
77
```javascript { .api }
78
/**
79
* String formatter configuration
80
*/
81
interface StringFormatterConfig {
82
/** Formatter type */
83
formatter: 'string';
84
/** Template pattern with placeholders */
85
formatterPattern: string;
86
}
87
88
/**
89
* String formatter class
90
*/
91
class StringFormatter {
92
/**
93
* Create string formatter with pattern
94
* @param {string} pattern - Template pattern with placeholders
95
*/
96
constructor(pattern: string);
97
98
/**
99
* Format geocoding results using the pattern
100
* @param {GeocodeResult[]} data - Array of geocoding results
101
* @returns {string[]} Array of formatted strings
102
*/
103
format(data: GeocodeResult[]): string[];
104
}
105
```
106
107
**Pattern Placeholders:**
108
109
```javascript { .api }
110
/**
111
* Available placeholders for string formatter patterns
112
*/
113
interface StringPlaceholders {
114
'%n': 'streetNumber'; // Street number
115
'%S': 'streetName'; // Street name
116
'%z': 'zipcode'; // ZIP/postal code
117
'%P': 'country'; // Country name
118
'%p': 'countryCode'; // Country code
119
'%c': 'city'; // City name
120
'%T': 'state'; // State/province name
121
'%t': 'stateCode'; // State/province code
122
}
123
```
124
125
**Usage Examples:**
126
127
```javascript
128
// Create geocoder with string formatter
129
const geocoder = NodeGeocoder('google', {
130
apiKey: 'YOUR_API_KEY',
131
formatter: 'string',
132
formatterPattern: '%n %S, %c, %P %z' // "123 Main St, New York, United States 10001"
133
});
134
135
// Geocode and get formatted strings
136
const addresses = await geocoder.geocode([
137
'1600 Amphitheatre Parkway, Mountain View, CA',
138
'Times Square, New York, NY'
139
]);
140
141
console.log(addresses);
142
// Output: [
143
// "1600 Amphitheatre Parkway, Mountain View, United States 94043",
144
// " Times Square, New York, United States "
145
// ]
146
147
// Custom patterns for different use cases
148
const patterns = {
149
simple: '%c, %P', // "Paris, France"
150
detailed: '%n %S, %c %z, %P', // "123 Main St, Paris 75001, France"
151
coordinates: '%c (%lat, %lon)', // Not directly supported - use custom logic
152
postal: '%c %z' // "Paris 75001"
153
};
154
155
// Multiple formatters for different outputs
156
const cityFormatter = NodeGeocoder('google', {
157
apiKey: 'YOUR_API_KEY',
158
formatter: 'string',
159
formatterPattern: '%c, %P'
160
});
161
162
const fullFormatter = NodeGeocoder('google', {
163
apiKey: 'YOUR_API_KEY',
164
formatter: 'string',
165
formatterPattern: '%n %S, %c, %T %z, %P'
166
});
167
```
168
169
### Custom Formatting
170
171
Create custom formatters by processing the standard GeocodeResult objects.
172
173
```javascript { .api }
174
/**
175
* Standard geocode result structure for custom formatting
176
*/
177
interface GeocodeResult {
178
formattedAddress: string;
179
latitude: number;
180
longitude: number;
181
country?: string;
182
countryCode?: string;
183
city?: string;
184
zipcode?: string;
185
streetName?: string;
186
streetNumber?: string;
187
administrativeLevels?: {
188
level1long?: string;
189
level1short?: string;
190
level2long?: string;
191
level2short?: string;
192
level3long?: string;
193
level3short?: string;
194
level4long?: string;
195
level4short?: string;
196
level5long?: string;
197
level5short?: string;
198
};
199
extra?: {
200
confidence?: number;
201
[key: string]: any;
202
};
203
provider: string;
204
}
205
```
206
207
**Custom Formatting Examples:**
208
209
```javascript
210
const NodeGeocoder = require('node-geocoder');
211
212
// Standard geocoder without formatter
213
const geocoder = NodeGeocoder('google', {
214
apiKey: 'YOUR_API_KEY'
215
});
216
217
// Custom JSON formatter
218
function formatAsJson(results) {
219
return results.map(result => ({
220
address: result.formattedAddress,
221
coordinates: [result.longitude, result.latitude],
222
components: {
223
street: `${result.streetNumber || ''} ${result.streetName || ''}`.trim(),
224
city: result.city,
225
country: result.country,
226
postal: result.zipcode
227
},
228
confidence: result.extra?.confidence,
229
provider: result.provider
230
}));
231
}
232
233
// Custom CSV formatter
234
function formatAsCsv(results) {
235
const header = 'address,latitude,longitude,city,country,zipcode';
236
const rows = results.map(r =>
237
`"${r.formattedAddress}",${r.latitude},${r.longitude},"${r.city || ''}","${r.country || ''}","${r.zipcode || ''}"`
238
);
239
return [header, ...rows].join('\n');
240
}
241
242
// Custom coordinates formatter
243
function formatAsCoordinates(results) {
244
return results.map(result =>
245
`${result.latitude},${result.longitude}`
246
);
247
}
248
249
// Usage
250
const results = await geocoder.geocode(['Paris, France', 'London, UK']);
251
252
const jsonFormat = formatAsJson(results);
253
const csvFormat = formatAsCsv(results);
254
const coordinates = formatAsCoordinates(results);
255
256
console.log('JSON:', jsonFormat);
257
console.log('CSV:', csvFormat);
258
console.log('Coordinates:', coordinates);
259
```
260
261
### Formatter Error Handling
262
263
Handle formatting errors and edge cases in result data.
264
265
```javascript { .api }
266
/**
267
* Formatter error handling
268
*/
269
interface FormatterError extends Error {
270
message: string;
271
name: 'FormatterError';
272
}
273
```
274
275
**Error Handling Examples:**
276
277
```javascript
278
// String formatter requires pattern
279
try {
280
const geocoder = NodeGeocoder('google', {
281
apiKey: 'YOUR_API_KEY',
282
formatter: 'string'
283
// Missing formatterPattern
284
});
285
} catch (error) {
286
console.error(error.message); // "StringFormatter need a pattern"
287
}
288
289
// Handle missing data in custom formatters
290
function safeStringFormat(pattern, result) {
291
return pattern
292
.replace(/%n/g, result.streetNumber || '')
293
.replace(/%S/g, result.streetName || '')
294
.replace(/%z/g, result.zipcode || '')
295
.replace(/%P/g, result.country || '')
296
.replace(/%p/g, result.countryCode || '')
297
.replace(/%c/g, result.city || '')
298
.replace(/%T/g, result.administrativeLevels?.level1long || '')
299
.replace(/%t/g, result.administrativeLevels?.level1short || '');
300
}
301
302
// Robust custom formatter with error handling
303
function robustFormatter(results, format) {
304
try {
305
return results.map(result => {
306
if (!result || typeof result !== 'object') {
307
return 'Invalid result';
308
}
309
310
switch (format) {
311
case 'coordinates':
312
return `${result.latitude || 0},${result.longitude || 0}`;
313
case 'address':
314
return result.formattedAddress || 'Unknown address';
315
default:
316
return JSON.stringify(result);
317
}
318
});
319
} catch (error) {
320
console.error('Formatting error:', error);
321
return ['Formatting failed'];
322
}
323
}
324
```