Jquery Mobile not loading Google Map (except on refresh)

前端 未结 6 1990
温柔的废话
温柔的废话 2021-02-06 02:52

I\'m using Jquery Mobile 1.0 and Google Maps v3 to load a user location map. The map loads fine when accessed via direct url but when accessed from a link, it chokes up and not

6条回答
  •  忘掉有多难
    2021-02-06 03:24

    I had similar issue, and I use external js file.

    Several thing which I did wrong:

    • Need to use pageinit instead of jquery document ready
    • I had a class check to see if before I run my map loading, but it should be at the JQM's div page level like
      , since if the page is loaded via Ajax the body class will be irrelevant.
    • I need to get the correct map canvas, so at the end I set class="map_canvas" instead of id="map_canvas" to avoid id duplication.
    • I then need to know the current active page by doing activePage = $(event.target). With this I can get the correct canvas by $('.map_canvas', activePage). (I encountered once that the map is loaded into some hidden div)
    • Since I am using external js file, all the relevant js file need to be included in every JQM pages. I put them in the layout file which all JQM pages uses.

    My code (coffeescript):

    $(document).on "pageinit", (event) ->
      activePage = $(event.target)
      return if !$(activePage).is('.page-map')
    
      createMap = (options) ->
        canvas = $('.map_canvas', activePage)
        canvas.css(width: '100%', height: '90%')
        map = new google.maps.Map(canvas[0], options)
    
      address = $('.address', activePage).text()
      geocoder = new google.maps.Geocoder()
    
      geocoder.geocode {address: address}, (results, status) ->
        if status == google.maps.GeocoderStatus.OK
          options =
            zoom: 14
            center: results[0].geometry.location
            mapTypeId: google.maps.MapTypeId.ROADMAP
    
          map = createMap(options)
          map.setCenter(results[0].geometry.location)
    

提交回复
热议问题