Google Maps - Rails 5 Customization - Geocoder Not Geocoding

I tried 4 more years to try and find a way to use Google maps in my Rails application. I'm trying to use Rails 5 now.

I recently wrote this cry for help. The suggestions I received did not work for me, so again I try to find out if anyone else can know something. Rails 5, Gmaps4Rails - customization

I have models for organization and address.

Associations:

Organization

has_many :addresses, as: :addressable
    accepts_nested_attributes_for :addresses,  reject_if: :all_blank, allow_destroy: true

The address

belongs_to :addressable, :polymorphic => true, optional: true

I am no longer trying to figure this out with the gmaps4rails gem. I deleted this from my gem file. However, I still have a geocoder stone.

In my address controller I have

def index
    @addresses = Address.all
    end

    def show

    end

In my organizational controller I have

def index
    @organisations = Organisation.all
    authorize @organisations
  end

  def show
    @addresses = @organisation.addresses.all

  end

In my view of the organization, I have

<%= render 'contacts/addresses/map' %>

In my address view, I have

<%= javascript_tag do %>
  var addresses = <%= raw @addresses.to_json %>;
<% end %>


<script src="https://maps.googleapis.com/maps/api/js?key=<%= ENV["GOOGLE_MAPS_API_KEY"] %>&callback=initMap"
    async defer></script>

address.js

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4
  });
  var bounds = new google.maps.LatLngBounds();

  var n = addresses.length;
  for (var i = 0; i < n; i++) {
    var address = new google.maps.Marker({
      position: {lat: parseFloat(addresses[i].latitude), lng: parseFloat(addresses[i].longitude)},
      title: addresses[i].name,
      map: map
    });
    bounds.extend(address.position);
  }

  map.fitBounds(bounds);
}

, , .

, :

js?key=.....&callback=initMap:42 Uncaught RangeError: Maximum call stack size exceeded

Uncaught RangeError: Google, , , , lat/lng js. , , .

:

class Address < ApplicationRecord

  geocoded_by :full_address   # can also be an IP address

  # --------------- associations

  belongs_to :addressable, :polymorphic => true, optional: true

  # --------------- scopes

  # --------------- validations


  # --------------- class methods


  def unit_line
    if self.unit.present? 
      ['Unit', unit.titlecase].join(' ')
    end
  end

  def first_line
    [street_number, street.titlecase].join(' ')
  end

  def middle_line
    if self.building.present? 
      ['Building', building.titlecase].join(' ')
    end
  end

  def last_line
    [city.titlecase, region.upcase, zip].join('   ')
  end

  # def country_name
  #   # self.country = ISO3166::Country[country]
  #   # country.translations[I18n.locale.to_s] || country.name

  #   # iso_country = ISO3166::Country.find_by_name(country) # `country` should be name like 'Australia'
  #   # iso_country.translations[I18n.locale.to_s] || iso_country.name
  # end

  # def country_name
  #   self.country = ISO3166::Country[country]
  #   country.translations[I18n.locale.to_s] || country.name
  # end

  def country_name
    country = self.country
    ISO3166::Country[country]
  end



  def full_address
    [self.unit_line, first_line, middle_line, last_line, country_name].compact.join("<br>").html_safe
  end


  # --------------- callbacks

  after_create :geocode#, if  self.full_address.changed? 

:

after_validation :geocode



  # --------------- instance methods

  # --------------- private methods



end

. , .

geocoder.rb :

Geocoder.configure(
  # Geocoding options
   :timeout      => 3,           # geocoding service timeout (secs)
   :lookup       => :google,     # name of geocoding service (symbol)
   :language     => :en,         # ISO-639 language code
   :use_https    => true,       # use HTTPS for lookup requests? (if supported)
  # :http_proxy   => nil,         # HTTP proxy server (user:pass@host:port)
  # :https_proxy  => nil,         # HTTPS proxy server (user:pass@host:port)
   :api_key      => nil,         # API key for geocoding service
  # :cache        => nil,         # cache object (must respond to #[], #[]=, and #keys)
  # :cache_prefix => "geocoder:", # prefix (string) to use for all cache keys

  # exceptions that should not be rescued by default
  # (if you want to implement custom error handling);
  # supports SocketError and TimeoutError
  # :always_raise => [],

  # calculation options
   :units     => :km,       # :km for kilometers or :mi for miles
  # :distances => :linear    # :spherical or :linear
)

- , , ?

, address.rb, , lat/lng .

a = Address.first
  Address Load (30.2ms)  SELECT  "addresses".* FROM "addresses" ORDER BY "addresses"."id" ASC LIMIT $1  [["LIMIT", 1]]
 => #<Address id: 8, unit: "16", building: "asdf", street_number: "15", street: "Johnston Street", city: "Balmain East", region: "NSW", zip: "2041", country: "AU", time_zone: "Midway Island", addressable_id: 1, addressable_type: "Organisation", description: "registered_office", created_at: "2016-11-10 00:16:50", updated_at: "2016-11-10 00:16:50", latitude: nil, longitude: nil> 

, lat/lng.

Address.where(latitude: nil).or(Address.where(longitude: nil)).each{|marker| marker.save}
  Address Load (16.3ms)  SELECT "addresses".* FROM "addresses" WHERE ("addresses"."latitude" IS NULL OR "addresses"."longitude" IS NULL)
   (2.0ms)  BEGIN
   (0.8ms)  COMMIT
 => [#<Address id: 8, unit: "1", building: "asdf", street_number: "10", street: "Darling Street", city: "Balmain", region: "NSW", zip: "2041", country: "AU", time_zone: "Midway Island", addressable_id: 1, addressable_type: "Organisation", description: "registered_office", created_at: "2016-11-10 00:16:50", updated_at: "2016-11-10 00:16:50", latitude: nil, longitude: nil>] 
+1
1

, . Rails .

gem 'geocoder' Gemfile.

bundle install

geocoded_by :name   # can also be an IP address
after_validation :geocode

Marker, , : .

rails c:

Marker.create(:name => 'New Dehli')
Marker.create(:name => 'New-York')

, !

. - - , , " " js. , , , after_validation :geocode :

Marker.where(latitude: nil).or(Marker.where(longitude: nil)).each{|marker| marker.save}

, .

- , js :

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4
  });
  var bounds = new google.maps.LatLngBounds();

  var n = markers.length;
  for (var i = 0; i < n; i++) {
    var lat = markers[i].latitude;
    var lng = markers[i].longitude;
    if (lat == null || lng ==null){
      console.log(markers[i].name + " doesn't have coordinates");
    }else {
      var marker = new google.maps.Marker({
        position: {lat: parseFloat(lat), lng: parseFloat(lng)},
        title: markers[i].name,
        map: map
      });
      bounds.extend(marker.position);
    }
  }
  map.fitBounds(bounds);
}
0

Source: https://habr.com/ru/post/1658795/


All Articles