Google Maps无法正确加载,错误:您似乎正在使用格式错误的密钥。 (无效的密钥)

时间:2019-10-04 11:30:21

标签: ruby-on-rails ruby google-maps google-maps-api-3 google-javascript-api

我已经设置了API密钥,并将其启用了地址解析API和Javascript Map API。但是,谷歌地图没有正确加载到我的显示页面上。该错误不断提到我虽然没有API密钥,但仍将其保存在env

中。
  

此页面无法正确加载Google Maps。

这是控制台上的错误消息

std::reverse(p + i * bih.width, p + (i + 1) * bih.width);  // Exclusive end, so no -1

Application.html.erb

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

show.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" %>

控制器

        <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>

javascript / packs / map.js

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


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

感谢您的所有帮助!

1 个答案:

答案 0 :(得分:0)

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

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