#Shapefile to geoJSON & javascript variable
#This tool takes a shapefile and outputs a json file --
#-- and a js file with the json data stored in a single variable

import shapefile
import arcpy

#environments
arcpy.env.overwriteOutput = True

# parameters
shpfile = arcpy.GetParameterAsText(0) #shapefile to convert
jsonOutput = arcpy.GetParameterAsText(1) #.json output
jsVar = arcpy.GetParameterAsText(2) #variable for JavaScript file
jsOutput = arcpy.GetParameterAsText(3) #.js output

#If shapefile is not in WGS 1984, this will create a 2nd shapefile in WGS 1984
spatialRef = arcpy.Describe(shpfile).spatialReference

if spatialRef.name != "GCS_WGS_1984":
    outCS = arcpy.SpatialReference("WGS 1984")
    shpfile2 = shpfile.replace(".shp","_WGS1984.shp")
    arcpy.Project_management(shpfile, shpfile2, outCS)
    shpfile = shpfile2

# read the shapefile
reader = shapefile.Reader(shpfile)
fields = reader.fields[1:]
field_names = [field[0] for field in fields]
buffer = []
for sr in reader.shapeRecords():
    atr = dict(zip(field_names, sr.record))
    geom = sr.shape.__geo_interface__
    buffer.append(dict(type="Feature", geometry=geom, properties=atr))

# write the GeoJSON file
from json import dumps

geojson = open(jsonOutput, "w")
geojson.write(dumps({"type": "FeatureCollection", "features": buffer}, indent=2) + "\n")
geojson.close()

# store geoJSON data in JS file
myFile = open(jsonOutput)
json = myFile.read()
js = "var " + jsVar + " = [" + json + "];"
myFile.close()

myFile = open(jsOutput, 'w')
myFile.write(js)
myFile.close()