Display Google Maps API with Rails and pin display


I used the Google Maps API in my portfolio in the past, but I've forgotten the flow, so I'm reminded.


rails 5.2.3 ruby 2.6.3

What to do this time

-Obtain the longitude and latitude from the current location information and display the marker. -Change the acquired list information to json format and place it on the map as a marker. ・ Map display

Create a controller to display, this time the action name is search.


  def search
    @spaces = Space.all

Create a model, enter the address, and then get the latitude and longitude automatically.


class Space < ApplicationRecord
  geocoded_by :address
  after_validation :geocode, if: :address_changed?


create_table "spaces", force: :cascade do |t|
    t.string "address"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.float "latitude"
    t.float "longitude"

Script to display MAP


  function initMap() 
    //Where to display the map
    var target = document.getElementById('gmap');
    //Map display
    var map = new google.maps.Map(document.getElementById('gmap'), {
      center: {lat: 35.681167, lng: 139.767052},//Center point setting
      zoom: 8//Map magnification setting

    //Creating a location marker
    //If you cannot get your current location
      infoWindow.setContent('It does not support Geolocation.');

    navigator.geolocation.getCurrentPosition(function(position) {
      //Get longitude and latitude of your current location
      var pos = { lat: position.coords.latitude, lng: position.coords.longitude };
      var mark = new google.maps.Marker({
        //Dropdown animation settings
        animation: google.maps.Animation.DROP,
        position: pos,
        map: map,
        //Create an icon for the current location pin. This time the default design is used for multiple markers, so change it.
        icon: {
          fillColor: "rgb(48, 255, 176)",
          fillOpacity: 1.0,
          path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
          scale: 4,
          strokeColor: "green",
          strokeWeight: 1.0
    }, function() {
      infoWindow.setContent('Error:Geolocation is invalid.');
    //Multiple markers
    //List data in json format
    var spaces = #{raw @spaces.to_json};
    var marker = [];
    var info;
    for(var i = 0; i < spaces.length; ++i) {
      //Create markers by extracting longitude and latitude information one by one from the list
      spot = new google.maps.LatLng({lat: spaces[i].latitude, lng: spaces[i].longitude});
      marker[i] = new google.maps.Marker({
        position: spot,
        map: map,
      	animation: google.maps.Animation.DROP
    //Multiple marker hover event
    function markerEvent(i) {
      marker[i].addListener('mouseover', function() {
        var target = $('#' + (i + 1));
        var position = target.offset().top - 280;
        $('body,html').animate({scrollTop:position}, 400, 'swing');

script src="https://maps.googleapis.com/maps/api/js?key=#{ENV[""]}&callback=initMap" async defer

Note that this time the template engine is slim and it is written directly in it, so the data variable storage is different from usual. Using gem's geocoder makes it very easy to get the longitude and latitude from the name, but this time I'm using Google Geocoding because it's inaccurate and doesn't even display the street number.

Recommended Posts

Display Google Maps API with Rails and pin display
[Rails] google maps api How to post and display including map information
Book registration easily with Google Books API and Rails
Introducing Google Map API with rails
[Google Maps API] Map is not displayed and becomes blank [Rails]
[Ruby on Rails] Display and pinning of GoolgeMAP using Google API
[Rails] Google Maps API Description when latitude and longitude cannot be saved
[Rails] Displaying Google Maps using Google Maps API and searching routes between multiple points
Create a tweet heatmap with the Google Maps API
[Rails] How to calculate latitude and longitude with high accuracy using Geocoding API and display it on Google Map
Beginners of Google Maps API and Twitter API made "tweet map"
Issue reverse geocoding in Japanese with Python Google Maps API
[Rails] How to display Google Map
Google API access token and refresh token
Get conversions and revenue with Google Analytics API and report to Slack
Try to display google map and geospatial information authority map with python
[Map display] Display a map from the address registered by the user using the Google Maps JavaScript API and Geocoding API!
Calculate and display standard weight with python
Streaming speech recognition with Google Cloud Speech API
Explains JavaScript of Google Maps Geocoding API
Execute Google Translate and DeepL Translate with GUI
Use TPU and Keras with Google Colaboratory
Encrypt with Ruby (Rails) and decrypt with Python
Get holidays with the Google Calendar API
Edit Slide (PowerPoint for Google) with Python (Low-cost RPA case with Google API and Python)
[Rails 6 / Google Map API] Post an address and set multiple markers on the map
How to use Service Account OAuth and API with Google API Client for python
How to display Map using Google Map API (Android)
I tried "License OCR" with Google Vision API
Try running Google Chrome with Python and Selenium
Interactively display algebraic curves with Python and Jupyter
Automatic voice transcription with Google Cloud Speech API
Wrap and display Japanese sentences well with pyglet
I tried "Receipt OCR" with Google Vision API
Get Gmail subject and body with Python and Gmail API
Google App Engine Datastore and Search API integration
Format and display XML acquired by OpenWeatherMap API.
[Rails] How to display multiple markers on Google Map and display a balloon when clicked
Get data labels by linking with Google Cloud Vision API when previewing images with Rails
[For beginners] How to display maps and search boxes using the GoogleMap Javascript API
[GCP] [Python] Deploy API serverless with Google Cloud Functions!
Display serial number columns and variables with Bottle template
Display embedded images of mp3 and flac with mutagen
Manipulate S3 objects with Boto3 (high-level API and low-level API)
Crawling with Python and Twitter API 1-Simple search function
Get comments and subscribers with the YouTube Data API
Display and shoot webcam video with Python Kivy [GUI]
How to analyze with Google Colaboratory using Kaggle API
Speech transcription procedure using Python and Google Cloud Speech API
[Python] Get user information and article information with Qiita API
Upload to a shared drive with Google Drive API V3
YOLP: Extract latitude and longitude with Yahoo! Geocoder API.
Install tweepy with pip and use it for API 1.1