[英]Rails: How to include meta tags in views and not in application.html.erb?
[英]How to include an url in application.html.erb in rails 6?
我正在尝试在我的 rails 应用程序中添加 Google 地图。 我按照指导链接: https : //medium.com/@pjbelo/using-google-maps-api-v3-with-rails-5-2-b066a4b2cf14 (但我使用rails 6)并且我有我的代码:应用程序.html.erb:
<head>
<title>GmapTry</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'https://maps.googleapis.com/maps/api/js?key=AIzaSyA7ClwnGU9QTuNhY3DuVqM5K5YbWA7zJsI' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= yield(:head_tags) %>
</head>
<body>
<%= yield %>
</body>
<% provide :head_tags do %>
<meta name='turbolinks-visit-control' content='reload'>
<script>
document.addEventListener("DOMContentLoaded", function(){
initMap(<%=@place.latitude%>, <%=@place.longitude%>)
});
</script>
<% end %>
...
...
<p>
<div id="map"></div>
</p>
地方.js
function initMap(lat, lng) {
var myCoords = new google.maps.LatLng(lat, lng);
var mapOptions = {
center: myCoords,
zoom: 14
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
应用程序.js
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("gmaps/google")
require("packs/places")
但是当我使用 js 进行下一步时,现在什么也没有显示。 有谁知道为什么? 在 rails 6 中,在 application.html.erb 中写入%= javascript_include_tag 'https://maps.googleapis.com/maps/api/js?key=AIzaSyA7ClwnGU9QTuNhY3DuVqM5K5YbWA7zJsI' %
有什么问题吗?
我看过的每个地图教程都会导致内联脚本标签和全局变量的死胡同,而实际上“以正确的方式”完成这项工作真的很容易。
只需使用具有数据属性的元素将信息从视图传递到您的 JavaScript:
<%= content_tag :div,
"",
class: 'google-maps-widget', # call it whatever you want
data: {
lat: @place.latitude,
lng: @place.longitude
}
%>
理想情况下,您可以将此代码干燥到辅助方法中。 然后只需设置一个事件处理程序,在初始页面加载时或在 turbolinks 刷新页面时加载地图。
document.addEventListener("turbolinks:load", function(){
// find the maps on the page
let maps = document.querySelectorAll(".google-maps-widget");
// loop through the maps
maps.forEach(function(element){
let data = element.dataset;
if (!data.initialized) {
let map = new google.maps.Map(element, {
// you can just use a object literal instead
center: { lat: data.lat, lng: data.lng },
// lets you override the inital zoom
zoom: data.zoom || 14
});
// This keeps the element from being re-initialized
// if turbolinks persists it
element.dataset.initialized = "true";
}
});
});
如果你想在地图上添加一堆标记,你可以在<div class="google-maps-widget"...
元素中添加一堆元素:
<div class="google-maps-widget" ... >
<div class="marker hidden" data-lng="1" data-lng="2">My Favorite spot</div>
...
<end>
然后,您将在初始化地图时解析这些内容。 或者您将数据属性添加到带有 URI 的地图元素,您可以在其中通过 AJAX 获取标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.