Created
July 24, 2014 03:22
-
-
Save radcliff/ba27f27d7c3c320f8efa to your computer and use it in GitHub Desktop.
Ruby method to convert geojson to topojson in Rails API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
project repo: https://github.com/radcliff/drought-monitor-api/tree/execjs