Tuesday, June 19, 2012

Using Google Maps with jQuery Mobile

I ran into some problems trying to use Google MapView with jQuery mobile in my PhoneGap app for Android. Basically the map view would load, displaying some of the map tiles, but it would show some grey tiles too. Scrolling or panning around the map would load new tiles but slightly off center, leaving some grey tiles showing.

The problem was that the map view was being initialized while it was on a hidden page--the div page that contained was the map was not being shown.

To solve the problem, instead of loading the map view in the $(document).ready() function I had to listen for the pageshow event and then initialize the map after the page had been loaded and the transition animations completed. Assuming you have something like:


<div data-role="page" id="map-page">
    <div data-role="content">
        <div id="map_canvas"></div>
    </div>
</div>


You can do:


$(document).ready(function() {
    $('#map-page').live('pageshow',mapPageChanged)    
});



var mapPageChanged = function(event) {
    console.log("Map page changed");
    $('#map_canvas').gmap(); // initialize Google map view with jQuery.ui.map plugin here
}


And your map view will stop acting confused.

No comments:

Post a Comment