首页 > 解决方案 > 谷歌地图没有正确加载,错误:您似乎使用了格式错误的密钥。(无效的密钥)

问题描述

我已经设置了一个 API 密钥,并为 Geocoding API 和 Javascript Map API 启用了它。但是,谷歌地图没有在我的显示页面上正确加载。错误一直提到我没有 API 密钥,虽然我有,我将它保存在 env

Google 地图在此页面上未正确加载。

这是控制台上的错误消息

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

应用程序.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" %>

显示.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);
  }
}


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

感谢您的所有帮助!

标签: ruby-on-railsrubygoogle-mapsgoogle-maps-api-3google-api-javascript-client

解决方案


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

<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') %>

推荐阅读