2

I'm asking if someone has already done the following description. I don't even know if it's possible.

I would like to use a KML file to generate a polygon recorded on my PostgreSQL database (with PostGIS).

brcebn
  • 1,571
  • 1
  • 23
  • 46
  • Are you asking how to import a KML file to Postgres or how to generate KML from Postgres/GIS? – John Powell May 03 '14 at 07:57
  • It was about importing a KML to Postgres. I've found this this GEM that seems to match with my research : [GeoRuby](https://github.com/nofxx/georuby) I'm currently working on it. I will let you know if I have some conclusive results. – brcebn May 03 '14 at 10:21
  • If that doesn't work, try ogr2ogr – John Powell May 03 '14 at 11:08
  • Thank you. I did it. I've added a link that helped me a lot coming from [iNaturalist](https://github.com/inaturalist/inaturalist/blob/master/app/controllers/places_controller.rb) – brcebn May 03 '14 at 17:27
  • Great. Once is postgis, there are a whole bunch of formats you can select as, such as geojson amd kml. – John Powell May 03 '14 at 18:13

1 Answers1

3

I finally did it

geometry = GeoRuby::SimpleFeatures::MultiPolygon.new
doc = kml =~ /\<kml / ? Nokogiri::XML(kml) : Nokogiri::XML.fragment(kml)
doc.search('Polygon').each_with_index do |hpoly,i|
  poly = GeoRuby::SimpleFeatures::Geometry.from_kml(hpoly.to_s)
end
geometry.empty? ? nil : geometry

The kml file is directly the uploaded file where I applied the open method.

I've found a lot of inspiration coming from this document of inaturalist

By the way. I found another problem: store it. I didn't find any way to convert (and project) points coming from GeoRuby to RGeo. That's why I finally parse it by myself:

@doc = Nokogiri::XML(kml)
@doc.css('Placemark').each do |placemark| 
  coordinates = placemark.at_css('coordinates')

  if coordinates
    coordinates.text.split(' ').each do |coordinate|
      (lon,lat,elevation) = coordinate.split(',')
      points << Geo::StorageFactory.point(lon.to_f, lat.to_f)
      print "#{lat},#{lon}"
        puts "\n"
      end

  end
end

@area = Geo::StorageFactory.polygon(Geo::StorageFactory.line_string(points)).projection
brcebn
  • 1,571
  • 1
  • 23
  • 46