在ajax调用中,gmaps4rails地图在画布上不会完全显示

时间:2013-08-01 13:02:53

标签: javascript ajax google-maps styling gmaps4rails

我正在使用带有mongoid和bootstrap的gmaps4rails。当我点击下一步按钮以通过ajax调用加载地图时,地图不会完全出现在画布上(参见附图)。当我在没有javascript调用的情况下渲染gmaps4rails(@json)时,它正常工作。但我需要在这里使用javascript。 这是我的档案。

的CSS

.map_container {
  padding: 6px;
  border-width: 1px;
  border-style: solid;
  border-color: #ccc #ccc #999 #ccc;
  -webkit-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px;
  -moz-box-shadow: rgba(64, 64, 64, 0.5) 0 2px 5px;
  box-shadow: rgba(64, 64, 64, 0.1) 0 2px 5px;
  width: 100%;
}

.gmaps4rails_map {
  width: 100%;
  height: 400px;
}

.bing_map {
   position: absolute;
   top: 20;
   left: 10;
   width: 400px;
   height: 400px;
   border:#555555 2px solid;
}

 #map label { width: auto; display:inline; }
 #map img { max-width: none; }

查看

     #wizard-step-2-content.hide{ data: { step: 2 } }   
    .row
      = gmaps({:last_map => false })
      /- content_for :scripts do
      /  :javascript
      /    Gmaps.map.callback = function() {
      /      alert('asdf') // <-- I never see this alert
      /    }
      /= gmaps(@gmap_options)
      .span12.text-center
    .row
      #providers-thumbs
      = hidden_field_tag :selectedproviders, id: 'selectedproviders'
      /= share_on_facebook_timeline_checkbutton(f)
  .form-actions.pagination-centered

    = button_tag t('.previous_step'), type: 'button', class: 'btn btn-large hide', name: 'back_button', id: 'wizard-prev-step-button', disabled: true
    = f.submit t('.next_step'), type: 'button', class: 'btn btn-large btn-primary', name: 'next_button', id: 'wizard-next-step-button', disabled: false

模型(使用gmap4rails +使用mongoid进行地理编码的示例)

include Mongoid::Timestamps
  include Mongoid::Paranoia
  include Mongoid::Geospatial
  include Mongoid::MultiParameterAttributes
  include Mongoid::Slug
  include Gmaps4rails::ActsAsGmappable
  acts_as_gmappable :lat => 'latitude', :lon => 'longitude', :process_geocoding => true,
                    :check_process => :prevent_geocoding,
                    :address => "business_address"

控制器

   skip_before_filter :require_login, only: [:show, :search] 
  before_filter :check_permissions  
  respond_to :html, :json

  def getlocation    
    if request.post?
      session[:latitude] = nil
      session[:longitude] = nil
      session[:latitude] = params[:latitude] 
      session[:longitude] = params[:longitude]
      session[:categoryid] = params[:categoryid]  
      data  =   { :latitude => session[:latitude].to_f, :longitude => session[:longitude].to_f,:categoryid => session[:categoryid] }
      respond_to do |format|
      format.json  { render :json => data}
      end
    else  
      searchterm = session[:categoryid].to_s
      @places = Provider.all.near(:location [ session[:latitude].to_f,session[:longitude].to_f ]).within_circle(location: [[ session[:latitude].to_f,session[:longitude].to_f ], 150 ]).where(:category.to_s => /.*#{searchterm}.*/).entries     #where(session[:categoryid].in  =>  :category  )
      @json = @places.to_gmaps4rails 
      respond_to do |format|
      format.json  { render :json =>@places} 

      end
    end 
  end  

js.coffee

   wizardNextStep = ->

  categoryid = $("#categoryid").val()
  latitude =  $("#latitude").val()
  longitude = $("#longitude").val()
  markers = 
    lat: latitude
    lng: longitude
    picture: "http://icons.iconarchive.com/icons/icons-land/vista-map-markers/32/Map-Marker-Marker-Outside-Chartreuse-icon.png"
    width: 30
    height: 30

  $.ajax
    url: "/providers/getlocation"
    data:
      latitude: latitude
      longitude: longitude
      categoryid:  categoryid    
    type: "POST"    
    success: (data) ->
     $.getJSON "/providers/getlocation", (json) ->  
      $(".map_container").show()
      Gmaps.map = new Gmaps4RailsGoogle()      
      Gmaps.load_map = ->     
        Gmaps.map.initialize()
        Gmaps.map.map_options.detect_location = false;
        Gmaps.map.map_options.center_on_user = true;
        Gmaps.map.addMarkers json  
        Gmaps.map.addMarkers(markers) 
        Gmaps.map.create_markers()
        Gmaps.map.adjustMapToBounds();
        Gmaps.map.callback();
      Gmaps.loadMaps()        
      #google.maps.event.trigger(map, 'resize')  

      $('#providers-thumbs').html ''
      index = 0
      #hizmetkutusu.latLngBounds = new google.maps.LatLngBounds()
      row_template = $("""<div class="span12" ></div>""")
      row = row_template
      $(json).each ->
        $('#providers-thumbs').append(row = row_template.clone(true)) if (index % 2) is 0
        color = routeColoursArray[index++ % routeColoursArray.length]
        #drawPath this, color
        this.borderColor = hexToRgba(color, 0.45) # borderColor injection, waiting for proper @data support in handlebars
        row.append HandlebarsTemplates['providers/thumbnail'](this)     
    failure: ->
      alert "Unsuccessful" 

Application.js.coffee.erb

#= require jquery
#= require jquery_ujs
#= require jquery.turbolinks
#= require turbolinks
#= require jquery.validate
#= require jquery.validate.additional-methods
#= require gmaps4rails/googlemaps.js 

# VENDOR ASSETS
#= require jquery.ba-throttle-debounce
# require waypoints

# CLIENT SIDE VALIDATIONS
#= require rails.validations
#= require rails.validations.turbolinks

Application.html.haml

!!!
%html{ lang: I18n.locale.to_s }
  %head{ prefix: "og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# #{APP_CONFIG.facebook.namespace}: http://ogp.me/ns/fb/#{APP_CONFIG.facebook.namespace}#" }

    %title= yield_or_default :title, controller.action_name.titlecase
    %meta{ name: 'viewport', content: 'width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0' }
    = csrf_meta_tags
    = yield :head
    / Le HTML5 shim, for IE6-8 support of HTML elements
    /[if lt IE 9]
      = javascript_include_tag "http://html5shim.googlecode.com/svn/trunk/html5.js"

    = stylesheet_link_tag 'http://fonts.googleapis.com/css?family=Ubuntu:400,500,700|Pacifico', 'application', media: 'all'


    / Touch icons
    %link{ href: asset_path('apple-touch-icon.png'), rel: 'apple-touch-icon' }
    %link{ href: asset_path('apple-touch-icon-72x72.png'), rel: 'apple-touch-icon', sizes: '72x72' }
    %link{ href: asset_path('apple-touch-icon-114x114.png'), rel: 'apple-touch-icon', sizes: '114x114' }
    %link{ href: asset_path('apple-touch-icon-144x144.png'), rel: 'apple-touch-icon', sizes: '144x144' }


    / Placed at the top of the document 'cause of turbolinks
    = javascript_include_tag 'http://maps.googleapis.com/maps/api/js?sensor=true&libraries=geometry,places', 'application'
    = analytics_init if APP_CONFIG.google_analytics_id.present?

  %body
    /= yield :scripts
    = render 'shared/navbar'    
    #main-container.container= yield     

    #footer= render 'shared/footer'

first page

second page

我做什么我无法让它发挥作用。我尝试添加yield:脚本,包含回调函数,触发中心地图,禁用查找用户位置......无法正常工作... googlemaps.js和gmaps4rails.googlemaps.js.coffee已包含在内。还尝试将它们包含在应用程序文件中。将gem升级到2.0.0然后降级到正常。它在我将loadmaps放在函数顶部之前部分工作,但现在它甚至无法工作,即使我把它放在顶部或底部。 代码变得一团糟。我无法解决它! 请帮帮我:/

1 个答案:

答案 0 :(得分:0)

没有人帮助我,所以我尝试找到一个肮脏的解决方案。问题出在wizard-step-2-content的hide()函数中。我没有隐藏内容,我只是隐藏并显示了行,它开始工作而没有回调,触发reize或之前写的任何其他内容。

查看

 #wizard-step-2-content{ data: { step: 2 } }   
    #xxx1.row.hide()
      = gmaps({:last_map => false })
      .span12.text-center
    .row
      #providers-thumbs
      = hidden_field_tag :selectedproviders, id: 'selectedproviders'
      /= share_on_facebook_timeline_checkbutton(f)
  .form-actions.pagination-centered

<强>咖啡

wizardNextStep = ->
  $("#wizard-step-#{2}-content").fadeIn()
  categoryid = $("#categoryid").val()
  latitude =  $("#latitude").val()
  longitude = $("#longitude").val()
  markers = 
    lat: latitude
    lng: longitude
    picture: "http://icons.iconarchive.com/icons/icons-land/vista-map-markers/32/Map-Marker-Marker-Outside-Chartreuse-icon.png"
    width: 30
    height: 30

  $.ajax
    url: "/providers/getlocation"
    data:
      latitude: latitude
      longitude: longitude
      categoryid:  categoryid    
    type: "POST"    
    success:  ->
     $.getJSON "/providers/getlocation", (json) ->        
      Gmaps.map = new Gmaps4RailsGoogle()            
      Gmaps.load_map = ->     
        Gmaps.map.initialize()
        Gmaps.map.addMarkers json  
        Gmaps.map.addMarkers(markers)  
      Gmaps.loadMaps()  
      $('#providers-thumbs').html ''
      index = 0
      #hizmetkutusu.latLngBounds = new google.maps.LatLngBounds()
      row_template = $("""<div class="span12" ></div>""")
      row = row_template
      $(json).each ->
        $('#providers-thumbs').append(row = row_template.clone(true)) if (index % 2) is 0
        color = routeColoursArray[index++ % routeColoursArray.length]
        #drawPath this, color
        this.borderColor = hexToRgba(color, 0.45) # borderColor injection, waiting for proper @data support in handlebars
        row.append HandlebarsTemplates['providers/thumbnail'](this)     
    failure: ->
      alert "Unsuccessful"  

  arr = new Array()
  $('#providers-thumbs').on 'click', '#givequote', (e) ->
    #e.preventDefault()
    value1 = $("#selectedproviders").val()
    value2 = $(this).data('id')  

    if value1.indexOf(value2) > -1
      arr.splice $.inArray(value2, arr), 1
    else
      arr.push value2

    $("#selectedproviders").val arr     
  $("#xxx1.row").show()