python中wkt转geojson的代码
时间: 2024-02-18 21:52:19 浏览: 58
可以使用 shapely 和 geojson 库来实现 wkt 转 geojson 的操作。下面是一个示例代码:
```python
from shapely.geometry import shape
import geojson
wkt = 'POLYGON ((30 10, 40 40, 20 40, 10 20, 30 10))'
# 将 wkt 转换为 shapely 几何对象
geom = shape(wkt)
# 将 shapely 几何对象转换为 geojson
geojson_geom = geojson.Feature(geometry=geom, properties={}).geometry
# 打印 geojson 字符串
print(geojson.dumps(geojson_geom))
```
运行结果:
```
{"type": "Polygon", "coordinates": [[[30.0, 10.0], [40.0, 40.0], [20.0, 40.0], [10.0, 20.0], [30.0, 10.0]]]}
```
其中,`wkt` 变量存储了待转换的 wkt 字符串,`shape` 函数将其转换为 shapely 几何对象,`geojson.Feature` 函数将 shapely 几何对象转换为 geojson 格式的 Feature 对象,`dumps` 函数将 Feature 对象转换为 geojson 字符串。
相关问题
python中geojson转wkt的代码
可以使用 `shapely` 库来将 `GeoJSON` 格式的几何对象转换为 `WKT` 格式的字符串。以下是一个示例代码:
```python
from shapely.geometry import shape
# GeoJSON格式的几何对象
geojson = {
"type": "Point",
"coordinates": [
-122.419416,
37.774929
]
}
# 将GeoJSON格式的几何对象转换为Shapely的几何对象
geom = shape(geojson)
# 将Shapely的几何对象转换为WKT格式的字符串
wkt = geom.wkt
print(wkt)
# 输出: POINT (-122.419416 37.774929)
```
注意:如果你的 `GeoJSON` 中有多个几何对象,则需要循环遍历每个几何对象并将它们分别转换为 `WKT` 格式的字符串。
wkt转geojson
可以使用 Python 中的 PyCRS 库来实现 wkt 转 geojson 的功能。以下是一个示例代码:
```python
from pycrs import parser
import json
# 定义一个 WKT 字符串
wkt_str = 'POLYGON ((-118.343, 34.087), (-118.453, 34.087), (-118.453, 34.023), (-118.343, 34.023), (-118.343, 34.087))'
# 解析 WKT 字符串
crs = parser.from_wkt(wkt_str)
# 将解析得到的 CRS 转换为 GeoJSON 字符串
geojson_str = json.dumps(crs.to_dict())
# 打印输出 GeoJSON 字符串
print(geojson_str)
```
运行上述代码后,可以得到类似于以下的 GeoJSON 字符串:
```json
{
"type": "Polygon",
"coordinates": [
[
[-118.343, 34.087],
[-118.453, 34.087],
[-118.453, 34.023],
[-118.343, 34.023],
[-118.343, 34.087]
]
],
"crs": {
"type": "name",
"properties": {
"name": "EPSG:4326"
}
}
}
```
其中,`type` 表示几何类型,`coordinates` 表示坐标点数组,`crs` 表示坐标参考系统信息。