【问题标题】:Import googlemaps via importmaps in Rails 7在 Rails 7 中通过 importmaps 导入 googlemaps
【发布时间】:2023-02-14 13:12:25
【问题描述】:

在 Rails 7 中通过 importmap 加载 Google 地图的方式是什么?

我见过人们像这样通过脚本标签导入它:

<script src="https://maps.googleapis.com/maps/api/js?key=<%= Rails.application.credentials[:p10_google_maps_js_api_key] %>&callback=initMap" async defer data-turbolinks-eval="false"></script>

但我想利用 Rails 7 的新 importmap 功能。不幸的是,我不明白如何在不将它用作脚本的情况下触发 initMap 回调。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-7 import-maps


    【解决方案1】:

    所以有一个 Stimulus 组件可以使用 stimulus-places-autocomplete。但是,您可以轻松地自己实现它并省去引入依赖项的麻烦。

    在一天结束时,谷歌回调需要被解雇。大多数解决此问题的方法是创建事件并将其附加到窗口。然后,您将一个 data-action 添加到您的视图控制器 div 中,它将查找这个事件并触发它自己的回调。该回调是 Stimulus 控制器本身中的初始化程序。

    ##########places_controller.rb##########

    import { Controller } from "@hotwired/stimulus";
    
    export default class extends Controller {
      static targets = ["street", "city", "state", "zip"];
    
      connect() {
        // Can also initialize this with a CustomEvent
        const event = new Event('google-maps-callback', {
          bubbles: true,
          cancelable: true,
        })
        window.dispatchEvent(event);
      }
    
      // additional actions
    }
    

    ##########index.html.erb##########

    <div
      data-controller="places"
      data-action="google-maps-callback@window->places#initMap"
    >
      <%# view code here %>
    </div>
    
    

    这仍然不是我喜欢的解决方案。但是,这是我们目前的解决方法。

    【讨论】:

      猜你喜欢
      • 2023-01-24
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-24
      • 2021-12-13
      • 2013-01-28
      相关资源
      最近更新 更多