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

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

The following has been implemented.

Slim introduction -Login function implementationGoogle Map display -Calculate latitude and longitude with Gocoding API

Implementation

1. Edit the 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 = []; //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>`
});

Caution

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

How to disable turbolinks

Recommended Posts

[Rails] How to display multiple markers on Google Map and display a balloon when clicked
[Rails 6 / Google Map API] Post an address and set multiple markers on the map
Display the address entered using Rails gem'geocoder' on Google Map
When I tried to build a Rails environment on WSL2 (Ubuntu 20.04LTS), I stumbled and fell.
How to display formulas in latex when using sympy (> = 1.4) in Google Colaboratory
How to display PDF resolution and detailed information on Linux (pdfinfo)
Try to display google map and geospatial information authority map with python
[Ruby on Rails] Display and pinning of GoolgeMAP using Google API
How to write a string when there are multiple lines in python
How to use Google Assistant on Windows 10
How to test on a Django-authenticated page
How to make a Pelican site map
How to run a Django application on a Docker container (development and production environment)
How to make multiple kernels selectable on Jupyter
Display Google Maps API with Rails and pin display
How to remember when you forget a word
How to live a decent life on 2017 Windows
How to display videos inline in Google Colab
How to build a beautiful Python environment on a new Mac and install Jupter Notebook
How to create a Python 3.6.0 environment by putting pyenv on Amazon Linux and Ubuntu
Visualize and understand Japan's regional mesh on a map
How to deploy a Django application on Alibaba Cloud
How to install Linux on a 32bit UEFI PC
How to install Git GUI and Gitk on CentOS
A memorandum on how to use keras.preprocessing.image in Keras
Visualize B League goals and goals on a heat map
How to display multiple images of galaxies in tiles
How to build a Django (python) environment on docker
How to display DataFrame as a table in Markdown
[Python] How to create Correlation Matrix and Heat Map
How to use Django on Google App Engine / Python
How to run Django on IIS on a Windows server
How to build a Python environment on amazon linux 2
Good and bad code to compare on a minimap
How to set up WSL2 on Windows 10 and create a study environment for Linux commands
How to get the current weather data and display it on the GUI while updating it automatically
How to connect to Cloud SQL PostgreSQL on Google Cloud Platform from a local environment with Java
How to easily draw the structure of a neural network on Google Colaboratory using "convnet-drawer"
How to display a specified line of a file or command result on Linux (sed, awk)