58 lines
1.8 KiB
Python
58 lines
1.8 KiB
Python
import json
|
|
import psycopg2
|
|
from shapely.geometry import shape
|
|
|
|
def import_geojson(filepath):
|
|
conn = psycopg2.connect(
|
|
dbname="gis_data",
|
|
user="osm",
|
|
password="osm",
|
|
host="localhost"
|
|
)
|
|
cur = conn.cursor()
|
|
|
|
try:
|
|
with open(filepath) as f:
|
|
data = json.load(f)
|
|
|
|
if data["type"] != "FeatureCollection":
|
|
raise ValueError("GeoJSON must be a FeatureCollection")
|
|
|
|
for idx, feature in enumerate(data["features"]):
|
|
try:
|
|
geom_type = feature["geometry"]["type"]
|
|
properties = feature["properties"]
|
|
geom = shape(feature["geometry"])
|
|
wkt = geom.wkt
|
|
|
|
# Insert lines
|
|
if geom_type == "LineString":
|
|
cur.execute("""
|
|
INSERT INTO osm_lines (geometry, tags)
|
|
VALUES (ST_GeomFromText(%s, 4326), %s)
|
|
""", (wkt, json.dumps(properties)))
|
|
|
|
# Insert polygons AND multipolygons
|
|
elif geom_type in ("Polygon", "MultiPolygon"):
|
|
cur.execute("""
|
|
INSERT INTO osm_polygons (geometry, tags)
|
|
VALUES (ST_GeomFromText(%s, 4326), %s)
|
|
""", (wkt, json.dumps(properties)))
|
|
|
|
else:
|
|
print(f"Skipping unsupported geometry type: {geom_type}")
|
|
|
|
except Exception as e:
|
|
print(f"Error processing feature {idx}: {e}")
|
|
continue
|
|
|
|
conn.commit()
|
|
|
|
except json.JSONDecodeError:
|
|
print("Invalid JSON file. Ensure filtered.geojson is correctly generated.")
|
|
finally:
|
|
cur.close()
|
|
conn.close()
|
|
|
|
if __name__ == "__main__":
|
|
import_geojson("israel.geojson")
|