在一个模型中对多个地址进行地理编码 [英] Geocoding multiple addresses in one model

查看:115
本文介绍了在一个模型中对多个地址进行地理编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使用地理编码器对模型中的2个地址进行地理编码,并且无法让宝石按我的意愿工作。这是我应用于我的模型的代码:

I am trying to geocode 2 addresses in a model using geocoder and I can't get gem to work as I want to. Here is the code that I am applying to my model:

class Sender < ActiveRecord::Base
validates_presence_of :source_address
validates_presence_of :destination_address
geocoded_by :source_address, :latitude => :latitude1, :longitude => :longitude1
geocoded_by :destination_address, :latitude2 => :latitude2, :longitude2 => :longitude2

def update_coordinates
    geocode
    [latitude1, longitude1, latitude2, longitude2]
end

after_validation :geocode  

以下是views / senders / show.html.erb的代码:

Here is code for views/senders/show.html.erb:

 <%= @sender.latitude1 %>
   <%= @sender.longitude1 %>
   <%= @sender.latitude2 %>
   <%= @sender.longitude2 %>

结果:35.6894875 139.6917064 - 是不是应该寄回我2份地址资讯?

Result : 35.6894875 139.6917064 - Isn't it supposed to send me back 2 address information?

以下是我的js:

Here is my js:

<script type="text/javascript">
function initialize() {
  var source = new google.maps.LatLng(<%= @sender.latitude1 %>, <%= @sender.longitude1 %>);
  var dest = new google.maps.LatLng(<%= @sender.latitude2 %>, <%= @sender.longitude2 %>);
  var mapOptions = {
    center: source,
    zoom: 8

  }
  var mapOptions2 = {
    center: dest,
    zoom: 8

  }

  var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
  var map2 = new google.maps.Map(document.getElementById('map_canvas2'), mapOptions2);

  var marker = new google.maps.Marker({
    position:source,
    map: map
  });
  var marker2 = new google.maps.Marker({
    position:dest,
    map: map2
  });
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>


推荐答案

提到的问题和解决方案这里

The problem and solution are mentioned here.

添加以下 before_save 以及相应的方法来解决问题。不要忘记为第二个地点(也许是目的地)重复部分代码:

Add the following before_save and corresponding method to your model to solve the problem. Don't forget to repeat the part of code for the second location (maybe destination):

before_save :geocode_endpoints

  private
  #To enable Geocoder to works with multiple locations
  def geocode_endpoints
    if from_changed?
      geocoded = Geocoder.search(loc1).first
      if geocoded
        self.latitude = geocoded.latitude
        self.longitude = geocoded.longitude
      end
    end
    # Repeat for destination
        if to_changed?
      geocoded = Geocoder.search(loc2).first
      if geocoded
        self.latitude2 = geocoded.latitude
        self.longitude2 = geocoded.longitude
      end
    end
  end

这篇关于在一个模型中对多个地址进行地理编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