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

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

我已经设置了一个 API 密钥并启用它用于地理编码 API 以及 Javascript 地图 API。但是,google 地图在我的显示页面上没有正确加载。错误一直提到我没有 API 密钥,虽然我有,但我将它保存在 env

Google Maps did not load correctly on this page.

这是控制台上的错误消息

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>

控制器

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);
  }
}


如果您有任何其他问题或需要更多信息,请告诉我。

感谢您的帮助!

问题是您希望对其进行插值:

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

然而它只是 HTML 的一小部分。您需要使用 ERB 标签或 script_tag 助手:

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

你也可以只写一个助手来清理它:

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

用法

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