Using Google Maps JavaScript API v3 with jQuery Mobile

Written by on April 8, 2015

Using Google Maps JavaScript API v3 with jQuery Mobile

Embedded working example

jQuery Mobile Solution

Example

<!DOCTYPE html>
<html>
<head>
    <title>jQM Complex Demo</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1"/>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" /> 
	<style>
		#content {
			padding: 0;
			position : absolute !important; 
			top : 40px !important;  
			right : 0; 
			bottom : 40px !important;  
			left : 0 !important;  		
		}
	</style>  
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>    
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>  	
    <script>
		$(document).on('pageshow', '#index', function (e, data) {

			setTimeout(function () {
				// This is the minimum zoom level that we'll allow
				var minZoomLevel = 12;

				var map = new google.maps.Map(document.getElementById('map_canvas'), {
					zoom: minZoomLevel,
					center: new google.maps.LatLng(38.50, -90.50),
					mapTypeId: google.maps.MapTypeId.ROADMAP
				});
			}, 100);
		});	
	</script>	
</head>
<body>
    <div data-role="page" id="index">
        <div data-theme="a" data-role="header">
            <h3>
                First Page
            </h3>
        </div>

        <div data-role="content" id="content">
            <div id="map_canvas" style="height:100%"></div>
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">
            <h3>
                First Page
            </h3>
        </div>
    </div>
</body>
</html> 

The Second jQuery Mobile solution

Demo

Unfortunately, a first solution will not be useful every time. Sometimes we will not know our page dimensions or what will be available space for our content div, this is where jQuery comes to help.

Here’s a nifty function that will calculate available content height. It can be then used to dynamically set new content height. That combined with window resize event will give you best responsiveness.

Embedded working example

jQuery Mobile Solution 2

Example

<!DOCTYPE html>
<html>
<head>
    <title>jQM Complex Demo</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1"/>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" /> 
	<style>
		#content {
			padding: 0 !important;
		}
	</style>  
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>    
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>  	
    <script>
		$(document).on('pageshow', '#index',function(e,data){   
		
			$('#content').height(getRealContentHeight());
			
		   // This is the minimum zoom level that we'll allow
		   var minZoomLevel = 12;

		   var map = new google.maps.Map(document.getElementById('map_canvas'), {
			  zoom: minZoomLevel,
			  center: new google.maps.LatLng(38.50, -90.50),
			  mapTypeId: google.maps.MapTypeId.ROADMAP
		   });			
		});

		function getRealContentHeight() {
			var header = $.mobile.activePage.find("div[data-role='header']:visible");
			var footer = $.mobile.activePage.find("div[data-role='footer']:visible");
			var content = $.mobile.activePage.find("div[data-role='content']:visible:visible");
			var viewport_height = $(window).height();

			var content_height = viewport_height - header.outerHeight() - footer.outerHeight();
			if((content.outerHeight() - header.outerHeight() - footer.outerHeight()) <= viewport_height) {
				content_height -= (content.outerHeight() - content.height());
			} 
			return content_height;
		}
	</script> 
</head>
<body>
    <div data-role="page" id="index">
        <div data-theme="a" data-role="header">
            <h3>
                First Page
            </h3>
        </div>

        <div data-role="content" id="content">
            <div id="map_canvas" style="height:100%"></div>
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">
            <h3>
                First Page
            </h3>
        </div>
    </div>
</body>
</html>   

Who Am I?

Between working as a senior Java developer in one of the largest insurance companies in the world and traveling, in my free time, I work as a professional mobile development adviser. I'm also a major jQuery Mobile supporter back at StackOverflow and a forum moderator at the official Ionic Framework forum.



Categories

