【发布时间】:2020-02-03 10:42:21
【问题描述】:
我在我的页面中嵌入了 Google Map API (Javascript)。但是,地图只有在我刷新一次页面后才会加载。
当我检查控制台时,谷歌地图有两个错误。
❌You have included the Google Maps JavaScript API multiple times on this page.
js?key=<my_key>&callback=initMap:140
This may cause unexpected errors.
❌Uncaught (in promise)
xd {message: "initMap is not a function", name: "InvalidValueError", stack: "Error↵ at new xd (https://maps.googleapis.com/<my_key>&callback=initMap:138:113"}
message: "initMap is not a function"
name: "InvalidValueError"
stack: "Error↵ at new xd
1) 我想我没有多次调用 API,但不知何故有错误消息。
2) 至于第二个,我确实意识到我使用了一个包含 initMap 函数的脚本 src(来自文档),尽管我还没有定义它。 我确实从文档中看到了这个例子,但我不确定在这种情况下我应该如何使用它。
显示.html.erb
<div id="map"
style="width: 100%;
height: 300px;"
data-markers="<%= @markers.to_json %>"
></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=<%= ENV['GOOGLE_API_BROWSER_KEY'] %>&callback=initMap"
type="text/javascript"></script>
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);
}
}
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" %>
【问题讨论】:
标签: javascript ruby-on-rails google-maps google-maps-api-3 maps