Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
galaxyproject
GitHub Repository: galaxyproject/training-material
Path: blob/main/bin/geocode.rb
1677 views
1
#!/usr/bin/env ruby
2
require 'yaml'
3
require 'net/http'
4
require 'json'
5
require 'uri'
6
require 'date'
7
8
def request(url)
9
uri = URI.parse(url)
10
request = Net::HTTP::Get.new(uri)
11
request['Accept'] = 'application/json'
12
request['User-Agent'] = 'GTN-geocode/1.0 (+https://github.com/galaxyproject/training-material)'
13
req_options = {
14
use_ssl: uri.scheme == 'https',
15
}
16
Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
17
http.request(request)
18
end
19
end
20
21
# loop across events
22
events = Dir.glob('events/*.md')
23
events.each do |event|
24
# Load as yaml
25
begin
26
event_data = YAML.load_file(event, permitted_classes: [Date])
27
rescue StandardError
28
event_data = YAML.load_file(event)
29
end
30
31
# Check if it is external, no need to show a map then
32
if event_data.key?('external') or event_data['layout'] == 'event-external'
33
STDERR.puts "Skipping external event: #{event}"
34
next
35
end
36
37
if event_data['layout'] != 'event'
38
STDERR.puts "Skipping non-event: #{event}"
39
next
40
end
41
42
# Check if it is already geocoded
43
if !event_data.key?('location')
44
STDERR.puts "Skipping geocoded event: #{event}"
45
next
46
end
47
48
if !event_data['location'].key?('geo')
49
# Geocode
50
loc = {
51
'street' => event_data['location'].fetch('address', nil),
52
'city' => event_data['location'].fetch('city', nil),
53
'country' => event_data['location'].fetch('country', nil),
54
'postcode' => event_data['location'].fetch('postcode', nil),
55
}
56
57
if event_data['location'].fetch('name', "").downcase == "online"
58
STDERR.puts "Skipping online event: #{event}"
59
next
60
end
61
62
if loc.values.compact.empty?
63
STDERR.puts "Skipping location-less event: #{event}"
64
next
65
end
66
67
# Nominatim
68
#
69
# https://nominatim.openstreetmap.org/search.php?street=Dr+Molewaterplein+40&city=Rotterdam&state=Zuid+Holland&country=the+Netherlands&postalcode=3015GD&dedupe=0&limit=1&format=jsonv2
70
kv = loc.map { |k, v| "#{k}=#{URI.encode_www_form_component(v)}" }.join('&')
71
url = "https://nominatim.openstreetmap.org/search.php?#{kv}&format=jsonv2"
72
data = JSON.parse(request(url).body)
73
74
# Open the file, replace ^location:$ with the geo text appended
75
if data.length.positive?
76
event_data['location']['geo'] = {
77
'lat' => data[0]['lat'],
78
'lon' => data[0]['lon'],
79
}
80
contents = File.read(event)
81
contents = contents.gsub(/^location:$/,
82
"location:\n geo:\n lat: #{data[0]['lat']}\n lon: #{data[0]['lon']}")
83
File.open(event, 'w') { |file| file.puts contents }
84
end
85
end
86
end
87
88