Skip to content
Snippets Groups Projects
Commit 83e7ca7e authored by Wigal, Jacob (CIV)'s avatar Wigal, Jacob (CIV) :sparkles:
Browse files

removed command-line dependency, added all geopandas drivers support, added...

removed command-line dependency, added all geopandas drivers support, added input, added helpful readouts for troubleshooting
parent f5800cd9
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
### About
This notebook is for the following functions:
This notebook is for:
- Converting Shapefiles to GeoJSON files
- Converting Geopackages to Geo
JSON files
- Converting KMLs to GeoJSON files
Converting geospatial data files such as Shapefiles, Geopackages, and KMLs to GeoJSON files
%% Cell type:markdown id: tags:
# Shapefile/Geopackage/KML to GeoJSON Conversion
%% Cell type:code id: tags:
``` python
import os
import geopandas as gpd
print("Current Working Directory" , os.getcwd())
```
%% Output
Current Working Directory C:\Users\Dan\Anaconda_dan_packages\cid\usvi_gis\usvi-optimzation\Data\jeff_good_data_geojson
%% Cell type:markdown id: tags:
Replace /Users/filepath/etc/ with the filepath of the folder your shapefile/Geopackage is located in.
%% Cell type:code id: tags:
``` python
directory = 'C:/Users/Dan/Anaconda_dan_packages/cid/usvi_gis/usvi-optimzation/Data/jeff_good_data_geojson'
```
%% Cell type:code id: tags:
``` python
os.chdir(location)
!cd $location
print("Current Working Directory" , os.getcwd())
```
%% Output
Current Working Directory C:\Users\Dan\Anaconda_dan_packages\cid\usvi_gis\usvi-optimzation\Data\jeff_good_data_geojson
# GeoJSON Conversion
%% Cell type:markdown id: tags:
### For Shapefiles, Geopackages, KML, and others:
%% Cell type:markdown id: tags:
Running the next cell will make a new folder called geojson within the folder ccurrent working director. Then, it will try to convert any vector layer within the folder ((e.g. if you have three shapefiles in the directory, there will be three converted geojson files). This works for all layers that geopandas can read, which is essentially all normal vector layer types GeoJSON for every shape file. Note: Running this cell will also reproject the data to CRS WGS84 (EPSG 4326) for all files with a different CRS.
Running the next cell will prompt you to enter the filepath of the folder containing all the files you wish to convert to GeoJSON. Then, it will attempt to convert any geospatial data file within the folder ((e.g. if you have three shapefiles in the directory, there will be three converted geojson files). It will place the converted files in a new folder within your directory called "geojson". This works for all layers that geopandas can read, which is essentially all normal vector layer types GeoJSON for every shape file. Note: Running this cell will also reproject the data to CRS WGS84 (EPSG 4326) for all files with a different CRS.
%% Cell type:code id: tags:
``` python
# Make a geojson folder if it doesn't exist
current_directory = os.getcwd()
geojson_directory = current_directory + '/geojson'
if not os.path.exists(current_directory):
os.mkdir('geojson')
# iterate over files and try to convert all to geojson
for file in os.listdir(current_directory):
print('Trying to convert ' + file + '...')
try:
# Load data
data = gpd.read_file(file)
# Re-project if not WGS84
if data.crs['init'] != 'epsg:4326':
print(file + 'CRS is not WGS84. Re-projecting Data...')
try:
data['geometry'] = data['geometry'].to_crs(epsg=4326)
print('SUCCESS: ' + file + ' was re-projected from ' + data.crs['init'] + ' to epsg:4326')
except:
print('EXCEPTION: ' + file + ' could not be re-projected ' + data.crs['init'] + ' to epsg:4326')
print('this error may occur for the following reasons:')
print('1) there is data that has no geometry that needs to be added')
print('2) geopandas to_crs() methods breaks for some recent versions of shapley')
print('RECOMMEND: checking data file or look for implement other method using gdal or ogr')
# Export data as GeoJSON
filename = 'geojson/' + os.path.splitext(file)[0] + '.geojson'
data.to_file(filename, driver = 'GeoJSON')
# Print success message
print('Success: ' + file + ' was converted to ' + os.path.splitext(file)[0] + '.geojson')
print(os.path.splitext(file)[0] + '.geojson is now in folder geosjon.')
print('')
except:
# Throw exepction for files that geopandas cannot read
print('EXCEPTION: '+ file + ' is not a vector layer or geopandas readable filetype')
print(file + ' could not be converted.')
print('')
print('Done.')
```
%% Output
Trying to convert arcs_df_ss.gpkg...
Success: arcs_df_ss.gpkg was converted to arcs_df_ss.geojson
arcs_df_ss.geojson is now in folder geosjon.
Trying to convert DNodes_10Aug.geojson...
DNodes_10Aug.geojsonCRS is not WGS84. Re-projecting Data...
SUCCESS: DNodes_10Aug.geojson was re-projected from epsg:32620 to epsg:4326
Success: DNodes_10Aug.geojson was converted to DNodes_10Aug.geojson
DNodes_10Aug.geojson is now in folder geosjon.
Trying to convert DNodes_10Aug.gpkg...
Success: DNodes_10Aug.gpkg was converted to DNodes_10Aug.geojson
DNodes_10Aug.geojson is now in folder geosjon.
Trying to convert estatesSTX.gpkg...
Success: estatesSTX.gpkg was converted to estatesSTX.geojson
estatesSTX.geojson is now in folder geosjon.
Trying to convert geojson...
EXCEPTION: geojson is not a vector layer or geopandas readable filetype
geojson could not be converted.
Trying to convert GNodes_10Aug.gpkg...
Success: GNodes_10Aug.gpkg was converted to GNodes_10Aug.geojson
GNodes_10Aug.geojson is now in folder geosjon.
Trying to convert HNodes_10Aug.gpkg...
Success: HNodes_10Aug.gpkg was converted to HNodes_10Aug.geojson
HNodes_10Aug.geojson is now in folder geosjon.
Trying to convert ONodes_10Aug.gpkg...
Success: ONodes_10Aug.gpkg was converted to ONodes_10Aug.geojson
ONodes_10Aug.geojson is now in folder geosjon.
Trying to convert PNodes_10Aug.gpkg...
Success: PNodes_10Aug.gpkg was converted to PNodes_10Aug.geojson
PNodes_10Aug.geojson is now in folder geosjon.
Trying to convert SNodes_10Aug.gpkg...
Success: SNodes_10Aug.gpkg was converted to SNodes_10Aug.geojson
SNodes_10Aug.geojson is now in folder geosjon.
Trying to convert TNodes_10Aug.gpkg...
Success: TNodes_10Aug.gpkg was converted to TNodes_10Aug.geojson
TNodes_10Aug.geojson is now in folder geosjon.
Done.
%% Cell type:markdown id: tags:
### For Geopackages:
%% Cell type:markdown id: tags:
Running the next cell will make a new folder within the folder chosen containing one GeoJSON for every Geopackage file. (e.g. if you have three Geopackage files in the directory, there will be three converted geojson files) Note: Running this cell will also reproject your CRS to WGS 84 EPSG 4326.
%% Cell type:code id: tags:
``` python
%lsmagic
```
%% Output
Available line magics:
%alias %alias_magic %autoawait %autocall %automagic %autosave %bookmark %cd %clear %cls %colors %conda %config %connect_info %copy %ddir %debug %dhist %dirs %doctest_mode %echo %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %macro %magic %matplotlib %mkdir %more %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %pip %popd %pprint %precision %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %ren %rep %rerun %reset %reset_selective %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode
Available cell magics:
%%! %%HTML %%SVG %%bash %%capture %%cmd %%debug %%file %%html %%javascript %%js %%latex %%markdown %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefile
Automagic is ON, % prefix IS NOT needed for line magics.
%% Cell type:code id: tags:
``` python
%%cmd
mkdir geojson
for filename in ./*.gpkg do ogr2ogr -f "GeoJSON" "./geojson/$filename.geojson" "$filename";done
```
%% Output
Microsoft Windows [Version 10.0.18362.720]
(c) 2019 Microsoft Corporation. All rights reserved.
(pyomo_test) C:\Users\Dan\Anaconda_dan_packages\cid\usvi_gis\usvi-optimzation\Data\jeff_good_data_geojson>mkdir geojson
(pyomo_test) C:\Users\Dan\Anaconda_dan_packages\cid\usvi_gis\usvi-optimzation\Data\jeff_good_data_geojson>for filename in ./*.gpkg do ogr2ogr -f "GeoJSON" "./geojson/$filename.geojson" "$filename";done
(pyomo_test) C:\Users\Dan\Anaconda_dan_packages\cid\usvi_gis\usvi-optimzation\Data\jeff_good_data_geojson>
(pyomo_test) C:\Users\Dan\Anaconda_dan_packages\cid\usvi_gis\usvi-optimzation\Data\jeff_good_data_geojson>
(pyomo_test) C:\Users\Dan\Anaconda_dan_packages\cid\usvi_gis\usvi-optimzation\Data\jeff_good_data_geojson>
%% Cell type:markdown id: tags:
### For KML:
import os
import geopandas as gpd
import re
%% Cell type:markdown id: tags:
def convert2geojson():
Running the next cell will make a new folder within the folder chosen containing one GeoJSON for every KML file. (e.g. if you have three Geopackage files in the directory, there will be three converted geojson files) Note: Running this cell will also reproject your CRS to WGS 84 EPSG 4326. You may recieve a warning such as "The output driver does not natively support DateTime".
# Ask user for filepath of folder containing files to convert
def enterfilepath():
while True:
filepath=(input("Enter filepath of the folder containing your files: "))
if os.path.exists(filepath):
break
print("Not a valid filepath.")
os.chdir(filepath)
print("Converting all files in" , os.getcwd(), 'to geojson.')
enterfilepath()
# Make a geojson folder if it doesn't exist
current_directory = os.getcwd()
geojson_directory = current_directory + '/geojson'
if not os.path.exists(geojson_directory):
os.mkdir('geojson')
print('Will place all converted files in new "geojson" folder.' + '\n')
else:
print('Will place all converted files in existing "geojson" folder.' + '\n')
# Iterate over files and attempt to convert all to geojson
for file in os.listdir(current_directory):
# Skip folders and listed filetypes
if os.path.isdir(file):
continue
if not file.lower().endswith(('txt','jpg','jpeg','geojson','ds_store','pdf',\
'xlsx','doc','docx','git','qpj','prj','dbf','shx','cpg')):
print('Converting ' + file + '...')
%% Cell type:code id: tags:
try:
# Load data
file = str(current_directory) + '/' + str(file)
data = gpd.read_file(file)
# Alert user if CRS is changing with conversion
if data.crs['init'] != 'epsg:4326':
match = re.search('epsg:.[^\']*', str(data.crs)) #use regex to split each dms string into integer components to input in the dms_to_decimal function
crs = str(match.group())
print('Original CRS was ' + crs + '...will be converted to epsg:4326')
# Create new filepath with geojson folder and extension
head, tail = os.path.split(file)
filename = head + '/geojson/'+ tail
filename_ext = os.path.splitext(filename)[0] + '.geojson'
data.to_file(filename_ext, driver = 'GeoJSON')
#Print success message
print('Success: ' + file + ' was converted to GeoJSON' + '\n')
``` python
!for filename in ./*.kml; do mkdir -p geojson; ogr2ogr -f "GeoJSON" -t_srs crs:84 "./geojson/$filename.geojson" "$filename";done
```
except:
# Alert user if file conversion failed
print('EXCEPTION: '+ file + ' is not a geopandas readable filetype')
print(file + ' could not be converted.' + '\n')
%% Cell type:code id: tags:
print('Done.')
``` python
convert2geojson()
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment