[RAILS] Explains JavaScript of Google Maps Geocoding API

Introduction

The other day, I implemented the map display function by incorporating the Google Maps API into the portfolio created with Rails. The understanding of the JavaScript code I wrote there was ambiguous, so I summarized it in an article.

This article focuses on the JavaScript code, not how to deploy the Google Maps API. I will not explain how to introduce the API in this article, so if you want to know, please see the following article. [[Rails 6 / Google Map API] For beginners! Easy introduction of Google Map API with Ruby on Rails](https://qiita.com/nagaseToya/items/e49977efb686ed05eadb#%E6%A4%9C%E7%B4%A2%E3%83%95%E3%82 % A9% E3% 83% BC% E3% 83% A0% E3% 81% 8B% E3% 82% 89% E4% BD% 8F% E6% 89% 80% E3% 82% 92% E7% 89% B9 % E5% AE% 9A% E3% 81% 97% E3% 83% 94% E3% 83% B3% E3% 82% 92% E5% 88% BA% E3% 81% 99)

"I managed to copy and paste an article on the net, but I can't understand the code." If you have any questions, please read it.

Prerequisite knowledge

Converting an address or place name into geographic coordinates such as latitude and longitude is called "geocoding". The Geocoding API of Google Maps is an API for geocoding.

Complete image

Created an app that allows people who want to travel the other day to recruit tour guides I implemented it so that the place I entered as the place I want to travel is displayed on the map.

In this article, I will explain under the image of this app.

スクリーンショット 2020-10-24 13.16.03.jpg

Source code

The source code of the view is as follows The id of ʻaddress is given to the place where you want to travel, and the id of map` is given to the place where you want to display the map.

show.html.haml


    .Post_main__Box
      .Post_show_title
        = @post.title
      .Post_table.Text
        %table
          %tr
            %th Where you want to travel
            -#Show address here
            %td#address
              = @post.region
          %tr
            %th desired date and time
            %td
              = @post.datetime
          %tr
            %th desired price
            %td
              = @post.charge
          %tr
            %th payment method
            %td
              = @post.payment
      .Post_head
        = "-Request details-"
      .Post_content
        = simple_format(@post.content)
      .Post_head
        = "-map-"
      -#Show map here
      .Post_map#map

In addition, the JavaScript source code is below.

map.js


//Set to process after HTML has finished loading
document.addEventListener('DOMContentLoaded', () => {
  const inputAddress = document.getElementById('address').textContent;    //①
  const target = document.getElementById('map');    //②
  geocoder = new google.maps.Geocoder();   // ③

  geocoder.geocode( { address: inputAddress}, (results, status) => {  // ④
    if (status == 'OK') {  // ⑤
      const map = new google.maps.Map(target, {  // ⑥
        center: results[0].geometry.location,   // ⑦
        zoom: 13  // ⑧
      });
      new google.maps.Marker({  // ⑨
          map: map,  // ⑩
          position: results[0].geometry.location  // ⑪
      });
    } else {   // ⑫
      document.getElementById('map').style.height = '20px'   // ⑬
      document.getElementById('map').innerHTML = 'I can not find the corresponding place.'   // ⑭
    }
  });   
})

Commentary

I will explain the above JavaScript code.

** ▼ About ① and ② **

const inputAddress = document.getElementById('address').textContent;   //①
const target = document.getElementById('map');   //②

In ①, the character string (address in this case) in the element with the id of ʻaddress is acquired and assigned to ʻinputAddress. In (2), the object of the div element of the area to display the map with the id of map is assigned to target.

** About ③ **

geocoder = new google.maps.Geocoder();

In this description, the object (instance) of google.maps.Geocoder required to communicate with the Google server is generated. The API is accessed through this object.

** About ④ **

geocoder.geocode( { address: inputAddress}, (results, status) => {   

Here, first, by using the geocode () method on the geocoder object created in ①, I am sending a request for geocoding.

When sending a request, you must pass a value of either ʻaddress, location, or placeId in the API specification. In the above code, the value of ʻinputAddress defined in ① is put in the property of ʻaddress` and passed as a parameter.

When the request is completed, the result (results) and status (status) will be returned. To get them and process them, write a callback function with results and status as arguments.

** About ⑤ **

if (status == 'OK')

The status returned as a result of the request returns ʻOK if geocoding was successful. If unsuccessful, a code such as ʻERROR is returned. The above description represents the case of successful geocoding.

** ▼ About ⑥ ~ ⑧ **

const map = new google.maps.Map(target, {  // ⑥
  center: results[0].geometry.location,   // ⑦
  zoom: 13  // ⑧
});

In ⑥, a map is generated with new google.maps.Map and assigned to map. In the constructor of the google.maps.Map class, the first argument is the div element that displays the map. Here, the target defined in ② is specified. Also, in the second argument, specify the object that sets the coordinates and zoom level of the map.

In ⑦, get the longitude and latitude information from the request results with results [0] .geometry.location. It is described so that the geographic coordinates are displayed in the center of the map. By the way, since the result of the request is returned as an array, it is described as results [0].

Furthermore, the zoom level is specified by ⑧. The larger this number, the larger the map will be displayed.

** ▼ About ⑨ ~ ⑪ **

new google.maps.Marker({  // ⑨
    map: map,  // ⑩
    position: results[0].geometry.location  // ⑪
});

Here, the description is to display a marker (red pin) on the map. A marker object is created in ⑨, and map and position are specified as options in the arguments. In ⑩, the map to display the marker is specified, and here, map defined in ⑥ is specified. Also, in ⑪, the position to display the marker is specified by the geographic coordinates obtained from the result of the request.

By the way, if you add ʻanimation: google.maps.Animation.DROP` as an option, You can add an animation that makes the marker fall from the top.

** ▼ About ⑫ ~ ⑭ **

} else {   // ⑫
  document.getElementById('map').style.height = '20px'   // ⑬
  document.getElementById('map').innerHTML = 'I can not find the corresponding place.'   // ⑭
}

This section describes what to do if geocoding is unsuccessful. The height of the div element that displays the map is changed in ⑬, and the HTML content is rewritten to characters in ⑭. If you write it like this, it will be displayed as follows. スクリーンショット 2020-10-24 13.16.20.jpg

Referenced articles

In posting this article, I referred to the following articles. The following articles are written in more detail, so if you want to know more, please have a look. Geocoding Service  |  Maps JavaScript API  |  Google Developers How to use Google Maps API / Web Design Leaves Geocoding-How to use Mappy Google Maps API JavaScript- Introduction to Google Maps JavaScript API

Recommended Posts

Explains JavaScript of Google Maps Geocoding API
About the camera change event of Google Maps Android API
Beginners of Google Maps API and Twitter API made "tweet map"
Issue reverse geocoding in Japanese with Python Google Maps API
[Map display] Display a map from the address registered by the user using the Google Maps JavaScript API and Geocoding API!
Display Google Maps API with Rails and pin display
Create a tweet heatmap with the Google Maps API
Play music by hitting the unofficial API of Google Play Music
How to hide your Google Maps API key from HTML
Speech recognition of wav files with Google Cloud Speech API Beta
The story of creating a database using the Google Analytics API