a-thousand-channels / ORTE-backend

Application for creating and managing places (or "Orte") on a map
GNU General Public License v3.0
2 stars 3 forks source link

KML/GeoJSON Importer #284

Open ut opened 1 year ago

ut commented 1 year ago

Approach


require 'nokogiri'

module KMLImporter
  class Importer
    def self.import_kml(file_path)
      kml_data = File.read(file_path)
      doc = Nokogiri::XML(kml_data)

      # Process the KML data here and save it to your application's model
      # Example: Parse the KML data and save it to a Location model
      locations = []

      doc.css('Placemark').each do |placemark|
        name = placemark.css('name').text
        coordinates = placemark.css('coordinates').text.split(',').map(&:strip)
        lat, lon = coordinates[1], coordinates[0] # KML uses (lon, lat) order

        # Create or update Location records with parsed data
        location = Location.find_or_initialize_by(name: name)
        location.latitude = lat.to_f
        location.longitude = lon.to_f
        locations << location
      end

      # Save all parsed locations
      Location.transaction do
        locations.each(&:save)
      end
    end
  end
end