[Java] [Rails] How to display multiple markers on Google Map and display a balloon when clicked

1 minute read

Target

ezgif.com-video-to-gif.gif

Development environment

・Ruby: 2.5.7 Rails: 5.2.4 ・Vagrant: 2.2.7 ・VirtualBox: 6.1 ・OS: macOS Catalina

Premise

Implemented below.

Slim introductionImplementation of login functionGoogle Map DisplayCalculate latitude and longitude with Gocoding API

Implementation

1. Edit controller

users_controller.rb


def index
  @users = User.all
  gon.users = User.all
end

2. Edit the view

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 = []; // Since we want to display multiple markers, array them
  let infoWindow = []; // I want to display multiple balloons, so array
  let markerData = gon.users; // Assign the instance variable defined in 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 }, // centered on Tokyo Tower
      zoom: 12,
    });

    // Display multiple markers and callouts by repeating 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({
        // the content of the balloon
        content: markerData[i]['address']
      });

      // Add a click event to the marker
      markerEvent(i);
    }
  }

  // Show the balloon when you click the marker
  function markerEvent(i) {
    marker[i].addListener('click', function () {
      infoWindow[i].open(map, marker[i]);
    });
  }

If you want to link the content of the balloon, describe as follows.

``


// Variable each user's ID
let id = markerData[i]['id']

infoWindow[i] = new google.maps.InfoWindow({
  // Create link with <a> tag
  content: `<a href='/users/${ id }'>${ markerData[i]['address'] }</a>`
});

Note

If you do not disable turbolinks, the map will not switch, so be sure to disable it.

How to disable turbolinks