0
# Input/Output
1
2
Convert geometries to and from standard spatial data formats including Well-Known Text (WKT), Well-Known Binary (WKB), and GeoJSON. These functions enable interoperability with other spatial libraries and data storage systems.
3
4
## Capabilities
5
6
### Well-Known Text (WKT)
7
8
Text-based representation of geometries using OGC standard format.
9
10
```python { .api }
11
def to_wkt(geometry, rounding_precision=None, trim=True, output_dimension=None, old_3d=False, **kwargs):
12
"""
13
Convert geometry to Well-Known Text format.
14
15
Parameters:
16
- geometry: input geometry or array of geometries
17
- rounding_precision: decimal places for coordinates (None for no rounding)
18
- trim: remove trailing zeros from coordinates
19
- output_dimension: force 2D or 3D output (None for auto-detect)
20
- old_3d: use old-style 3D WKT format
21
22
Returns:
23
str or ndarray of str: WKT representation
24
"""
25
26
def from_wkt(wkt, on_invalid='raise', **kwargs):
27
"""
28
Create geometry from Well-Known Text string.
29
30
Parameters:
31
- wkt: WKT string or array of WKT strings
32
- on_invalid: error handling ('raise', 'warn', 'ignore', 'fix')
33
34
Returns:
35
Geometry or ndarray of geometries
36
"""
37
```
38
39
**Usage Example:**
40
41
```python
42
import shapely
43
from shapely.geometry import Point, Polygon
44
45
# Convert to WKT
46
point = Point(1.123456, 2.654321)
47
point_wkt = shapely.to_wkt(point)
48
print(point_wkt) # 'POINT (1.123456 2.654321)'
49
50
# With rounding
51
point_wkt_rounded = shapely.to_wkt(point, rounding_precision=2)
52
print(point_wkt_rounded) # 'POINT (1.12 2.65)'
53
54
# Complex geometry
55
polygon = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])
56
poly_wkt = shapely.to_wkt(polygon)
57
print(poly_wkt) # 'POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))'
58
59
# Convert from WKT
60
wkt_string = "LINESTRING (0 0, 1 1, 2 0)"
61
line = shapely.from_wkt(wkt_string)
62
print(f"Line length: {line.length:.2f}")
63
64
# Array operations
65
wkt_array = [
66
"POINT (0 0)",
67
"POINT (1 1)",
68
"LINESTRING (0 0, 2 2)"
69
]
70
geometries = shapely.from_wkt(wkt_array)
71
print(f"Created {len(geometries)} geometries")
72
```
73
74
### Well-Known Binary (WKB)
75
76
Binary representation for efficient storage and transmission.
77
78
```python { .api }
79
def to_wkb(geometry, hex=False, output_dimension=None, byte_order=None, include_srid=False, flavor='extended', **kwargs):
80
"""
81
Convert geometry to Well-Known Binary format.
82
83
Parameters:
84
- geometry: input geometry or array of geometries
85
- hex: return hexadecimal string instead of bytes
86
- output_dimension: force 2D or 3D output
87
- byte_order: byte order (-1 for little-endian, 1 for big-endian)
88
- include_srid: include SRID in output
89
- flavor: WKB flavor ('extended' or 'iso')
90
91
Returns:
92
bytes or str (if hex=True) or ndarray
93
"""
94
95
def from_wkb(wkb, on_invalid='raise', **kwargs):
96
"""
97
Create geometry from Well-Known Binary data.
98
99
Parameters:
100
- wkb: WKB bytes, hex string, or array of WKB data
101
- on_invalid: error handling ('raise', 'warn', 'ignore', 'fix')
102
103
Returns:
104
Geometry or ndarray of geometries
105
"""
106
```
107
108
**Usage Example:**
109
110
```python
111
import shapely
112
from shapely.geometry import Point
113
114
# Convert to WKB
115
point = Point(1, 2)
116
wkb_bytes = shapely.to_wkb(point)
117
wkb_hex = shapely.to_wkb(point, hex=True)
118
119
print(f"WKB bytes length: {len(wkb_bytes)}")
120
print(f"WKB hex: {wkb_hex}")
121
122
# Convert back from WKB
123
point_from_bytes = shapely.from_wkb(wkb_bytes)
124
point_from_hex = shapely.from_wkb(wkb_hex)
125
126
print(f"Original: {point}")
127
print(f"From bytes: {point_from_bytes}")
128
print(f"Equal: {point.equals(point_from_bytes)}")
129
```
130
131
### GeoJSON
132
133
JSON-based format for web applications and data exchange.
134
135
```python { .api }
136
def to_geojson(geometry, indent=None, **kwargs):
137
"""
138
Convert geometry to GeoJSON format.
139
140
Parameters:
141
- geometry: input geometry or array of geometries
142
- indent: JSON indentation (None for compact format)
143
144
Returns:
145
str or ndarray of str: GeoJSON representation
146
"""
147
148
def from_geojson(geojson, on_invalid='raise', **kwargs):
149
"""
150
Create geometry from GeoJSON string.
151
Requires GEOS 3.10.1+.
152
153
Parameters:
154
- geojson: GeoJSON string or array of GeoJSON strings
155
- on_invalid: error handling ('raise', 'warn', 'ignore', 'fix')
156
157
Returns:
158
Geometry or ndarray of geometries
159
"""
160
```
161
162
**Usage Example:**
163
164
```python
165
import shapely
166
from shapely.geometry import Point, Polygon
167
import json
168
169
# Convert to GeoJSON
170
point = Point(-122.4194, 37.7749) # San Francisco
171
point_geojson = shapely.to_geojson(point)
172
print("Point GeoJSON:")
173
print(json.dumps(json.loads(point_geojson), indent=2))
174
175
# Complex geometry
176
polygon = Polygon([(-122.5, 37.7), (-122.3, 37.7), (-122.3, 37.8), (-122.5, 37.8)])
177
poly_geojson = shapely.to_geojson(polygon, indent=2)
178
print("Polygon GeoJSON:")
179
print(poly_geojson)
180
181
# Convert from GeoJSON
182
geojson_str = '''
183
{
184
"type": "LineString",
185
"coordinates": [[-122.4, 37.7], [-122.4, 37.8], [-122.3, 37.8]]
186
}
187
'''
188
line = shapely.from_geojson(geojson_str)
189
print(f"Line from GeoJSON length: {line.length:.4f}")
190
```
191
192
### Ragged Arrays
193
194
Efficient representation for coordinate data with variable-length sequences.
195
196
```python { .api }
197
def to_ragged_array(geometry, include_z=False, include_m=False, **kwargs):
198
"""
199
Convert geometries to ragged coordinate arrays.
200
201
Parameters:
202
- geometry: input geometry or array of geometries
203
- include_z: include Z coordinates
204
- include_m: include M coordinates
205
206
Returns:
207
tuple: (coordinates, offsets) arrays
208
"""
209
210
def from_ragged_array(coords, offsets, geometry_type, crs=None, **kwargs):
211
"""
212
Create geometries from ragged coordinate arrays.
213
214
Parameters:
215
- coords: coordinate array
216
- offsets: offset array defining geometry boundaries
217
- geometry_type: target geometry type
218
- crs: coordinate reference system (optional)
219
220
Returns:
221
ndarray of geometries
222
"""
223
```
224
225
**Usage Example:**
226
227
```python
228
import shapely
229
import numpy as np
230
231
# Create multiple linestrings
232
lines = [
233
shapely.LineString([(0, 0), (1, 1)]),
234
shapely.LineString([(2, 2), (3, 3), (4, 4)]),
235
shapely.LineString([(5, 5), (6, 6), (7, 7), (8, 8)])
236
]
237
238
# Convert to ragged arrays
239
coords, offsets = shapely.to_ragged_array(lines)
240
print(f"Coordinates shape: {coords.shape}")
241
print(f"Offsets: {offsets}")
242
243
# Convert back to geometries
244
lines_reconstructed = shapely.from_ragged_array(
245
coords, offsets, geometry_type='LineString'
246
)
247
print(f"Reconstructed {len(lines_reconstructed)} lines")
248
249
# Verify reconstruction
250
for original, reconstructed in zip(lines, lines_reconstructed):
251
print(f"Equal: {original.equals(reconstructed)}")
252
```
253
254
### Error Handling
255
256
Control how invalid input data is handled during conversion.
257
258
```python { .api }
259
# Example of error handling options
260
import shapely
261
262
# Invalid WKT
263
invalid_wkt = "POINT (not_a_number 2)"
264
265
try:
266
# Default: raise exception
267
geom = shapely.from_wkt(invalid_wkt, on_invalid='raise')
268
except Exception as e:
269
print(f"Error raised: {e}")
270
271
# Ignore invalid input (returns None)
272
geom = shapely.from_wkt(invalid_wkt, on_invalid='ignore')
273
print(f"Ignored result: {geom}")
274
275
# Try to fix invalid input
276
try:
277
geom = shapely.from_wkt(invalid_wkt, on_invalid='fix')
278
print(f"Fixed result: {geom}")
279
except:
280
print("Could not fix invalid input")
281
```
282
283
### Batch Processing
284
285
Efficient I/O operations on geometry arrays.
286
287
**Usage Example:**
288
289
```python
290
import shapely
291
import numpy as np
292
293
# Create large array of geometries
294
np.random.seed(42)
295
coords = np.random.rand(1000, 2) * 100
296
points = shapely.points(coords)
297
298
# Convert all to WKT efficiently
299
wkt_strings = shapely.to_wkt(points, rounding_precision=1)
300
print(f"Converted {len(wkt_strings)} points to WKT")
301
302
# Convert back
303
points_from_wkt = shapely.from_wkt(wkt_strings)
304
print(f"Reconstructed {len(points_from_wkt)} points")
305
306
# Binary format for efficient storage
307
wkb_data = shapely.to_wkb(points)
308
print(f"WKB data size: {sum(len(wkb) for wkb in wkb_data)} bytes")
309
310
# Hex format for database storage
311
wkb_hex = shapely.to_wkb(points, hex=True)
312
print(f"First WKB hex: {wkb_hex[0]}")
313
```
314
315
## Types
316
317
```python { .api }
318
# Error handling options
319
class DecodingErrorOptions:
320
ignore = 0 # Skip invalid input, return None
321
warn = 1 # Issue warning, return None
322
raise = 2 # Raise exception (default)
323
fix = 3 # Attempt to fix invalid input
324
325
# WKB format options
326
class WKBFlavorOptions:
327
extended = 1 # Extended WKB format (default)
328
iso = 2 # ISO SQL/MM WKB format
329
```