rails 5 turbolinks 5 和 google 映射如何?

rails 5 turbolinks 5 and google maps how to?

我将 rails 5 与 turbolinks 5 一起使用,并尝试使用 google 网站上的示例 google 让 google 地点自动完成地址表单工作 here

我只想加载此页面上的 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>

根据文档:

Turbolinks evaluates script elements in a page’s body each time it renders the page. You can use inline body scripts to set up per-page JavaScript state or bootstrap client-side models. To install behavior, or to perform more complex operations when the page changes, avoid script elements and use the turbolinks:load event instead.

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

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

什么时候应该:

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

也试试这个....

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

我解决了 Turbolinks 5 和 Google 地图 API 问题,只是在我的 google 地图脚本标签上使用 data-turbolinks-eval="false" 属性。

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

并在您的 coffee/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)
})

我对其他答案不满意,因为 Google 如果多次加载,地图会发出警告,例如在重新访问页面时,禁用 Turbolinks 会破坏其目的。还使用 Google 地图 JavaScript API 的 callback 参数强制您污染 window 名称 space.

相反,我们可以获得 Google 地图脚本,例如使用 jQuery,当且仅当它尚未加载时。这是我在 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()