2

我一直在动态更新我的 Gmaps4Rails,方法是等到用户停止在搜索表单中输入 0.5 秒,然后发送 AJAX 请求。但是,在 2 或 3 次请求之后,地图在 Gmaps4Rails.replaceMarkers 之后停止更新,并出现 Javascript 错误

TypeError:无法读取 null 的属性“serviceObject”

我已经追踪到 Gmaps4Rails.clear_marker:

Gmaps4Rails.clearMarker = function(marker) {
  if (marker!=null) { // <-- I've added this line to make it work
    marker.serviceObject.setMap(null);
  }                   // <-- I've added this line to make it work
};

这是需要修补的东西还是我在其他地方做错了什么?

这是我的application.rb中的相关部分

$('.venue_find').live('keyup', function() {
    window.clearTimeout(window.timeOutId);
    window.timeOutId = window.setTimeout(function() {
    $.get('/venues/find?address='+$('#venue_address').val()+","+$('#venue_city').val()+","+$('#venue_state').val()+","+$('#venue_postal_code').val()+","+$('#venue_country').val());
    },500); 
});

地图设置为:

<div id="venue_form">
  <div id="venue_map">
    <%= gmaps("map_options"=>{"centre_latitude"=>51.500181,"centre_longitude"=>-0.12619,"maxZoom" => 16, "auto_zoom"=>true},"markers"=>{"data"=>@json}) %>
  <div id="addresses">
  </div>
</div>

这是来自 */venues/_form.html.erb* 的相关内容

<%= form_for(@venue, :remote=>true) do |f| %>
    <div class="field">
        <%= f.label :address %><br />
        <%= f.text_field :address, :class=>"venue_find" %>
    </div>
    <div class="field">
        <%= f.label :city %><br />
        <%= f.text_field :city, :class=>"venue_find" %>
    </div>
    <div class="field">
        <%= f.label :state %><br />
        <%= f.text_field :state, :class=>"venue_find" %>
    </div>
    <div class="field">
        <%= f.label :postal_code %><br />
        <%= f.text_field :postal_code, :class=>"venue_find" %>
    </div>
    <div class="field">
        <%= f.label :country %><br />
        <%= f.text_field :country, :class=>"venue_find" %>
    </div>
<% end %>

这是场地_controller.rb

def find
  if !params[:address].nil? && params[:address]!=""
    begin
      addresses=Gmaps4rails.geocode(params[:address])
      @json = "[" + addresses.map {|a|  "{\"lng\": \"#{a[:lng]}\",\"lat\": \"#{a[:lat]}\"} " }.join(",")+"]"
      @matched_addresses = addresses.map{|a| a[:matched_address]}.join("<br/>")
    rescue Gmaps4rails::GeocodeStatus
      @json=[]
      @matched_addresses=[]
    end
  else
    @json=[]
  end
  respond_to do |format|
    format.js
  end
end

最后是 find.js.erb

$('#addresses').empty();
$('#addresses').html('<%=pluralize(@matched_addresses.length,'result')%><br/><%=raw @matched_addresses %>');
Gmaps4Rails.replaceMarkers(<%= raw @json %>);
4

1 回答 1

1

我无法重现您的错误,我什至无法理解您的修复为何有用:)

实际上,在clearMarkers所有现有标记上都有一个循环:

for (var i = 0; i < this.markers.length; ++i) {
  this.clearMarker(this.markers[i]);
}

所以如果没有标记,就没有循环......

你能提供更多的上下文吗?

我发布了这个长长的评论作为答案,因为我几乎是唯一一个回答这个标签的人

于 2011-08-10T09:28:14.613 回答