使用两个地址的地理编码器 [英] Geocoder to work with two addresses

查看:53
本文介绍了使用两个地址的地理编码器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

带有 Geocoder gem 的 rails 4.1.3 应用程序在模型上具有以下属性

rails 4.1.3 application with Geocoder gem has the following attributes on a model

  t.decimal :origin_lon, :precision => 15, :scale => 10
  t.decimal :origin_lat, :precision => 15, :scale => 10
  t.point :origin_lonlat, :srid => 3857
  t.decimal :destination_lon, :precision => 15, :scale => 10
  t.decimal :destination_lat, :precision => 15, :scale => 10
  t.point :destination_lonlat, :srid => 3857

模型定义为

geocoded_by :origin, :latitude  => :origin_lat, :longitude => :origin_lon
geocoded_by :destination, :latitude  => :destination_lat, :longitude => :destination_lon

但是,如果我在控制台中运行:

However if I run in the console:

Circuit.create(origin: 'avenue des Champs-Élysées, 90 Paris', destination: 'Place Mariejol, Antibes')

别看,这是毕加索博物馆...
仅填充目标数据.如果 geocoded_by 指令的顺序颠倒并且服务器重新启动,则正在填充原始数据.很明显,在这种语法下,只有一次调用 geocoded_by 是可能的.

don't look it up, it's the Picasso Museum...
only destination data is being populated. If the order of the geocoded_by instructions are inverted and the server is re-started, then the origin data is being populated. So clearly only one call for geocoded_by is possible under this syntax.

允许同时进行两次搜索的语法是什么?

What syntax allows for the two simultaneous searches?

推荐答案

问题在于 geocoded_by 调用geocoder_init,其中只包含一组选项,所以 geocoded_by :destination 破坏 geocoded_by :origin.

The problem is geocoded_by calls geocoder_init, which only contains one set of options, so geocoded_by :destination clobbers geocoded_by :origin.

def geocoder_init(options)
  unless defined?(@geocoder_options)
    @geocoder_options = {}
    require "geocoder/stores/#{geocoder_file_name}"
    include Geocoder::Store.const_get(geocoder_module_name)
  end
  @geocoder_options.merge! options
end

您可以编写自己的 ActiveRecord 挂钩来对两者进行地理编码:

You can write your own ActiveRecord hook to geocode both:

class Circuit < ActiveRecord::Base
  before_save :geocode_endpoints

  private

  def geocode_endpoints
    if origin_changed?
      geocoded = Geocoder.search(origin).first
      if geocoded
        self.origin_lat = geocoded.latitude
        self.origin_lon = geocoded.longitude
      end
    end
    # Repeat for destination
  end
end

看看geocode 方法 看看 gem 是如何做的,它处理什么样的错误.等等.不幸的是,我们不能使用 do_lookup 因为它依赖于配置的选项而不是接受参数.

Take a look at the geocode method to see how the gem does it, what kind of errors, it handles. etc. Unfortunately, we can't use do_lookup because that relies on the configured options instead of accepting parameters.

这篇关于使用两个地址的地理编码器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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