・ First, get the API to use googlemap. Click here to get the API (https://qiita.com/nagaseToya/items/e49977efb686ed05eadb)
-Create a column to save the address and a column to save the latitude and longitude. latitude / longitude is latitude / longitude.
schema.rb
create_table "tours", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "address", null: false
t.float "latitude"
t.float "longitude"
end
・ Gemfile ・ Tour.rb ・ .Gitignore ・ .Env ・ Geocorder.rb ・ Show.html.erb
Gemfile
geocorder bundle install
gem 'geocoder'
tour.rb Add the following
tour.rb
geocoded_by :address
after_validation :geocode, if: :address_changed?
Save latitude and longitude from the address entered by geocoded_by. after_validation: geocode saves the changed latitude and longitude even if the address changes later.
Add .env to .gitignore. This doesn't go up on github.
.gitignore
/.env
Add the following to .env. Make the part of YOUR_API_KEY the acquired API key.
.env
GOOGLEMAP=YOUR_API_KEY
geocorder.rb
Create config / initialize / geocorder.rb with rails g geocoder: config
and add the following.
The acquired API is entered in the api_key part.
geocorder.rb
Geocoder.configure(
lookup: :google,
always_raise: [
Geocoder::OverQueryLimitError,
Geocoder::RequestDenied,
Geocoder::InvalidRequest,
Geocoder::InvalidApiKey
],
api_key: ENV['GOOGLEMAP'] ,
use_https: true
)
show.html.erb Finally paste googlemap into show.html.erb
show.html.erb
<div id="map"></div>
<style>
#map {
height: 500px;
width: 70%;
}
</style>
<script>
function initMap() {
var uluru = {lat: <%= tour.latitude %>, lng: <%= tour.longitude %>};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
enter: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<%= ENV['GOOGLEMAP'] %>&callback=initMap"async defer></script>
After that, you can adjust the height and width according to your size preference.
Recommended Posts