Rails 5和Turbolinks 5如何使用Google Maps?

7

我正在使用Rails 5和Turbolinks 5,并尝试使用Google网站上的示例(在这里找到)来使Google地点自动完成地址表单工作。

我只想在此页面上加载JavaScript和Google地图库。

如何正确地让以下JavaScript与Rails 5和Turbolinks 5一起工作?

<script>
  // This example displays an address form, using the autocomplete feature
  // of the Google Places API to help users fill in the information.

  // This example requires the Places library. Include the libraries=places
  // parameter when you first load the API. For example:
  // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

  var placeSearch, autocomplete;
  var componentForm = {
    street_number: 'short_name',
    route: 'long_name',
    locality: 'long_name',
    administrative_area_level_1: 'short_name',
    country: 'long_name',
    postal_code: 'short_name'
  };

  function initAutocomplete() {
    // Create the autocomplete object, restricting the search to geographical
    // location types.
    autocomplete = new google.maps.places.Autocomplete(
        /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
        {types: ['geocode']});

    // When the user selects an address from the dropdown, populate the address
    // fields in the form.
    autocomplete.addListener('place_changed', fillInAddress);
  }

  function fillInAddress() {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();

    for (var component in componentForm) {
      document.getElementById(component).value = '';
      document.getElementById(component).disabled = false;
    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      if (componentForm[addressType]) {
        var val = place.address_components[i][componentForm[addressType]];
        document.getElementById(addressType).value = val;
      }
    }
  }

  // Bias the autocomplete object to the user's geographical location,
  // as supplied by the browser's 'navigator.geolocation' object.
  function geolocate() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var geolocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        var circle = new google.maps.Circle({
          center: geolocation,
          radius: position.coords.accuracy
        });
        autocomplete.setBounds(circle.getBounds());
      });
    }
  }
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete"
    async defer></script>
4个回答

6
我通过在谷歌地图脚本标签上添加data-turbolinks-eval="false"属性解决了Turbolinks 5和Google Maps API的问题。
... application.html.erb
<head>
<!-- Other HTML page Head content -->    
<title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>
<script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY" data-turbolinks-eval="false"></script>
<%= javascript_include_tag "application", 'data-turbolinks-track' => 'reload' %>
</head>

在您的咖啡/JS文件中使用:

coffee:
$(document).on "turbolinks:load", ->
  map = new google.maps.Map $('map').get(0), mapOptions
js:
$(document).on("turbolinks:load", function(){
  map = new google.maps.Map($('map').get(0), mapOptions)
})

这样做不起作用,因为当页面卸载事件发生时,JS 需要被卸载和移除,否则此组件的 JS 将无法在后续页面上工作。 - JP Silvashy
Google脚本将由浏览器评估,而不是TurboLinks。因此它将在每个页面重新加载。 当TurboLinks准备就绪时,我们可以创建Google地图对象。 - Jokūbas

3

请尝试以下内容...

google.maps.event.addDomListener(window, 'turbolinks:load', initialize);

很棒的解决方案。谢谢。另请参阅:https://github.com/turbolinks/turbolinks/blob/master/src/turbolinks/compatibility.coffee - Benjamin J. Benoudis

0

我对其他答案不满意,因为如果多次加载Google Maps(例如重新访问页面),它会发出警告,而禁用Turbolinks则违背了其目的。此外,使用Google Maps JavaScript API的callback参数会强制你污染window命名空间。

相反,我们可以使用jQuery获取Google Maps脚本,但前提是它尚未加载。以下是我在Rails 4.2.10中使用的CoffeeScript代码:

initMap = ->
  ...
$(document).on 'turbolinks:load', ->
//  if you would like to limit what views are affected
//  see https://brandonhilkert.com/blog/organizing-javascript-in-rails-application-with-turbolinks/
//  return unless $('.plots.map').length > 0
  if typeof(google)=='undefined' or typeof(google.maps)=='undefined'
    $.get
      url: "https://maps.googleapis.com/maps/api/js?key=<use_your_key>&libraries=geometry"
      dataType: 'script'
      success: initMap
  else
    initMap()

-3
根据文档:

Turbolinks 每次渲染页面时都会评估页面主体中的脚本元素。您可以使用内联主体脚本来设置每个页面的 JavaScript 状态或引导客户端模型。要安装行为,或在页面更改时执行更复杂的操作,请避免使用脚本元素,而是使用 turbolinks:load 事件。

但它对我不起作用的原因是因为在 layouts/application.html.erb 中我有:

<%= javascript_include_tag "application", 'data-turbolinks-track' => true %>

应该是:

<%= javascript_include_tag "application", 'data-turbolinks-track': 'reload' %>

这不是正确的答案,它还会以一种不利的方式改变Turbolinks的行为。 - JP Silvashy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接