Display Google Maps API with Rails and pin display

Introduction

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

environment

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.

spaces_controller.rb


  def search
    @spaces = Space.all
  end

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

space.rb


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

schema.rb


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"
end

Script to display MAP

javascript


  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
    if(!navigator.geolocation){
      infoWindow.setPosition(map.getCenter());
      infoWindow.setContent('It does not support Geolocation.');
      infoWindow.open(map);
    }

    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.setPosition(map.getCenter());
      infoWindow.setContent('Error:Geolocation is invalid.');
      infoWindow.open(map);
    });
    //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
      });
      markerEvent(i);
    }
    //Multiple marker hover event
    function markerEvent(i) {
      marker[i].addListener('mouseover', function() {
        var target = $('#' + (i + 1));
        $(".highlight").removeClass("highlight");
        target.addClass("highlight");
        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
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
Beginners of Google Maps API and Twitter API made "tweet map"
Issue reverse geocoding in Japanese with Python Google Maps API
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
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)
How to use Service Account OAuth and API with Google API Client for python
Graph the power map of dogs and cats with Google Chart API and settle
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
Google App Engine Datastore and Search API integration
Format and display XML acquired by OpenWeatherMap API.
[For beginners] How to display maps and search boxes using the GoogleMap Javascript API
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]
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