Skip to content

Instantly share code, notes, and snippets.

@katsuyoshi
Created June 14, 2024 23:20
Show Gist options
  • Save katsuyoshi/8244ff926550f5690c9758e1438c39ca to your computer and use it in GitHub Desktop.
Save katsuyoshi/8244ff926550f5690c9758e1438c39ca to your computer and use it in GitHub Desktop.
外部データ読み込みテスト
require 'sinatra'
require 'sinatra/reloader' if development?
require 'haml'
before do
response.headers['Access-Control-Allow-Origin'] = 'https://irboard.itosoft.com'
end
get '/' do
haml :index
end
get '/popup_content' do
content_type 'text/html'
send_file File.join(settings.public_folder, 'popup_content.html')
end
get '/json_popup_content' do
content_type :json
data = {
message: 'Hello, World!',
body: File.read(File.join(settings.public_folder, 'popup_content.html')),
status: 'success'
}
data.to_json
end
!!!
/ views/index.haml
%html
%head
%meta{:content => "text/html; charset=UTF-8", "http-equiv" => "Content-Type"}/
%meta{:charset => "utf-8"}/
%title Leaflet Map
%link{:href => "https://unpkg.com/[email protected]/dist/leaflet.css", :rel => "stylesheet"}/
:css
#map {
height: 600px;
width: 100%;
}
%body
%h1 Leaflet Map with Sinatra
#map
#result
%script{:src => "https://unpkg.com/[email protected]/dist/leaflet.js"}
:javascript
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var marker = L.marker([51.5, -0.09]).addTo(map);
// AJAXリクエストで外部HTMLを取得してポップアップに表示する
/*
fetch('/popup_content')
.then(response => response.text())
.then(data => {
marker.bindPopup(data).openPopup();
})
.catch(error => console.error('Error loading popup content:', error));
*/
//fetch('http://127.0.0.1:8080/json_popup_content')
fetch('/json_popup_content')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => {
marker.bindPopup(data.body).openPopup();
})
.catch(error => {
document.getElementById('result').innerHTML = '<p>An error occurred: ' + error.message + '</p>';
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment