[Ruby on Rails] Multiple pins, balloons, and links on Google map

Target

map複数.gif

Development environment

ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina

Premise

-[Ruby on Rails] Automatically enter the address from the zip code --Google API key issued (Geocoding API Maps JavaScript API) ――The explanation was easy to understand here. -Until you try to display Google Map on Rails 5 -[Ruby on Rails] Display and pinning of GoolgeMAP using Google API

We will proceed on the premise that one item has already been displayed.

Introduction of 1 gem

Add the following to the Gemfile.

Gemfile


gem "gon"

Terminal


$ bundle install
Supplement gon is a gem that can use variables in controller in Javascript.

2 Editing controller

Define gon.users.

app/controllers/users_controller.erb


class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
  end

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

3 Edit view

Make it available in Javascript by writing <% = include_gon%>.

erb:app/views/layouts/application.html.erb


<head>
...
  <%= include_gon %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
...
<head>

This time it is described on the following page.

erb:app/views/users/index.html.erb


<div id='map'></div>
<style>
#map{
    height: 500px;
    width: 530px;
}
</style>

<script>

let map
let geocoder
let marker = []; //I want to display multiple markers, so I arrange them
let infoWindow = []; //I want to display multiple balloons, so I arrange them
const users = gon.users; //Assign the instance variable defined by the controller to the variable


function initMap(){
    //Initialize geocoder
    geocoder = new google.maps.Geocoder()
    //Initial position setting of map
    map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -35.6809591, lng: 139.7673068},
    zoom: 14
    });
    //for is iterative
    //Define the variable i as 0
    //After that, the process of repeatedly adding users defined by gon is performed.
    for (let i = 0; i < users.length; i++) {
        //Get latitude and longitude of address with geocoder
        // users[i]Is getting the user of variable i
        geocoder.geocode( { 'address': users[i].prefecture_code + users[i].city + users[i].street }, function(results, status) {
            //If status is OK
        if (status == 'OK') {
        // map.Map moves with setCenter
            map.setCenter(results[0].geometry.location);
            marker[i] = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
            //Assign variable i to variable id
            let id = users[i]['id']
            //infoWindow is a speech bubble
            infoWindow[i] = new google.maps.InfoWindow({
            //Specify the contents with content
            //This time it is displayed with a link pasted on the characters
            content: `<a href='/users/${id}'>${users[i].email}</a>`
            });
            //When the marker is clicked
            marker[i].addListener("click", function(){
                //Show infoWindow
                infoWindow[i].open(map, marker[i]);
            });
        } else {
            alert('Geocode was not successful for the following reason: ' + status);
        }
        });
    }
}

function codeAddress(){
    //Get input
    let inputAddress = document.getElementById('address').value;
    //Move map after geocoding
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=<%= ENV['SECRET_KEY'] %>&callback=initMap" async defer></script>
Supplement [When things go wrong] When the address is registered but not pinned [Geocoding Service](https://developers.google.com/maps/documentation/javascript/geocoding) It is OK if you enable Geocoding API referring to this.

Recommended Posts