[RUBY] [Rails 6] Introducing Google Maps to your portfolio

Introduction

I would like to introduce Google Map, which I often see on Web services when creating a portfolio! !! I thought that I implemented it, so I will write an article for memorandum and review this time. As for the contents, when you move to the display page, whether or not you have acquired your current location is displayed, and if you allow it, The current location can be displayed, and by entering the location you want to search in the search form, that location can also be displayed.

The article I referred to is [Rails6 / Google Map API] for beginners! Easy introduction of Google Map API with Ruby on Rails is! I'm really thankful to you.

environment

Ruby on Rails '6.0.0' Ruby '2.6.5'

Premise

--Already obtained an API key on Google Cloud Platform.

Edit view file

Once you got the API key, you're almost done editing the view file. .. I wrote the following in html.erb that I want to display.

ruby:app/views/layouts/_map.html.erb


<div class="search-form">
  <input id="address" class="search-name" type="textbox" placeholder="You can search for nearby government offices from your current location">
  <input type="button" class="btn btn-outline-success" value="Search for" onclick="codeAddress()">
</div>

<div id='map'></div>

<style>
#map {
  height: 50vh;
  width: 60vw;
  margin: 0 auto;
}
</style>

<script>
  let map
  let geocoder

  function initMap(){
    geocoder = new google.maps.Geocoder()
    if(!navigator.geolocation) {
      alert('Does not support Geolocation API');
      return false;
    }

    navigator.geolocation.getCurrentPosition(function(position) {
      latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

      map = new google.maps.Map(document.getElementById('map'), {
        center: latLng,
        zoom: 12,
      });

      marker = new google.maps.Marker({
        position:  latLng,
        map: map
      });
    }, function() {
        alert('Failed to get location information');
      });
  }

  function codeAddress(){
    let inputAddress = document.getElementById('address').value;

    geocoder.geocode( { 'address': inputAddress}, function(results, status) {
      if (status == 'OK') {
        map.setCenter(results[0].geometry.location);
        let marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
        });
      } else {
          alert('There were no applicable results:' + status);
      }
    });   
  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<%= ENV['GOOGLE_MAP_SECRET_KEY'] %>&callback=initMap" async defer></script>

Then, I will explain it in parts.

ruby:app/views/layouts/_map.html.erb


<div class="search-form">
  <input id="address" class="search-name" type="textbox" placeholder="You can search for nearby government offices from your current location">
  <input type="button" class="btn btn-outline-success" value="Search for" onclick="codeAddress()">
</div>

The search form is first implemented in this part of the upper row. Buttons etc. use bootstrap.

ruby:app/views/layouts/_map.html.erb


<style>
#map {
  height: 50vh;
  width: 60vw;
  margin: 0 auto;
}
</style>

In this part, the size and arrangement of the map are decided.

ruby:app/views/layouts/_map.html.erb


#↓ Acquisition process of current location
function initMap(){
    geocoder = new google.maps.Geocoder()
    if(!navigator.geolocation) {
      alert('Does not support Geolocation API');
      return false;
    }
#↑ If the user's device does not support Google Map, the map will not be displayed.
    navigator.geolocation.getCurrentPosition(function(position) {
      latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

      map = new google.maps.Map(document.getElementById('map'), {
        center: latLng,
        zoom: 12,
      });
#↑ If the location information can be obtained, the latitude and mild information of the current location are defined in latLng, and the process is being performed to display it on the map.
#「center:Display your current location in the center of the map with "latLng" and "zoom":"12" is the magnification of enlargement.

      marker = new google.maps.Marker({
        position:  latLng,
        map: map
      });
#↑ A marker is displayed at the current location.
    }, function() {
        alert('Failed to get location information');
      });
  }
#If the acquisition fails in some way, it will be displayed as alert.

The above is the initial display stage when the page is opened. The processing content is described in the comment out.

ruby:app/views/layouts/_map.html.erb


#Click the search button to start the process.
  function codeAddress(){
    let inputAddress = document.getElementById('address').value;
#↑ The position entered in the search form is being acquired.
    geocoder.geocode( { 'address': inputAddress}, function(results, status) {
      if (status == 'OK') {
        map.setCenter(results[0].geometry.location);
        let marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
        });
#↑ When the search result is hit, the latitude and longitude of the search result are displayed on the map and a marker is set.
      } else {
          alert('There were no applicable results:' + status);
      }
    });   
  }
#↑ If the search result is not applicable, the above is displayed.

The above is the process for displaying the search results.

ruby:app/views/layouts/_map.html.erb


<script src="https://maps.googleapis.com/maps/api/js?key=<%= ENV['GOOGLE_MAP_SECRET_KEY'] %>&callback=initMap" async defer></script>

The last line is getting the API key. Handle the acquired key with environment variables.

in conclusion

This completes the implementation. When you move to the display page, you will be asked if you want to get location information, so if you allow it, your current location will be displayed. When you search this time, the marker will stick to two points, your location information and the corresponding place in the search result. From here, if you can display the distance and time to the search results, I think that the application will be easier to use, so I will study it. If there are any differences, please point them out.

Recommended Posts

[Rails 6] Introducing Google Maps to your portfolio
Introducing CircleCI to Rails
Introducing Bootstrap to Rails 5
Introducing Bootstrap to Rails !!
Introducing full calendar to Rails application
Introducing React to Rails with react-rails
Portfolio creation Ruby on Rails
Create portfolio with rails + postgres sql
portfolio
[Rails 6] Introducing Google Maps to your portfolio
[Portfolio] Bookmark management app [Ruby on Rails]
Beginners create portfolio in Ruby on Rails
Introduce two-factor authentication to your Rails application
The process of introducing Vuetify to Rails
[Rails] Introducing jquery
Introducing New Relic to Rails apps on Heroku
[Rails] Introducing devise
Incorporate Docker into your Ruby on Rails portfolio!
[Rails] Introducing pay.jp (from view customization to registration)
How to implement guest login in 5 minutes in rails portfolio
How to write Rails
[Rails] Introducing Active Hash
Introduce Vue.js to Rails
How to uninstall Rails
Introducing Rails6 + Bootswatch / Honoka
How to deploy jQuery in your Rails app using Webpacker
A series of steps to create portfolio deliverables with Rails