我已经设置了API密钥,并将其启用了地址解析API和Javascript Map API。但是,Google Geocoder仅适用于不包含街道号之类的详细信息的地址。 (例如,仅城市名称或县名称)。
Rails Console - Geocoder only works for general addresses
尽管它仅适用于带有城市名称的地址,但地图上没有任何显示。仅有一个空白的蓝色界面。
我的配置
Geocoder.configure(
lookup: :google,
use_https: true,
api_key: ENV['GOOGLE_API_SERVER_KEY']
units: :km
)
事件控制器
class EventsController < ApplicationController
skip_before_action :authenticate_user!, only: [:index, :show]
def show
@event = policy_scope(Event).find(params[:id])
authorize @event
@event = Event.find(params[:id])
@markers =
{
lat: @event.latitude,
lng: @event.longitude
}
end
end
事件模型
class Event < ApplicationRecord
validates :location, presence: true
geocoded_by :location
after_validation :geocode, if: :will_save_change_to_location?
end
架构
create_table "events", force: :cascade do |t|
t.string "name"
t.text "description"
t.string "photo"
t.text "location"
t.float "latitude"
t.float "longitude"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "date"
t.bigint "user_id"
t.index ["user_id"], name: "index_events_on_user_id"
end
布局
<body>
<%= render 'shared/navbar' %>
<%= render 'shared/flashes' %>
<%= yield %>
<%= javascript_include_tag 'application' %>
<%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?libraries=places&key=#{ENV['GOOGLE_API_SERVER_KEY']}" %>
<%= javascript_pack_tag 'application' %>
<%= javascript_pack_tag "map" %>
</body>
地图显示
<div
id="map"
style="width: 100%;
height: 500px;"
data-markers="<%= @markers.to_json %>"
></div>
Javascript
import GMaps from 'gmaps/gmaps.js';
const mapElement = document.getElementById('map');
if (mapElement) {
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);
}
}