Skip to content

Instantly share code, notes, and snippets.

@radcliff
Created July 24, 2014 03:22
Show Gist options
  • Select an option

  • Save radcliff/ba27f27d7c3c320f8efa to your computer and use it in GitHub Desktop.

Select an option

Save radcliff/ba27f27d7c3c320f8efa to your computer and use it in GitHub Desktop.
Ruby method to convert geojson to topojson in Rails API
class DroughtshapesController < ApplicationController
include ApplicationHelper
def index
if params[:s]
state_name = params[:s].split.map {|i| i.capitalize}.join(" ")
state = State.find_by(name: state_name)
if state
shapes = state.drought_shapes
geojson_shapes = to_geojson(shapes)
if params[:geo] == "true"
render json: geojson_shapes # responds to requests with geojson
else
render json: convert_to_topojson(geojson_shapes) # responds to requests with topojson
end
else
render json: "not found - check query string and try again"
end
end
end
end
module TopojsonHelper
# given a geojson "feature collection", return a topojson object
def convert_to_topojson(geojson)
collection = geojson.to_json #convert a ruby hash to JSON object literal, ex. => becomes :
source = open('./lib/assets/topojson.js').read # load javascript library to memory
context = ExecJS.compile(source) # create ExecJS "context"
# string interpolate feature collection and pass it to topojson.topology
# evaluate within context of topojson library, and returns ruby object
topojson = context.eval("topojson.topology({collection: #{collection}})").to_json
return topojson
end
end
@radcliff
Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment