【问题标题】:Using google places search autocomplete in a rails app在 Rails 应用程序中使用谷歌地方搜索自动完成
【发布时间】:2017-06-10 03:31:47
【问题描述】:

我想在 Rails 表单中使用 google 地方自动完成功能。

我正在使用 rails v5.1.1

我正在关注这篇文章:https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

我的应用程序布局如下:

    ...lots of layout code
    <% yield %>

        <!-- this is to yield for additional page specific JS from other external sources -->
        <%= yield :additional_page_js %>

        <%= yield :additional_js %>
</body>

然后我有一个名为 Journeys/show.html.erb 的视图:

<div class="container">
<div class="col-xs-6">

<div class="col-xs-6">
<h4>Let's make a new leg</h4>

<%= simple_form_for(leg, html: { class: 'form-horizontal' }) do |f| %>
  <%= f.error_notification %>
  <%= f.input :journey_id,  as: :hidden %>
  <%= f.input  :name,  label: 'Give your leg a name', error: 'A name is mandatory - name it!' , hint: 'Something friendly...' %>
    <%= f.simple_fields_for :origin do |p| %>
        <%= p.input :name ,  label: 'Origin', error: 'An origin is mandatory - where did you begin?' , hint: 'Where did you begin?', :input_html => { :id => "pac-input", :class => "controls" } %>
    <% end %>
    <%= f.simple_fields_for :destination do |n| %>
        <%= n.input :name ,  label: 'Destination', error: 'A destination is mandatory - where did you end up?' , hint: 'Where did you end up?'%>
    <% end %>
  <%= f.button :submit , "Lets go!" %>
<% end %>

</div>

<div class="col-xs-6">

  <div id="origin_map"></div>

</div>
</div>

<%= content_for :additional_page_js do %>
<%= javascript_include_tag "controllers/journeys/journeys" %>
<% end %>

<%= content_for :additional_js do %>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAP927IOgIj5GshStjMVfGTfMzHj2Dr1uo&libraries=places&callback=initMapAutocomplete"></script>
<% end %>

请注意,content_for 'additional_page_js' 产量具有以下内容(即 Journeys.js):

 function initMapAutocomplete() {

        var map = new google.maps.Map(document.getElementById('origin_map'), {
          center: {lat: -33.8688, lng: 151.2195},
          zoom: 13,
          mapTypeId: 'roadmap'
        });

        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function() {
          searchBox.setBounds(map.getBounds());
        });

        var markers = [];
        // Listen for the event fired when the user selects a prediction and retrieve
        // more details for that place.
        searchBox.addListener('places_changed', function() {
          var places = searchBox.getPlaces();

          if (places.length == 0) {
            return;
          }

          // Clear out the old markers.
          markers.forEach(function(marker) {
            marker.setMap(null);
          });
          markers = [];

          // For each place, get the icon, name and location.
          var bounds = new google.maps.LatLngBounds();
          places.forEach(function(place) {
            if (!place.geometry) {
              console.log("Returned place contains no geometry");
              return;
            }
            var icon = {
              url: place.icon,
              size: new google.maps.Size(71, 71),
              origin: new google.maps.Point(0, 0),
              anchor: new google.maps.Point(17, 34),
              scaledSize: new google.maps.Size(25, 25)
            };

            // Create a marker for each place.
            markers.push(new google.maps.Marker({
              map: map,
              icon: icon,
              title: place.name,
              position: place.geometry.location
            }));

            if (place.geometry.viewport) {
              // Only geocodes have viewport.
              bounds.union(place.geometry.viewport);
            } else {
              bounds.extend(place.geometry.location);
            }
          });
          map.fitBounds(bounds);
        });
      }

content_foradditional_js 有以下内容:

Journeys.css 的 css 包含以下内容:

 #description {
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
      }

      #infowindow-content .title {
        font-weight: bold;
      }

      #infowindow-content {
        display: none;
      }

      #map #infowindow-content {
        display: inline;
      }

      .pac-card {
        margin: 10px 10px 0 0;
        border-radius: 2px 0 0 2px;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        outline: none;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        background-color: #fff;
        font-family: Roboto;
      }

      #pac-container {
        padding-bottom: 12px;
        margin-right: 12px;
      }

      .pac-controls {
        display: inline-block;
        padding: 5px 11px;
      }

      .pac-controls label {
        font-family: Roboto;
        font-size: 13px;
        font-weight: 300;
      }

      #pac-input {
        background-color: #fff;
        font-family: Roboto;
        font-size: 15px;
        font-weight: 300;
        margin-left: 12px;
        padding: 0 11px 0 13px;
        text-overflow: ellipsis;
        width: 400px;
      }

      #pac-input:focus {
        border-color: #4d90fe;
      }

      #title {
        color: #fff;
        background-color: #4d90fe;
        font-size: 25px;
        font-weight: 500;
        padding: 6px 12px;
      }
      #target {
        width: 345px;
      }

当页面加载时 - pac-input 字段不显示 - 实际上它甚至根本不在生成的 HTML 中:

<%= p.input :name ,  label: 'Origin', error: 'An origin is mandatory - where did you begin?' , hint: 'Where did you begin?', :input_html => { :id => "pac-input", :class => "controls" } %>

我没有收到任何 javascript 错误,并且我在服务器日志中也没有收到 rails 错误。

如果我从 Journeys.js 中删除 javascript - 原始表单字段显示工作正常。我相信导致该领域“消失”的那条线是来自 travels.js 的这条线:

 var searchBox = new google.maps.places.SearchBox(input);

请有人帮我让这个谷歌地方搜索自动完成字段工作!

【问题讨论】:

  • 不太了解前端,但不是div 需要additional_page_jsadditional_js
  • 不这么认为? js 本身完全可以加载到页面中。
  • 哦...好吧..

标签: javascript ruby-on-rails ruby google-maps google-places-api


【解决方案1】:

问题原来有两个部分。

1/ 地图 div 没有大小,因此没有显示。通过更改 html 给它一个大小 - 在页面加载现在呈现的地图。

<div id="origin_map" style='width: 100%; height: 30rem;'></div>

2/ 然后我意识到我的输入字段并没有消失——而是被移到了地图的顶部。通过注释掉执行此重新定位的行 - 我能够通过工作谷歌位置自动完成来修复我的表单。

map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 2017-01-25
    • 2019-08-06
    • 2011-09-19
    • 2021-12-28
    相关资源
    最近更新 更多