45 thoughts on “Using Google Maps JavaScript API v3 with jQuery Mobile”

  1. Thanks for all your tutorials! They help so much.

    I have a question: is it wrong to use Google maps in a multi-HTML template? I have a dynamic page with a map that produces markers. Since JQM loads pages in the DOM of the initial page, it’s possible to have several maps within the DOM.

    • You can have as much pages containing maps as you want. There only one problem I can think off, Google Maps API V3 cant successfully preinitialize map in non-active pages. So when other map pages are shown you will always see a brief loading flash. Also take care that div’s containing your maps have unique id’s.

      If you also don’t like map preinitialization problem you can take a look at other map frameworks like Leaflet. It works just fine with jQuery Mobile and unlike GMap API V3 this one don’t suffer from page height problem. More information can be found here: http://www.gajotres.net/jquery-mobile-and-leaflet-integration/

  2. I have a very similar problem to the one that you discuss, but unfortunately your solution doesn’t work for me. I’m hoping that you might know how to solve my issue.

    I have a jquery mobile site that has two pages. The map needs to reside on the second page, but I want to initialize it (and then get its bounds) it upon pageinit of the index page.

    It should come as no surprise to you that the google map on the second page is sized incorrectly. Here is a fiddle showing the problem: http://jsfiddle.net/EPVe6/. I’ve tried using css to set the size of the map_canvas, but I haven’t had any luck.

    What do you think? Is it possible??

    • Unfortunately I don’t know a solution for this problem. It can be fixed partially, if you initialize map in a first page you will need to trigger map resize during the second page pageshow event. This is the closest solution that I know.

      Here’s a working example: http://jsfiddle.net/Gajotres/TyKCR/

      In this example map can be used even before second page is shown. But there’s one downside, when second page is shown map will resize to cover available space. This alone is jQuery Mobile problem
      and only way to solve it requires second page to be enhanced at the app load and currently it can’t be done. I had an idea to try to do this manually (manually enhance second page content and add classes) but I never found time to do that.

      I hope this solves your problem.

  3. I really appreciate you taking a look at this problem. Unfortunately, resizing on the second page load doesn’t solve my problem because I need the accurate map bounds before the second page load. My solution (which is specific to my application) is to change the flow so that on the index page I geolocate the user’s location manually establish a set range from that center-point. When the user navigates to the map page I’ll set the map bounds to include all of the range. Not the best approach from a ux perspective, but it will get the job done.

    Thanks again!

    • Thanks for your replay, can you tell me more about your solution? Maybe I can help you make a pure CSS solution. On the other hand jQuery solution is also not bad, I just don’t like using javascript if there’s a CSS solution.

  4. Thanks for article!

    It really works in jsFiddle, but it doesn’t if you copy the code to local html-file. Could you please check that and attach html-file here?
    Thanks.

  5. I have used the above solution but the problem i am facing is page is showing as it is loading after that no response. If include the below script the page doesn’t load else the back page appears. If anyone has faced this problem pls let me know:

    $(document).on(‘pageinit’, ‘#index’,function(e,data){
    var minZoomLevel = 12;

    var map = new google.maps.Map(document.getElementById(‘map_canvas’), {
    zoom: minZoomLevel,
    center: new google.maps.LatLng(38.50, -90.50),
    mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    });

  6. I am receiving following error any help pls.

    10-11 06:55:29.580: E/Web Console(2048): Uncaught ReferenceError: google is not defined at file:///android_asset/www/RegisteredUsers.htm:3

  7. Hi Guys,

    Good to come in to this page, I am having a very seriously issue with Gmap, I have 3 pages I want to show my map. only the first page of my map will load fully is I navigate back and click the next page my map size will be weird,..showing half top left. I am using Jquery mobile and phonegap… I am not sure if this was the same case with anyone here, I really need a help to fix this.

    I will appreciate any help.

    Thanks

  8. Hi, a diffrent question, slightly off the current subject.
    Have you ever worked with a KML file? Like importing a KML file over Google Maps to define custom boundaries (polygons). I need some help with colour coding these custom regions dynamically, based on values from a database.

    Any help would be much appreciated.

  9. Hi, i have a different question, slightly off subject.
    Have you ever worked with KML files? Like importing a KML file over Google Maps to display custom boundaries(polygons). I need some help with colour these custom region territories based on asoociated data from a database.

    Any help would be much appreciated.
    Thanks

    • I used them long time ago just to see how everything works, nothing else. Do you have some specific working example I can look? Even better if you can create it inside jsFiddle environment and I will solve your problem.

  10. Hello Dragan,

    It seems your “Map example” download button is broken.

    So far I failed putting a gmap page up and running. All my test work great in chrome / FF but once compiled by PhoneGap, the map div doesn’t show up. A working example for jQuery Mobile & PhoneGap would absolutely rock !

    Thanks
    Greg

    • Are you sure? It works for me, at least when using desktop Firefox or Chrome. What browser are you using? Also if you can wait until tomorrow I can create you a working Phonegap project. Unfortunately I can only create you Android example.

  11. Hi, am using this with phonegap app. It works fine for android versions below 4.4 , but on android 4.4.2 and 4.4.2 it getCurrentPosition method doesnt work. Fails with [Object PositionError]. Any solution please…

  12. hi how to make a phonegap jquery mobile app truely responsive for all devices. Is media query the only solution?? I have written media query for 3 different resolutions 480×720, 720×1280, 1080×1920. Even the textsize imagesize given in pixels varies from one resolution model to another. There are different phones with different resolutions in market. I dont think writing media query for every single resolutions range is a right solution and its impossible too to get all those models for testing. Please help me get out of this problem. Thanx in advance

  13. Thank you for your constant great work. Especially on behalf of all of us part-timers, this is an invaluable resource.

  14. Why don’t you declare Google maps object as a global variable? This way it will be available to all pages.

    Of course, this solution will not work if you’re accessing other pages (holding maps) with rel=”external”.

    • Hi Dragan, thanks for your reply!
      I have already done this and then I had another issue, the map did not shown either in phonegap neither in browser, without any error in log file. I changed the map’s div width and height from percentages to pixel numbers and the map worked!
      Unfortunately now shows another issue: I try to load Google Maps API via Google AJAX API loader: google.load(“maps”, “3.8”, {“callback”: MyMapFunc, other_params: “sensor=true&language=en”}); and a TypeError occurs at this line of code: “undefined is not a function” and the app stucks there, although I have declared google map api js reference in index.html. Do you have something in mind with this issue please?
      Regards,
      George

  15. Hi,
    I’m new to jquery mobile so please bear with me. I’ve copied the above code and it works perfectly on my laptop but when I load it onto server it momentarily shows then the page goes blank and I get this message on Chrome and Firefox.

    Oops! Something went wrong.
    This page didn’t load Google Maps correctly. See the JavaScript console for technical details.

    Any help will be gratefully received.

    Ruth

Leave a Reply