・ Ruby: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ OS: macOS Catalina
The following has been implemented.
・ Slim introduction -Login function implementation ・ Google Map display -Calculate latitude and longitude with Gocoding API
users_controller.rb
def index
@users = User.all
gon.users = User.all
end
slim:users/index.html.slim
#map style='height: 500px; width: 500px;'
- google_api = "https://maps.googleapis.com/maps/api/js?key=#{ ENV['GOOGLE_MAP_API'] }&callback=initMap".html_safe
script{ async src=google_api }
javascript:
let map;
let marker = []; //I want to display multiple markers, so I arrange them
let infoWindow = []; //I want to display multiple balloons, so I arrange them
let markerData = gon.users; //Assign the instance variable defined by the controller to the variable
function initMap() {
geocoder = new google.maps.Geocoder()
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 35.6585, lng: 139.7486 }, //The display is centered around Tokyo Tower
zoom: 12,
});
//Display multiple markers and balloons by iterative processing
for (var i = 0; i < markerData.length; i++) {
let id = markerData[i]['id']
//Calculate the latitude and longitude of each point
markerLatLng = new google.maps.LatLng({
lat: markerData[i]['latitude'],
lng: markerData[i]['longitude']
});
//Create markers for each point
marker[i] = new google.maps.Marker({
position: markerLatLng,
map: map
});
//Create a balloon for each point
infoWindow[i] = new google.maps.InfoWindow({
//Contents of the balloon
content: markerData[i]['address']
});
//Add click event to marker
markerEvent(i);
}
}
//Click the marker to display a balloon
function markerEvent(i) {
marker[i].addListener('click', function () {
infoWindow[i].open(map, marker[i]);
});
}
If you want to link the contents of the balloon, describe as follows.
python
//Variableize each user's ID
let id = markerData[i]['id']
infoWindow[i] = new google.maps.InfoWindow({
// <a>Create a link with a tag
content: `<a href='/users/${ id }'>${ markerData[i]['address'] }</a>`
});
If you do not disable turbolinks
, the map will not switch, so be sure to disable it.
Recommended Posts