Oh my god. It's full of code!

Google Maps in jQuery UI Dialog

Just a quick fix type of post that hopefully someone finds in their googling. If you are attempting to use a google map (either v2 or v3) in your page, and want it inside a jQuery UI dialog box, you will likely run into a strange behavior where half the map is grey. You can pan around, zoom and such, but the map itself just acts weird. Only chunks of it show up. The reason for this, as close as I can find is that the map figured out how large it can be by finding the size of it’s parent container. So when you make a dialog box that isn’t autoopen it has no size. So the map says ‘ok, I guess I don’t really have a size’ and it proceeds to freak out. The fix is super simple, but it took me way to long to find and properly implement.

First of all, check out a demo Here

Then check out the source

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Google Map in jQuery dialog box</title>

<script src="http://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"  type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"  type="text/javascript"></script>

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/ui-darkness/jquery-ui.css" />
<style>
    .gBubble
    {
        color:black;
        font-family:Tahoma, Geneva, sans-serif;
        font-size:12px;    
    }
</style>
<script>
    var map;
    var coords = new Object();
    var markersArray = [];
    coords.lat = 44.856051;
    coords.lng = -93.242539;
    
    $(document).ready(function() 
    {
        
        $( "#map_container" ).dialog({
            autoOpen:false,
            width: 555,
            height: 400,
            resizeStop: function(event, ui) {google.maps.event.trigger(map, 'resize')  },
            open: function(event, ui) {google.maps.event.trigger(map, 'resize'); }      
        });  

        $( "#showMap" ).click(function() {           
            $( "#map_container" ).dialog( "open" );
            map.setCenter(new google.maps.LatLng(coords.lat, coords.lng), 10);
            return false;
        });    
        $(  "input:submit,input:button, a, button", "#controls" ).button();
        initialize();
        plotPoint(coords.lat,coords.lng,'Mall of America','<span class="gBubble"><b>Mall of America</b><br>60 East Brodway<br>Bloomington, MN 55425</span>');
    });

    function plotPoint(srcLat,srcLon,title,popUpContent,markerIcon)
    {
            var myLatlng = new google.maps.LatLng(srcLat, srcLon);            
            var marker = new google.maps.Marker({
                  position: myLatlng, 
                  map: map, 
                  title:title,
                  icon: markerIcon
              });
              markersArray.push(marker);
            var infowindow = new google.maps.InfoWindow({
                content: popUpContent
            });
              google.maps.event.addListener(marker, 'click', function() {
              infowindow.open(map,marker);
            });                                          
    }
    function initialize() 
    {      
    
        var latlng = new google.maps.LatLng(coords.lat, coords.lng);
        var myOptions = {
          zoom: 10,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
       map = new google.maps.Map(document.getElementById("map_canvas"),  myOptions);                         
    }        
</script>
</head>

<body>
    <div id="map_container" title="Location Map">    
        <div id="map_canvas" style="width:100%;height:100%;"></div>
    </div>
    
    <div id="controls">
        <input type="button" name="showMap" value="Show Map" id="showMap" />
    </div>    
</body>
</html>

The secret is the event handlers for the open and resize actions on the dialog.

            resizeStop: function(event, ui) {google.maps.event.trigger(map, 'resize')  },
            open: function(event, ui) {google.maps.event.trigger(map, 'resize'); } 

Those guys right there make the magic happen. Just make sure to include the resize functions in the event handlers when you register the dialog and you are all good. They just say when the dialog is opened or resize, have the google map recheck the size of it’s parent and scale accordingly. That resolves the issue in a snap. The rest of the code just makes a nice little sample app you can play with. Anyway, I really hope this helps someone cause I spent an afternoon beating my head against the wall on this one, and even migrated my whole app from google maps v2 to v3 hoping that would fix it, when it didn’t >.<

43 responses

  1. daniele

    You are my god! :D

    July 28, 2011 at 6:16 pm

    • Hey, I’m really glad I could help! Thanks so much for the comment. It made my day :)

      July 29, 2011 at 2:49 am

    • Joe

      Well – I’m sorry to say that my one God is the all mighty creator of the heavens and the known universe. But I must say good man – you wrote a very useful and awesome post – so thank you kindly.

      July 2, 2012 at 11:48 am

    • Anonymous

      I’m agree, super cool !

      June 13, 2014 at 11:51 am

  2. Very usefull!!! Thanks!

    September 9, 2011 at 9:12 pm

  3. User

    Great! had the exact issue and this saved me probably half a day!

    February 6, 2012 at 1:39 pm

  4. Carl

    I’ve been pulling my hair out over this for 2 days. well done for working out a solution. this is genius!

    February 24, 2012 at 1:37 am

  5. Thank you a lot! It took me 3 hours of trying different things before i have found you post.

    February 28, 2012 at 1:50 pm

  6. Carla

    Thank for your post. The most elegant solution I have found:
    While your example works like a chime in my case I have problems loading the map when I use Firefox 3.6. I get the map only partially loaded in the right top corner and the error is:
    Error : a is undefined
    File Source : http://maps.gstatic.com/intl/fr_ALL/mapfiles/api-3/8/1/main.js
    Line : 19

    Do you have any ideas why this happens?

    March 2, 2012 at 2:41 pm

  7. Gill

    Thank you for posting the whole code, I’ve been going crazy trying to insert the snippets found elsewhere to the right places. You saved me! :)

    March 23, 2012 at 1:18 pm

  8. Chris

    You saved me a lot of time. Thanks! Excelent demo as well.

    April 5, 2012 at 3:06 am

  9. futurekoder

    many thanks! :)

    April 26, 2012 at 10:58 pm

  10. fallanic

    thanks, helped a lot!

    May 18, 2012 at 11:05 pm

  11. Femi

    Thank a lot, you just saved me from 2days persistent headache

    June 22, 2012 at 3:19 pm

  12. Manoel Marcos (Brasil)

    fantastic

    June 27, 2012 at 5:50 pm

  13. Martin

    Thanks man!!!

    June 28, 2012 at 10:46 am

  14. Thanks dear
    its working for me

    August 15, 2012 at 4:50 am

  15. GOdeStAlbin

    What about calling initialize(); in the open function of the dialog instead of in the $(document).ready(function() ?
    This is what I have and it works for me.

    October 24, 2012 at 3:26 am

    • That’s a pretty good idea as well. In this case it would probably work, but I figure initializing the map before the user needs it may speed up performance. Then just resizing it as needed. I have no idea if that actually makes a difference or not, just my thought process.

      November 28, 2012 at 6:16 pm

    • aizazbarki

      I wants to pass the latitude, longitude dynamically to the popup to give me the popup with that location to be pointed. rest every thing is fine.

      I would be really thankful if you help me in this regard
      Best wishes

      January 18, 2013 at 1:29 pm

      • newBiee

        I wants to pass the lat and long dynamically.
        or how can i pass let and long with this button?
        $(“input:submit,input:button, a, button”, “#controls”).button();

        Can you tell me how did you fix it? Thanks!

        August 14, 2013 at 4:13 pm

      • I know I am way late on this, but I just wrote it up for someone else. If you are still looking for a way to do this, check out

        http://pastebin.com/JWnuc84u

        August 14, 2013 at 10:05 pm

  16. Darren

    I have been looking for this for ages!! Awesome man!

    October 26, 2012 at 7:13 am

    • Happy to be of service :)

      October 31, 2012 at 9:18 pm

  17. Goatlike

    Hey just wondering if I could replace the 1.6.2-jquery.min.js file with latest version of jquery js? Cuz after replacing the file, the map stop loading halfway and also the window is not at the center of screen..

    November 1, 2012 at 4:14 am

    • Hm, make sure you use the newest jQuery UI js and css sheets as well. It should work fine.

      November 1, 2012 at 4:50 am

  18. Goatlike

    I changed all the jquery js & css to the same version and it works now, thanks man~

    November 4, 2012 at 3:28 pm

  19. Stas

    BIG THANKS! Заебался искать решение проблемы, товарищ спас! :)

    November 28, 2012 at 6:12 pm

  20. Many many thanks you , it works for me. Now I can move on ……

    December 22, 2012 at 12:15 am

  21. Christoph

    Thanks !

    January 9, 2013 at 9:55 am

  22. aizazbarki

    Thank you very much for so nice piece of code,

    Best of Luck

    January 18, 2013 at 12:49 pm

  23. Anonymous

    Had similar problem with google charts.

    May 14, 2013 at 3:47 pm

  24. thank you
    you help me alot :)

    May 18, 2013 at 12:12 am

  25. Anonymous

    I knew someone already encounter this problem. Thanks for the help….

    June 12, 2013 at 1:15 pm

  26. Thank you very very very much !!!

    July 1, 2013 at 2:19 pm

  27. Ernest

    man, you are the best. thanks

    July 8, 2013 at 2:18 pm

  28. Anonymous

    HOLY CRAP THANK YOU!!!!!!!!!! You literally just saved me 17 minutes before code freeze.

    August 7, 2013 at 5:43 pm

  29. newBiee

    Thanks for this article.

    I want to pass the latitude and longitude dynamically.
    or how can i pass latitude and longitude with showMap button?

    Any help would be appreciated? Thanks!

    August 14, 2013 at 6:58 pm

    • This sample code should do it for ya. I just added some form fields, bound their data to the submit button and rigged the map to draw the point based on the data it gets passed in.

      http://pastebin.com/JWnuc84u

      August 14, 2013 at 10:03 pm

  30. PJ

    Beer for you, good job!

    October 1, 2013 at 4:24 pm

  31. Tony

    Perfect! Just what I needed without spending too many hours on trial and error.

    October 13, 2013 at 8:35 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 594 other followers