[Rails 6 / Google Map API] Post an address and set multiple markers on the map

Introduction

What to make

It is a map that searches for latitude and longitude from the posted address or place name like this and puts markers at each point. (You can also post your address like "1-1-2 Oshiage, Sumida-ku, Tokyo" (Skytree)) スクリーンショット 2020-08-28 1.54.39.png

Things to prepare

Prerequisite knowledge

This time, we will proceed assuming that the map can be displayed using the Google Map API. If you don't understand how to display a map using GoogleMapAPI, please read 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/e49977efb6 86ed05eadb "About map display")

function

Please prepare a simple posting function. I created a maps table with an address column for posting addresses and place names. スクリーンショット 2020-08-29 16.41.46.png It is like this!

flow

  1. Add latitude and longitude columns to the maps table to store latitude and longitude.
  2. Use Geocoder to get the latitude and longitude from the entered address or place name and save each in the latitude and longitude columns.
  3. Place a marker at the posted latitude / longitude point.

Implementation

We will implement it according to the above flow!

1. Add column

$ rails g migration AddCoordinateToMaps latitude:float longitude:float

Create a migration file to add columns with the above command.

$ rails db:migrate

Don't forget to migrate!

2. Get latitude / longitude using Geocoder

Geocoding ――Q. What is Geocoding in the first place? ?? --A. Obtaining coordinates (latitude / longitude) from addresses and place names, or obtaining addresses and place names from coordinates. You can also get an address or place name from an IP address.

By the way, the following article has written in detail about Geocoding, so if you want to know more, please have a look. Rails Geocoder and Play

Install the required gems

gem 'geocoder'

Write the above code in the gem file.

$ bundle install

Let's do bundle install firmly ~! Now you can use geocoder in rails.

Geocoding for the model

map.rb


class Map < ApplicationRecord
    geocoded_by :address
    after_validation :geocode
end

In the : address part, write the column you want to geocode. If you describe these two lines for a model with ʻaddress, latitude, and longitude, the latitude and longitude will be obtained from the address and place name entered in ʻaddress and saved in each column. Will do it.

And if you display latitude and longitude on the list screen, the latitude and longitude will be displayed as shown below.

スクリーンショット 2020-08-29 18.15.22.png

However, if you post the address as it is, such as "1-1-2 Oshiage, Sumida-ku, Tokyo", you will not be able to obtain the latitude and longitude.

Create config file for geocoder

Create a config file with the following command.

$ rails g geocoder:config

A config file called config / initializers / geocoder.rb will be generated, so describe the API information of googlemap in that file.

ruby:config.initializers.geocoder.rb


Geocoder.configure(
  # Geocoding options
  timeout: 5,                 # geocoding service timeout (secs)
  lookup: :google,         # name of geocoding service (symbol)
  api_key: 'YOUR_API_KEY',               # API key for geocoding service
  units: :km,                 # :km for kilometers or :mi for miles
)

Uncomment the four items timeout, lookup, ʻapi_key, and ʻunits in the generated geocoder.rb, and fill in the required items as shown in the above code.

By doing this, geocoder will be able to obtain even highly detailed addresses.

3. Display a marker at the posted position

index.html.erb




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

<script>
  let map

    function initMap(){
      geocoder = new google.maps.Geocoder()

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


      <% @maps.each do |m| %>
          (function(){
          var contentString = "Street address:<%= m.address %>"; 

          var marker = new google.maps.Marker({
              position:{lat: <%= m.latitude %>, lng: <%= m.longitude %>},
              map: map,
              title: contentString
          });

          })();
      <% end %>
      }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>

Like the code above<% @maps.each do |m| %> ~ <% end %>If you write the code you want to repeat in the box, a marker will appear at the position of the posted address or place name.

Reference article

-Rails Geocoder and Play -[[Rails 6 / Google Map API] For beginners! Easy introduction of Google Map API with Ruby on Rails](https://qiita.com/nagaseToya/items/e49977efb6 86ed05eadb "About map display") -[Display multiple markers using Google Maps API in Rails 5](https://qiita.com/yamaotoko4177/items/30b72766d013904452fa 86ed05eadb "About map display") -How to get latitude / longitude from address with Ruby on Rails and Google Geocoding API 86ed05eadb "About map display")

Recommended Posts

[Rails 6 / Google Map API] Post an address and set multiple markers on the map
Display multiple markers on Google Map
[Ruby on Rails] Multiple pins, balloons, and links on Google map
Display the address entered using Rails gem'geocoder' on Google Map
[Rails] google maps api How to post and display including map information
Introducing Google Map API with rails
Grant an access token with the curl command and POST the API
[Google Maps API] Map is not displayed and becomes blank [Rails]
[Ruby on Rails] Display and pinning of GoolgeMAP using Google API
[Map display] Display a map from the address registered by the user using the Google Maps JavaScript API and Geocoding API!
[Rails 6] Embed Google Map in the app and add a marker to the entered address. [Confirmation of details]
[Rails] Displaying Google Maps using Google Maps API and searching routes between multiple points
[Rails] How to calculate latitude and longitude with high accuracy using Geocoding API and display it on Google Map
Display Google Maps API with Rails and pin display
Google Drive API Set File Permission (Set permissions on Google Drive files)
Book registration easily with Google Books API and Rails
Post to your account using the API on Twitter
Beginners of Google Maps API and Twitter API made "tweet map"