Javascript, Snippets

Display a location-aware google map on page load with jQuery mobile

The following snippet of code will display a google map with user’s default location on jQuery mobile page if location services is enabled. Otherwise, it will use predefined lat and long values to create the map. The code uses jQuery mobile pagecreate event.

A little info on jQuery mobile pagecreate event:

Triggered when the page has been created in the DOM (via ajax or other) but before all widgets have had an opportunity to enhance the contained markup. This event is most useful for user’s wishing to create their own custom widgets for child markup enhancement as the jquery mobile widgets do.

$( '#aboutPage' ).live( 'pagecreate',function(event){
( ":jqmData(role='sweet-plugin')" ).sweetPlugin();

And the snippets:


function initialize(lat,lng) {
	var latlng = new google.maps.LatLng(lat, lng);

	var myoptions = {
		zoom: 12,
		center: latlng,
		disableDefaultUI: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	var map = new google.maps.Map(document.getElementById("googlemap"),myoptions);
	var icon = new google.maps.MarkerImage('images/marker.png',
			new google.maps.Size(20, 20), // size
			new google.maps.Point(0, 0), // origin
			new google.maps.Point(20, 20) // anchor
	var mymarker = new google.maps.Marker({
		position: latlng,
		map: map,
		icon: icon
$('.page-map').live("pagecreate", function() {
        var lat = -33.887418, lng = 151.17403;
	if(navigator.geolocation) {
		}, function() { console.log('Error with getCurrentPosition'); });
	} else {
                // predefined location
		initialize(lat, lng);


<div data-role="page" class="page-map">

	<div data-role="header">
		<h1>Google Map</h1>
	</div><!-- /header -->

	<div data-role="content">	
		 <div id="googlemap"></div>
	</div><!-- /content -->
	<div data-role="footer">
		<h4>Footer content</h4>
	</div><!-- /footer -->
</div><!-- /page -->
Career Guide for Software Developers