Search code examples
postgresqlkmlpostgisrails-geocoderrgeo

Use KML to generate geometry


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).


Solution

  • 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