A how-to information
I used to be just lately including a function to considered one of my Rails initiatives that might enable the person to enter a location and get again an inventory of breweries with an interactive map. The Google Maps API is clearly a preferred selection for this however I used to be stunned to see that there aren’t an entire lot of sources on-line for incorporating it right into a Rails app. To treatment this, let’s check out how one can go about making customized maps with this information.
First issues first, let’s arrange the area the place the map will go. Within the view, file make a bit for the map. Give it a easy id like “map”.
.env file. Ensure that this file is asserted in
.gitignore so that you don’t push your key to Github!
You have to a latitude and longitude for every location to place into the Google Maps API. I like to recommend utilizing the Geocoder gem for this.
If utilizing Rails 6 it ought to go in
Passing the Coordinates
Every brewery displayed in an inventory has their coordinates inside their
<li> tag as
data-longitude. The town that the breweries are situated in has its coordinates within the
<div> with the id of “breweries”.
map.js the file we could have one perform that creates a map, grabs the coordinates from the web page, and provides markers to the map with these coordinates. The place the map facilities on (a metropolis on this case) must be designated and are as much as you on the way you seize these coordinates (once more, Geocoder is beneficial for this).
For the sake of brevity, we’ll assume you have already got that data.
The perform will seize the coordinates for the town and use it as the middle place when creating the map. Then it is going to seize every brewery record merchandise and iterate over them, retrieve their coordinates, and create markers to put on the map to designate the place of every brewery. With all this in place we at the moment are able to name the Google Maps API within the view!
Creating the Map
map.js file will be made accessible with a Rails helper. They differ relying on whether or not you’re utilizing Rails 6 or 7.
We’ll place this within the view. The decision to the Google Maps API is completed utilizing a
<script> tag. There may be additionally a Rails helper for this:
With each helpers in place your view ought to now look one thing like this:
initMap as a callback which provides it the data it must create a map and markers. Notice we’re utilizing the
Since we’re counting on information units on the web page to get our coordinates we should be sure that the DOM content material is loaded earlier than our perform is named. The
defer attribute will wait till the HTML is assembled earlier than calling the API and utilizing the
initMap perform. The map will now be constructed and positioned in
<div id="map"> .
Now you’ve gotten a completely dynamic map in your Rails app. Hope you discovered this information useful. Keep secure and wholesome on the market!