Geocoding multiple addresses in one model

前端 未结 2 702
余生分开走
余生分开走 2021-01-16 08:06

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:

clas         


        
相关标签:
2条回答
  • 2021-01-16 08:21

    The problem and solution are mentioned here.

    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
    
    0 讨论(0)
  • 2021-01-16 08:36

    Rewrite

    def function
    ...
    end
    

    as:

    def update_coordinates
      geocode
      [latitude, longitude, latitude2, longitude2]
    end
    

    And also:

    geocoded_by :destination_address, :latitude => :latitude2, :longitude => :longitude2
    

    You also don't need :latitude => :lat, :longitude => :lon here:

    geocoded_by :source_address, ...
    

    And finally, coordinates are fetched automatically after record is validated. So you could do without update_coordinates (or function, in your version) and arrange the view for show action like this:

    <%= @sender.latitude %>
    <%= @sender.longitude %>
    <%= @sender.latitude2 %>
    <%= @sender.longitude2 %>
    
    0 讨论(0)
提交回复
热议问题