Rails 5 Google Maps API included multilpe times error resolution
While working on integrating Google Map with the Rails 5 application, faced an error saying
You have included the Google Maps API multiple times on this page. This may cause unexpected errors.
In this post I will be discussing how to resolve an issue with the loading of google map with the Rails 5 having turbolinks support for the Rails application.
1. Start with a Rails application
Let’s create a new Rails 5 application. Creating a new project with the following Ruby/Rails configuration.
Ruby: 2.4.0 Rails: 5.0.2 (latest stable release)
2. Create controller and views
Let’s create a new controller and view for showing a google map screen.
This will create controller and view resources.
3. Add sample view content
Create a view file index.html.erb
for showing map screen in app/views/maps/
.
Add sample content as given below:
4. Add route for the maps screen
Let’s root the website to maps controller view page.
5. Start the web server
Now, start the web server with the command.
Open up the site at http://localhost:3001/.
It should display the content from app/views/maps/index.html.erb
6. Integrate Google Maps
Google Maps provides javascript API to render google maps. The Maps JavaScript API gives an example illustrating how to integrate google maps with the website.
Let’s use the html and javascript content to render google map on the homepage.
7. Add link to Maps page
Let’s add a link to Maps screen (homepage) as shown below.
The map gets displayed as show below.
8. Warning
When clicking multiple times on the link to the page having google map integrated, the page throws error in the console stating that,
You have included the Google Maps API multiple times on this page. This may cause unexpected errors.
It is shown in the image given below for the reference.
Solution
When debugged, found out that google maps is getting initialized every time we hit the maps page. To avoid reloading the maps again and again, we need to figure out some way to not load google map js if it is already loaded.
Note: We have the GOOGLE_MAPS_API_KEY
as the constant defined.
This can be obtained from the Google Maps javascript integrations page.
The solution demonstrated in above code does not request google maps javascript
if the google
var is initialized
and attached to the windows
.
Conclusion
Now, if we click any number of times on the map page link, we won’t be shown any warning of the kind,
You have included the Google Maps API multiple times on this page. This may cause unexpected errors.
Please feel free to comment and let me know if there is any concern.
Thanks for reading.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox