Ag Analytics-CropDataLayers-Demo

Crop Land Data Layers, also known as CDLs, are published by USDA and provide estimates of historical crops cover.

In [ ]:
import requests
import json
import time
from pandas.io.json import json_normalize
import requests, zipfile, io
import geopandas as gpd
%matplotlib inline
import pandas as pd
%autosave 0

API Details

Request URL:https://ag-analytics.azure-api.net/CroplandDataLayers/get[?year][&inputShape][&env:outSR]

Request parameters

year Year of desired result.

inputShape (ESRI Polygon shape): The shape information for field in esriGeometryPolygon format. Standard open source JavaScript front-end libraries (e.g., Leaflet) can be used to structure the shape

env:outSR (optional) Output Spatial Reference. Return features in the specified spatial reference by supplying specific wkid (eg. 4326).

In order to get Ocp-Apim-Subscription-Key, please click on this link https://ag-analytics.org/developer/Session/SignInFromPayment

Request Parameters

In [ ]:
year=2016
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}}}]}
env=4326
f="json"
headers={'Ocp-Apim-Subscription-Key': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'}

API Function

In [ ]:
def get_crop_data_layers(year,inputShape,env,headers,f):
    try:
        url = "https://ag-analytics.azure-api.net/CroplandDataLayers/get?year={}&inputShape={}&env:outSR={}&f={}".format(year,inputShape,env,f)
     
        response = (requests.get(url,headers=headers).text)
        print(response)
       
        response_json = json.loads(response)
        time.sleep(0.5)
        return response_json
    
    except Exception as e:
        raise e

Calling API Function

In [ ]:
crop_layer=get_crop_data_layers(year,inputShape,env,headers,f)

Displaying Map

In [ ]:
#saving the respons eof api in geojson format

file=open('./jsonfiles/cropdatalayers.json','w')
file.write(json.dumps(crop_layer['results'][0]["value"]))
file.close()


# Helper functions for creating 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
    
In [ ]:
requestbody={'upload':open('./jsonfiles/cropdatalayers.json','rb')}
# Function call to convert json to geojson
cropdata_geojson=post_converttogeojson(requestbody)

requestbody={'json':cropdata_geojson,'skipFailures':"on"}
#function call to creatr shapefile from geojson 
post_converttoshapefile(requestbody)

# Reading a shapefile and displaying the map
gdf = gpd.read_file('./shapefiles/OGRGeoJSON.shp')


grid_code_mappings=pd.read_csv("cropnames_gridcodes_mappings.csv")

grid_code_mappings.set_index('Code',inplace=True)


gdf['CropName']=gdf['GRIDCODE'].map(grid_code_mappings.to_dict()['CropName'])

gdf.plot(column='CropName', cmap=None,figsize=(10, 10),legend=True)
gdf.head()