[RUBY] [Map display] Display a map from the address registered by the user using the Google Maps JavaScript API and Geocoding API!

Overview

The time when the map is displayed on the post detail page from the address registered by the user using the Google Maps JavaScript API and Geocoding API is recorded as a memorandum.

environment

・ Ruby '2.5.7' ・ Rails '5.2.3'

Premise

・ You have already obtained the API key for Google Maps. -The post model (here, the Datespot model) has an address column.

【reference】 Get the API key for Google Maps

process

1. Creating a post details page

Please create the post details page according to your own specifications.

views/show.html.erb


<div class="container">
  <div class="row">
  (abridgement)
    <div class="col-md-8">
      <h2 class="datespot-name"><%= @datespot.name %></h2>
      <div class="datespot-info">
    (abridgement)
        <h4 id="address">【Street address】<%= @datespot.address %></h4>
    (abridgement)
      </div>
    </div>
  </div>
</div>
<%= render "map-show" %>

2. Create a view to display the map

Create a view that displays the map.

views/_map-show.html.erb


<div class="map-container">
  <div class="map_wrapper">
    <div id="map" class="map"></div>
  </div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=<%= ENV['GOOGLE_MAP_API_KEY']%>&callback=initMap"></script>

Let's put the obtained API key in the environment variable.

stylesheets/custom.scss


#map{
  height: 310px;
  width: 550px;
}

If you do not explicitly specify the size of the map, it will not be displayed, so be sure to specify it.

3. Define a callback function

Define the callback function described in 2.

javascripts/map-show.js


function initMap() {
  //Assign the object of the div element of the area to display the map to the variable
  var target = document.getElementById('map');
  //Marker title
  var title = $('.datespot-name').text();
  //Obtaining the address described in HTML
  var address = document.getElementById('address').textContent;
  //Generating an instance of geocoding
  var geocoder = new google.maps.Geocoder();

  //geocoder.geocode()Pass the address to and write the callback function to process
  geocoder.geocode({ address: address }, function(results, status){
  //Status is OK and results[0]Generate a map if exists
    if (status === 'OK' && results[0]){
      //Assign an instance of the map to a variable
      var map = new google.maps.Map(target, {
      //results[0].geometry.location contains latitude / longitude objects
        center: results[0].geometry.location,
        zoom: 15
      });
      //Marker generation
      var marker = new google.maps.Marker({
        position: results[0].geometry.location,
        map: map,
        animation: google.maps.Animation.DROP
      });
      //Generation of acquired coordinates
      var latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
      //Create content to display in the info window
      var content = '<div id="map_content"><p>' + title + '<br/>' + address + '<br/><a href="https://maps.google.co.jp/maps?q=' + latlng + '&iwloc=J" target="_blank" rel="noopener noreferrer">View on Google Maps</a></p></div>';
      //Create an instance of the info window
      var infowindow = new google.maps.InfoWindow({
        content: content,
      });
      //Click marker to display information window(Listener registration)
      google.maps.event.addListener(marker, 'click', function() {
        //Specify a marker in the second argument and associate
        infowindow.open(map, marker);
      });
    }else{
    //If the status is other than OK or results[0]If does not exist, an alert is displayed and processing is interrupted.
      alert("The location could not be obtained from the address.: " + status);
      return;
    }
  });
}

var target = document.getElementById ('map'); is It refers to the <div id = "map" class = "map"> </ div> in views / map-show.html.erb.

var title = $ ('.datespot-name'). text (); is It refers to <h2 class = "datespot-name"> <% = @ datesspot.name%> </ h2> in views / show.html.erb.

var address = document.getElementById ('address'). TextContent; It refers to <h4 id = "address"> [address] <% = @ datesspot.address%> </ h4> in views / show.html.erb.

result

You can now display the map on the post details page from the address registered by the user! 200927_地図の表示.png

reference

How to use and use Google Maps API Let's use Google Maps

Recommended Posts

[Map display] Display a map from the address registered by the user using the Google Maps JavaScript API and Geocoding API!
[For beginners] How to display maps and search boxes using the GoogleMap Javascript API
Display the address entered using Rails gem'geocoder' on Google Map
Explains JavaScript of Google Maps Geocoding API
[Rails] google maps api How to post and display including map information
How to display Map using Google Map API (Android)
Display Google Maps API with Rails and pin display
[Rails 6 / Google Map API] Post an address and set multiple markers on the map
[Rails] How to calculate latitude and longitude with high accuracy using Geocoding API and display it on Google Map
Create a tweet heatmap with the Google Maps API
A little bit from Python using the Jenkins API
Beginners of Google Maps API and Twitter API made "tweet map"
The story of creating a database using the Google Analytics API
Create a model to store information from the Google Books API for intuitive handling and testing
Do a search by image from the camera roll using Pythonista3
How to get followers and followers from python using the Mastodon API
[Google Maps API] Map is not displayed and becomes blank [Rails]
[Ruby on Rails] Display and pinning of GoolgeMAP using Google API
[Rails 6] Embed Google Map in the app and add a marker to the entered address. [Confirmation of details]
Let's display the map using Basemap
Note that the Google Maps Android API GoogleMap.getProjection is not a singleton
Display the result of video analysis using Cloud Video Intelligence API from Colaboratory.
[Rails] Displaying Google Maps using Google Maps API and searching routes between multiple points
Get news from three major mobile companies using Django and the News API
Send an email from the VirtualBox CentOS 8 server using your Google account as the sending address and using the app password
Get the address from latitude and longitude
Create a REST API using the model learned in Lobe and TensorFlow Serving.
Image analysis was easy using the data and API provided by Microsoft COCO.