地理编码Gmaps API

时间:2018-07-24 17:27:07

标签: ruby-on-rails google-maps google-api google-maps-markers

我正在使用Google Maps API在Rails上构建Web应用程序(仍在开发中,所以我认为关键不是问题),该功能适用​​于索引视图,但不适用于Show。 这是我到目前为止所做的:

gem "geocoder"

create_table "appointments", force: :cascade do |t|
    t.datetime "date"
    t.string "time"
    t.string "location"
    t.string "status"
    t.text "description"
    t.bigint "car_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.float "latitude"
    t.float "longitude"
    t.index ["car_id"], name: "index_appointments_on_car_id"
  end
  
 <!-- app/views/layouts/application.html.erb -->
 
<body>
  <!-- [...] -->
  <%= javascript_include_tag "application" %>
  <%= javascript_include_tag "https://maps.googleapis.com/maps/api/js" %>
</body>



 <!-- Appointments controller -->
 
class AppointmentsController < ApplicationController

  def index
     @appointments = Appointment.where.not(latitude: nil, longitude: nil)
    @markers = @appointments.map do |a|
      {
        lat: a.latitude,
        lng: a.longitude
      }
    end
  end
  
    def show
    @appointment = Appointment.find(params[:id])
    @markers =
      {
        lat: @appointment.latitude,
        lng: @appointment.longitude
      }
  end
  
  <!-- Index and show view -->
  
    <div
  id="map"
  style="width: 50%;
  height: 600px;"
  data-markers="<%= @markers.to_json %>"
></div>


 <!-- map.js -->
 
 
// app/javascript/packs/map.js
import GMaps from 'gmaps/gmaps.js';

const mapElement = document.getElementById('map');
if (mapElement) { // don't try to build a map if there's no div#map to inject in
  const map = new GMaps({ el: '#map', lat: 0, lng: 0 });
  const markers = JSON.parse(mapElement.dataset.markers);
  map.addMarkers(markers);
  if (markers.length === 0) {
    map.setZoom(2);
  } else if (markers.length === 1) {
    map.setCenter(markers[0].lat, markers[0].lng);
    map.setZoom(14);
  } else {
    map.fitLatLngBounds(markers);
  }
}
 
  <!-- app/views/layouts/application.html.erb -->
<!-- [ ... ] -->
<%= javascript_include_tag "application" %>
<%= javascript_include_tag "https://maps.googleapis.com/maps/api/js" %>
<%= javascript_pack_tag "map" %>

它在索引上效果很好,但没有显示出来。我知道@markers可以正常工作,因为我可以从视图中正确访问lat:lng:,但是标记不存在,并且地图显示了太平洋中部。可能是什么问题?

谢谢!

0 个答案:

没有答案