The SURGGO Soils API provides soil type and average of the soil type attribute (e.g., NCCPI) by field for a shape entered.
import requests
import json
import time
from pandas.io.json import json_normalize
import pandas as pd
from collections import defaultdict
import math
import requests, zipfile, io
import geopandas as gpd
%matplotlib inline
Request URL: https://ag-analytics.azure-api.net/ssurgosoil/get[?inputShape][&inputFields]
Parameters:
inputShape (optional) ESRI Polygon shape.
The inputShape should have the Albers (“wkid”: 5070) spatial reference. The shape information for field is esriGeometryPolygon format. Standard open source JavaScript front-end libraries (e.g., Leaflet) can be used to structure the shape. See example request below, in which "spatialReference": {"wkid": 5070} is required
inputFields (optional) The metrics to return with the format “TableName_SoilTypeName”.
In order to get Ocp-Apim-Subscription-Key, please click on this link https://analytics.ag/Session/SignInToAPIPayment
inputShape={"geometryType":"esriGeometryPolygon","features":[{"geometry":{"rings":[[[-89.045774,43.730605],[-89.04577,43.730488],[-89.045722,43.729998],[-89.045789,43.729653],[-89.045661,43.72961],[-89.045635,43.729782],[-89.045644,43.730045],[-89.045653,43.730308],[-89.045651,43.730607],[-89.041228,43.730676],[-89.041171,43.728908],[-89.041111,43.727076],[-89.042892,43.727044],[-89.044665,43.727018],[-89.046178,43.726999],[-89.046237,43.730597],[-89.045774,43.730605]]],"spatialReference":{"wkid":4326}}}]}
inputFields="nccpi2all"
headers={'Ocp-Apim-Subscription-Key': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'}
def get_SSURGO_Soil_type(inputShape,inputFields,headers):
try:
url = "https://ag-analytics.azure-api.net/ssurgosoil/get?inputShape={}&inputFields={}".format(inputShape,inputFields)
response = (requests.get(url,headers=headers).text)
response_json = json.loads(response)
print(response_json)
time.sleep(0.5)
return response_json
except Exception as e:
raise e
ssurgo=get_SSURGO_Soil_type(inputShape,inputFields,headers)
totalAcres=0
mukeydict={}
for value in ssurgo['results'][2]['value']['features']:
totalAcres+=value['attributes']['SUM_intersect_Shape_Area1']*0.000247105 #sq meter to acres calc
df=defaultdict(list)
for value in ssurgo['results'][2]['value']['features']:
mukeydict[value['attributes']['intersect_MUKEY']]=value['attributes']['FIRST_valu1_MUNAME']
df['soil_Name'].append(value['attributes']['FIRST_valu1_MUNAME'])
partAcres=value['attributes']['SUM_intersect_Shape_Area1']*0.000247105
percentAcres=(partAcres/totalAcres)*100
df['Acres'].append(round(partAcres*100)/100)
df['Percent'].append(round(percentAcres*100)/100)
df['Avg nccpi'].append(value['attributes']['MIN_valu1_nccpi2all'])
ssurgodf=pd.DataFrame.from_dict(df)
ssurgodf
for params in ssurgo['results']:
if params['paramName']=='output2':
file=open('./jsonfiles/ssurgodata1.json','w')
file.write(json.dumps(params['value']))
file.close()
# functions to convert json to geojson and then to shapefiles
def post_converttogeojson(requestbody):
try:
url = "https://ogre.adc4gis.com/convert"
response = (requests.post(url,files=requestbody).text)
return response
except Exception as e:
raise e
def post_converttoshapefile(requestbody):
try:
url = "https://ogre.adc4gis.com/convertJson"
response = (requests.post(url,data=requestbody))
z = zipfile.ZipFile(io.BytesIO(response.content))
z.extractall("./shapefiles/")
time.sleep(0.5)
return response
except Exception as e:
raise e
requestbody={'upload':open('./jsonfiles/ssurgodata1.json','rb')}
#function call to convert json reponse to geojson
ssurgodata_geojson=post_converttogeojson(requestbody)
requestbody={'json':ssurgodata_geojson,'skipFailures':"on"}
#function call to create shapefiles
post_converttoshapefile(requestbody)
gdf = gpd.read_file('./shapefiles/OGRGeoJSON.shp')
gdf['soilName']=gdf['MUKEY'].map(mukeydict)
gdf.plot(column='soilName', cmap=None,figsize=(10, 10),legend=True)
gdf.head()