简体   繁体   English

Ruby on Rails-Geocoder视图

[英]Ruby on Rails - Geocoder view

Im trying to use geocoder for displaying a location based on an address. 我试图使用地址解析器来显示基于地址的位置。

My question is, what do I put in the view to show an interactive map once I got the Lat and Long from the address the user inserted in the database? 我的问题是,一旦从用户在数据库中插入的地址获得纬度和经度,我该在视图中放置什么以显示交互式地图?

my address model 我的地址模型

 belongs_to <another model>
 attr_accessible <all addresses attributes including latitude and longitude>

 geocoded_by :address

 after_validation :geocode, :if => :address_changed?

The fields Latitude and Longitude are automatically calculated after I insert the address. 插入地址后,会自动计算纬度和经度字段。

I've followed Ryan's Rail Cast tutorial but at the end, instead of displaying a static image I want to display a map, google maps interactive style. 我遵循了Ryan的Rail Cast教程,但最后,我不想显示静态图像,而是要显示地图,而是使用Google Maps交互式样式。 How can I achieve this? 我该如何实现?

If've taken a look at Google-Maps-for-Rails but couldn't understand how very well like how to get a single map on location in the show view. 如果看过Google Maps-for-Rails却无法理解如何在show view中获得一张地图。

Take a closer look at Google-Maps-for-Rails . 仔细看看Google Maps-for-Rails That gem makes it trivial, and the instructions on how to get the interactive map in your view are quite clear: 那颗宝石使它变得微不足道,关于如何在视图中获取交互式地图的说明也很明确:

(I'll presume your Address model belongs_to a User model. Change names as appropriate.) (我假设您的地址模型属于用户模型。适当更改名称。)

If you just want the one specific user on the map, of course you could change the controller: 如果只想在地图上显示一个特定的用户,当然可以更改控制器:

@json = User.find(params[:id]).address.to_gmaps4rails

In your view: 您认为:

<%= gmaps4rails(@json) %>

There are many helpful examples for the Google Maps API available here . 有可用的谷歌地图API许多有用的例子在这里 In the simplest case, you can do something like this: 在最简单的情况下,您可以执行以下操作:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  var lat = <%= @model.latitude %>, 
      lon = <%= @model.longitude %>,
      map;
  function initialize() {
    var myOptions = {
      center: new google.maps.LatLng(lat, lon)
    };
    map = new google.maps.Map(document.getElementById('map_canvas'),
        myOptions);
  }

  google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map_canvas"></div>

Just replace @model.latitude and @model.longitude with the corresponding geocoded fields in your model. 只需将@model.latitude@model.longitude替换为模型中相应的地理编码字段即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM