Skip to content

Instantly share code, notes, and snippets.

@smellman
Created August 8, 2023 10:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smellman/cb4baa4ad34b4167971652ab6ad7768e to your computer and use it in GitHub Desktop.
Save smellman/cb4baa4ad34b4167971652ab6ad7768e to your computer and use it in GitHub Desktop.
GeoJSON (FeatureCollection) to EPSG:3857
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'rgeo'
require 'rgeo/geo_json'
require 'rgeo/proj4'
require 'optparse'
OptionParser.new do |opts|
opts.banner = 'Usage: geojson_to_epsg3857.rb [options]'
opts.on('-f', '--file FILE', 'GeoJSON file to convert') do |file|
@file = file
end
opts.on('-h', '--help', 'Prints this help') do
puts opts
exit
end
end.parse!
if @file.nil?
puts 'Please specify a GeoJSON file to convert.'
exit
end
factory_4326 = RGeo::Geos.factory(coord_sys: "EPSG:4326", srid: 4326)
factory_3857 = RGeo::Geos.factory(coord_sys: "EPSG:3857", srid: 3857)
open(@file, 'r') do |f|
geojson = RGeo::GeoJSON.decode(f.read, json_parser: :json, geo_factory: factory_4326)
converted_features = geojson.map do |feature|
RGeo::GeoJSON::Feature.new(
feature.geometry.transform(factory_3857),
feature.feature_id,
feature.properties
)
end
new_geojson = RGeo::GeoJSON::FeatureCollection.new(converted_features)
puts RGeo::GeoJSON.encode(new_geojson)
end
@smellman
Copy link
Author

smellman commented Aug 8, 2023

same as ogr2ogr -f GeoJSON -s_srs EPSG:4326 -t_srs EPSG:3857 /vsistdout/ foobar.geojson

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