Search code examples
ruby-on-railsrubygoogle-mapsgoogle-maps-api-3google-api-javascript-client

Google Maps did not load correctly, ERROR: You seem to be using a malformed key. (Invalid Key)


I have set up an API Key and enabled it for Geocoding API as well as Javascript Map API. However, google map did not load correctly on my show page. The error keep mentioning that I did not have an API key, though I did, and I save it in env

Google Maps did not load correctly on this page.

Here's the error message on the console

x You are using this API without a key.
△ Google Maps JavaScript API warning: NoAPIKey
△ Google Maps JavaScript API warning: InvalidKey

Application.html.erb

     <%= yield %>
      <%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?libraries=places&key=#{ENV['GOOGLE_API_BROWSER_KEY']}" %>
      <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
      <%= javascript_pack_tag 'application' %>
      <%= javascript_pack_tag "map" %>

show.html.erb

        <script async defer src="https://maps.googleapis.com/maps/api/js?key=#{ENV['GOOGLE_API_BROWSER_KEY']}&callback=initMap"
  type="text/javascript"></script>
        <div
  id="map"
  style="width: 100%;
  height: 500px;"
  data-markers="<%= @markers.to_json %>"
></div>

controllers

class EventsController < ApplicationController
 def show
    @event = policy_scope(Event).find(params[:id])
    authorize @event
    @markers = [{
                  lat: @event.latitude,
                  lng: @event.longitude
    }]
  end
 end

javascript/packs/map.js

import GMaps from 'gmaps/gmaps.js';

const mapElement = document.getElementById('map');
if (mapElement) {
  const map = new GMaps({ el: '#map', lat: 0, lng: 0 });
  const markers = JSON.parse(mapElement.dataset.markers);
  map.addMarkers(markers);
  if (markers.length === 0) {
    map.setZoom(2);
  } else if (markers.length === 1) {
    map.setCenter(markers[0].lat, markers[0].lng);
    map.setZoom(14);
  } else {
    map.fitLatLngBounds(markers);
  }
}


Please let me know if you have any additional question or if you need anymore info.

Appreciate all your helps!


Solution

  • The problem is that you are expecting this to be interpolated:

    <script async defer src="https://maps.googleapis.com/maps/api/js?key=#{ENV['GOOGLE_API_BROWSER_KEY']}&callback=initMap"
      type="text/javascript"></script>
    

    However its just a chunk of HTML. You need to use ERB tags or the script_tag helper:

    <script async defer src="https://maps.googleapis.com/maps/api/js?key=<%= ENV['GOOGLE_API_BROWSER_KEY'] %>&callback=initMap"
      type="text/javascript"></script>
    

    You could also just write a helper to clean it up:

    module GMapsHelper
      def gmaps_script_tag(**options)
         options[:key] ||= ENV['GOOGLE_API_BROWSER_KEY']
         script_tag "https://maps.googleapis.com/maps/api/js?#{options.to_query}"
      end
    end
    

    Usage

    <%= gmaps_script_tag(callback: 'initMap') %>
    <%= gmaps_script_tag(libraries: 'places') %>