
ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina
-[Ruby on Rails] Automatically enter the address from the zip code --Google API key issued (Geocoding API Maps JavaScript API) ――The explanation was easy to understand here. -Until you try to display Google Map on Rails 5
This time, the latitude and longitude are acquired using the Geocoding API and displayed on the MAP.
Introduction of 1 gem 2 Create an .env file <-The most important 3 Edit view
Add the following to the Gemfile.
Gemfile
gem "dotenv-rails"
Terminal
$ bundle install
 Create an .env file in the same hierarchy as the Gemfile
.env
SECRET_KEY=My API key
#In the part to add<%= ENV['SECRET_KEY'] %>Can be used by typing)
Add the following to the bottom of the .gitignore file.
.gitignore
/.env
 The display location is OK anywhere. This time it is described on the following page.
erb:app/views/homes/mypage.html.erb
<h2>Your MAP</h2>
<div id='map' class="<%= current_user.prefecture_code + current_user.city + current_user.street %>"></div>
<style>
#map{
  height: 300px;
}
</style>
<script>
let map
let geocoder
function initMap(){
  geocoder = new google.maps.Geocoder()
  geocoder.geocode( { 'address': $('#map').attr('class')}, function(results, status) {
    if (status == 'OK') {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
  map = new google.maps.Map(document.getElementById('map'), {
  center: {lat: -35.6809591, lng: 139.7673068},
  zoom: 13
  });
}
function codeAddress(){
  let inputAddress = document.getElementById('address').value;
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<%= ENV['SECRET_KEY'] %>&callback=initMap" async defer></script>
Below is the code with supplements.
erb:app/views/homes/mypage.html.erb
<h2>Your MAP</h2>
<!-- id=Substitute the registered address in the map class.-->
<div id='map' class="<%= current_user.prefecture_code + current_user.city + current_user.street %>"></div>
<!-- id=Specify the size of the map. * You can put them together in a stylesheet.-->
<style>
#map{
  height: 300px;
}
</style>
<script>
//Since it is also used in the codeAddress below, map is defined outside the function, and geocoder is also prepared.
let map
let geocoder
function initMap(){
  //Initialize geocoder
  geocoder = new google.maps.Geocoder()
  //geocoder geocode()Use method to send a request to the Geocoder API for latitude and longitude.
  // geocode()id to address in method=Substitute the registered address of the map class and get the latitude and longitude.
  geocoder.geocode( { 'address': $('#map').attr('class')}, function(results, status) {
  	//If there are no errors
  	if (status == 'OK') {
    // map.The map is moved to the latitude and longitude described above in setCenter.
      map.setCenter(results[0].geometry.location);
    // google.maps.Marker stands at the specified position on Google Map with Marker
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    //If you get an error
    } else {
    //The error status is displayed in status, and you can solve it by examining the wording.
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
  //Specify the initial position of the map.
  //lat is the history and lng is the latitude. (The following specifies Tokyo Station)
  map = new google.maps.Map(document.getElementById('map'), {
  center: {lat: -35.6809591, lng: 139.7673068},
  //You can change the zoom size to your liking.
  //If the number is large, it is an enlargement.
  zoom: 13
  });
}
function codeAddress(){
  //Get input
  let inputAddress = document.getElementById('address').value;
  //Move map after geocoding
}
</script>
<!--It is a description for reading the Google API key.-->
<script src="https://maps.googleapis.com/maps/api/js?key=<%= ENV['SECRET_KEY'] %>&callback=initMap" async defer></script>
 Recommended Posts