1

4 년 이상 Rails 앱에서 Google지도를 사용하는 방법을 찾으려고 노력했습니다. 현재 Rails 5를 사용하고 있습니다.Google지도 - 레일스 5로 작동하도록 설정 - 지오 코더가 아닌 지오 코딩

최근에 나는이 도움 요청을 게시했습니다. 내가받은 제안은 나를 위해 일하지 않았으므로 다른 사람이 뭔가를 알 수 있는지 지금 다시 시도하고 있습니다. Rails 5, Gmaps4Rails - setup

조직 및 주소 모델이 있습니다.

연관성은 다음과 같습니다

기구

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

주소

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

나는 더 이상 gmaps4rails 보석으로이 문제를 알아 내기 위해 노력하고있어. 나는 그것을 보석 파일에서 삭제했다. 그래도 지오 코더 젬이 있습니다. 내 주소 컨트롤러에서

, 내 조직 컨트롤러에서

def index 
    @addresses = Address.all 
    end 

    def show 

    end 

을 가지고, 내 조직보기에서

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

    def show 
    @addresses = @organisation.addresses.all 

    end 

이, 내 주소보기에서

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

이 , 가지고있다

내 address.js에서 698,199,475,314,218,518,453,210

, 나는 줌 설정 나던 제대로 작동하지만, 이것은 실제로지도 내가 콘솔에서 위도와 경도 필드를 설정하는 것이 제공 렌더링

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: Maximum call stack size exceeded Google maps when I try to set bounds는 그 문제가 전달되지 좌표 위도/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에 대한 initialiser이 있습니다

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:[email protected]:port) 
    # :https_proxy => nil,   # HTTPS proxy server (user:[email protected]: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> 

내가 지오를 트리거 에릭의 제안을하려고했으나는 위도/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>] 
+0

,'Address.first.latitude' 무엇을 반환하지? –

+0

nil ..................... – Mel

+0

그리고 그건 당신 문제입니다. 컨트롤러, 뷰 및 자바 스크립트는 잊어 버리십시오. 귀하의 문제는 모델에 있습니다 –

답변

0

평소와 마찬가지로 간단히 시작하여 천천히 코드를 추가하십시오. 이전의 answer에서 기본 Rails 앱을 사용했습니다.

나는 Gemfile에 gem 'geocoder'을 추가했습니다. 소수점 속성 :

bundle install 후, 나는 이미 정의 위도와 경도를 가지고 내 마커 클래스에

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

을 추가했다. rails c에서

:

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

완료, 그들은지도에 표시!

참고 : 어떤 이유로 Marker에 좌표가 없으면 맵이 표시되지 않고 js console에서 "너무 많은 재귀"오류가 발생합니다.

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

마커를 저장하는 지오 코딩을 트리거 검증을 트리거 : 는이 문제를 방지하려면 모든 마커가 모델에 after_validation :geocode이 가능하고 콘솔에서이에서 시작하여 좌표를 가지고 있는지 확인 할 수 있습니다.

어떤 이유로 당신은 여전히 ​​마커, 당신의 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

이 js를 시도하면 콘솔에 다음과 같이 표시됩니다. 정의되지 않은 좌표가 없습니다 – Mel

+0

모델에 이름이 없습니다.마커 [i] .id를 사용할 수 있습니다. –