Android geolocation application demo using PhoneGap, jQuery Mobile and Google Maps


This android geolocation application uses PhoneGap api for phone geo position and displays the phone position point on Google Maps. jQuery Mobile is used to display the page header, footer and content map. Page is resized to full height and width for any orientation or window size. Made with Eclipse and Android SDK. This demo also works on Chrome browser.

<!DOCTYPE html>
<html> 
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">
    <title>Map</title>
    
    <link rel="stylesheet" href="css/jquery.mobile-1.0.1.css" />
    
    <script type="text/javascript" src="js/jquery-1.6.4.js"></script>
    <script type="text/javascript" src="js/jquery.mobile-1.0.1.js"></script>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript" src="js/cordova-1.5.0.js"></script>
    
<script type="text/javascript">

var map;
var marker;
var infowindow;
var watchID;

$(document).ready(function(){
	document.addEventListener("deviceready", onDeviceReady, false);
	//for testing in Chrome browser uncomment
	//onDeviceReady();
});

//PhoneGap is ready function
function onDeviceReady() {
	$(window).unbind();
	$(window).bind('pageshow resize orientationchange', function(e){
		max_height();
	});
	max_height();
	google.load("maps", "3.8", {"callback": map, other_params: "sensor=true&language=en"});
}

function max_height(){
	var h = $('div[data-role="header"]').outerHeight(true);
	var f = $('div[data-role="footer"]').outerHeight(true);
	var w = $(window).height();
	var c = $('div[data-role="content"]');
	var c_h = c.height();
	var c_oh = c.outerHeight(true);
	var c_new = w - h - f - c_oh + c_h;
	var total = h + f + c_oh;
	if(c_h<c.get(0).scrollHeight){
		c.height(c.get(0).scrollHeight);
	}else{
		c.height(c_new);
	}
}
		
function map(){
    var latlng = new google.maps.LatLng(55.17, 23.76);
    var myOptions = {
      zoom: 6,
      center: latlng,
	  streetViewControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      zoomControl: true
    };
    map = new google.maps.Map(document.getElementById("map"), myOptions);
	
	google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
		//get geoposition once
		//navigator.geolocation.getCurrentPosition(geo_success, geo_error, { maximumAge: 5000, timeout: 5000, enableHighAccuracy: true });
		//watch for geoposition change
		watchID = navigator.geolocation.watchPosition(geo_success, geo_error, { maximumAge: 5000, timeout: 5000, enableHighAccuracy: true });   
	}); 
}

function geo_error(error){
	//comment
    alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}

function geo_success(position) {
	
	map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
	map.setZoom(15);

    var info = 
    ('Latitude: '         + position.coords.latitude          + '<br>' +
    'Longitude: '         + position.coords.longitude         + '<br>' +
    'Altitude: '          + position.coords.altitude          + '<br>' +
    'Accuracy: '          + position.coords.accuracy          + '<br>' +
    'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '<br>' +
    'Heading: '           + position.coords.heading           + '<br>' +
    'Speed: '             + position.coords.speed             + '<br>' +
    'Timestamp: '         + new Date(position.timestamp));

	var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
	if(!marker){
		//create marker
		marker = new google.maps.Marker({
			position: point,
			map: map
		});
	}else{
		//move marker to new position
		marker.setPosition(point);
	}
	if(!infowindow){
		infowindow = new google.maps.InfoWindow({
		    content: info
		});
	}else{
		infowindow.setContent(info);
	}
	google.maps.event.addListener(marker, 'click', function() {
	  infowindow.open(map,marker);
	}); 
}
</script>

</head> 
<body> 

<div data-role="page" id="index">
	<div data-role="header" data-theme="b"><h1>Map Header</h1></div>
	<div data-role="content" style="padding:0;">
		<div id="map" style="width:100%;height:100%;"></div>
	</div>
	<div data-role="footer" data-theme="b"><h4>Map Footer</h4></div>
</div>

</html>

Download Map android application Eclipse project source map.7z, project source with jquery mobile version 1.4.3 and multipage demo map3.7z.

Build Android Application from project source
First you will need Android SDK download and install from here developer.android.com/sdk/index.html.
If you install not ADT Bundle, the you need Eclipse IDE and ADT Plugin for Eclipse. For ADT Bundle just skip next downloads.
Download and install Eclipse IDE for Java EE Developers www.eclipse.org/downloads/
Download and install ADT Plugin for Eclipse developer.android.com/sdk/eclipse-adt.html.
Now you have powerful integrated environment in which you can build Android applications.

Import project files to Eclipse
Download map.7z file and extract files with 7-Zip archiver www.7-zip.org.
Start Eclipse.
Select File -> Import... -> General -> Existing Projects into Workspace.
Select root directory, browse for folder with extracted map.7z files.
Press Finish.

Fix Android project properties
From Eclipce project pane right-click on Map project and select "Android Tools -> Fix Project Properties". You can skip this step if there is no errors with project.

Create AVD
Start AVD (Android Virtual Device) Manager and create new android virtual device with platform version greater 2.2 and start device (or Eclipce will start it after building project)

Build application
From Eclipse project pane right-click on imported Map project and select Run As -> Android Application. After a few seconds, the project is being built and installed to your android virtual device. Also you can test application in Chrome browser just open map\assets\www\index.html file from localhost or other host because Chrome has a security restriction with disabled navigator for the file protocol.

AVD Geoposition
If you see error message, then you need to set geoposition. Android virtual device don't emulate gps so you need to set manually geoposition via telnet. Open windows command line (for windows start -> run.. -> cmd), connect to your device and fix geo position. The port number can be seen in the title area of android emulator.

telnet localhost 5554
geo fix 25.28 54.68

Installing APK Application on Android virtual device
Of course you can skip building and immediately install Map.apk file from bin folder. Then you will need Android SDK installed and start Android virtual device. Next start command line (for windows start -> run.. -> cmd) and install by command

C:\progra~1\Android\android-sdk\platform-tools\adb.exe install Z:\android\project\map\bin\Map.apk

change path for Map.apk where files are extracted.

More information
jQuery JavaScript library
jQuery Mobile HTML5-based user interface system for all popular mobile device platforms
Phonegap get started guide for Android
Google Maps API

This entry was posted in Programming and tagged , , , , .

69 Responses to Android geolocation application demo using PhoneGap, jQuery Mobile and Google Maps

  1. nabil

    Thanks for this great job but the application run just for the first time when running eclipse (for android) and after when e start it again we have the alert message code 3 Timed out

    • There is timeout set to 5000 ms in line 53, try to increase. Also you must set geo position for the Android emulator via telnet, because Android emulator don't emulate gps.

  2. Branislav

    Thanks so much! This is the first tutorial of Google Maps that actually worked on my device as soon as trying it out!

  3. vanitha s

    Thank you so much for your great work done here...
    I got result easily from this example.

  4. idan

    Hi , thanks for the gr8 example !

    How do you install map.7z ?

    • map.7z is 7-Zip archiver file, you can download archiver http://www.7-zip.org/ and extract files.

      • idan

        I know but I'm using the AVD , I dont know how to install apps on it .....

        Becuase this kind of app using virtual gps\wifi i've got alot of questions :
        first is about the installation of map.7z on AVD ,
        where to extract the files ?
        how to upload APK file to the AVD ?

        other q's about AVD :
        What are the features on the AVD I must turn on in order to allow it use GPS and location services?
        does it effect this app if that features turned off ? ?

        Thank you for answers ....

        • I just updated post with more info about Eclipse project Android application building and apk install.
          where to extract the files ?
          You can extract map.7z files anywhere, just remember where they are, so you can import project to Eclipse or just install Map.apk file.
          how to upload APK file to the AVD ?
          Install any apk file with adb.exe from Android SDK.
          What are the features on the AVD I must turn on in order to allow it use GPS and location services?
          No special features, gps is always on and just virtual. You need to set AVD geo position via telnet in order to get that position from AVD to application or you will not get position. Also application must have location permission settings in AndroidManifest.xml without it you will get error. More info http://developer.android.com/guide/topics/location/obtaining-user-location.html

  5. idan

    helped alot !
    thanks ,

    another question ,
    if I want to resend my location ,or update by move , does it possible ?

    • Yes, set new location again via telnet, use geo fix command with longitude and latitude in decimal degrees, and an optional altitude in meters. For example:

      geo fix -121.45356 46.51119 4392
      
      • idan

        hi ,

        I tried , nothing changed , only if I reopen the app its updated . 🙁

        • Yes, it's because navigator.geolocation.getCurrentPosition function get location only once, so to update the location continually I changed to navigator.geolocation.watchPosition function. Source code updated. Now start application and send geo fix command, probably error will be, click ok and location will be set. Location will be set for any gps change with geo fix. Tested with Android AVD 2.2 and 4.0.3. Thanks for idea to update location continually!

  6. idan

    Thank you for your explanation and fix.
    Last question , I hope 🙂 .

    Does it updates every period of time or by moving around it sense changes?
    How can you manipulate that?
    Again , thanks !

    Idan 🙂

    • Not every period of time but only when the position data changes (either by device movement or if more accurate geo information arrives), then a callback is called with that updated position information. This is done using the watchPosition() function.

  7. Artsmorgan

    Not works for me, open the app in the emulator calculates the height and then nothing, looks like not load the coordinates, i try send the coords via telnet and nothing use the DDMS and nothing, then appears the time out

    • Open app, send the coords via telnet, then click Ok on alert message, and marker will be placed. Or you can edit code and delete alert message see geo_error function, install and start new app, send the coords and marker should be placed for coords.

  8. AlexAndr

    Nice Job, but when I am coping the source code into my own html file only header and footer are shown but not the div "content". Where is the problem?

  9. Aitor

    I use the code but it run only on index.html, if I run in other page it doesn't work. Anyone know a solution?

    Thanks

    • Yes this code example for single page. For many pages you can load map api on device ready, and initialize map only when map tag is visible this mean map page shows. Also calculate max height only for visible elements (current visible page). Example code with two pages:

      <!DOCTYPE html>
      <html> 
      <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">
          <title>Map</title>
          
          <link rel="stylesheet" href="css/jquery.mobile-1.0.1.css" />
          
          <script type="text/javascript" src="js/jquery-1.6.4.js"></script>
          <script type="text/javascript" src="js/jquery.mobile-1.0.1.js"></script>
          <script type="text/javascript" src="http://www.google.com/jsapi"></script>
          <script type="text/javascript" src="js/cordova-1.5.0.js"></script>
          
      <script type="text/javascript">
      
      var map;
      var marker;
      var infowindow;
      var watchID;
      
      $(document).ready(function(){
      	document.addEventListener("deviceready", load_map, false);
      	//for testing in Chrome browser uncomment
      	//load_map();
      });
      
      $(document).bind("pageshow", function(){
          if($("#map:visible").length){
              show_map();
          }
      });
      
      function load_map(){
      	google.load("maps", "3.11", {"callback": onDeviceReady, other_params: "sensor=true&language=en"});
      }
      
      //PhoneGap is ready function
      function onDeviceReady() {
      	$(window).unbind();
      	$(window).bind('pageshow resize orientationchange', function(e){
      		max_height();
      	});
      	max_height();
      }
      
      function max_height(){
      	var h = $('div:visible[data-role="header"]').outerHeight(true);
      	var f = $('div:visible[data-role="footer"]').outerHeight(true);
      	var w = $(window).height();
      	var c = $('div:visible[data-role="content"]');
      	var c_h = c.height();
      	var c_oh = c.outerHeight(true);
      	var c_new = w - h - f - c_oh + c_h;
      	var total = h + f + c_oh;
      	
      	if(c_oh < c.get(0).scrollHeight){
      		c.height(c.get(0).scrollHeight);
      	}else{
      		c.height(c_new);
      	}
      }
      		
      function show_map(){
      	if(!map){
      	    var latlng = new google.maps.LatLng(55.17, 23.76);
      	    var myOptions = {
      			zoom: 6,
      			center: latlng,
      			streetViewControl: true,
      			mapTypeId: google.maps.MapTypeId.ROADMAP,
      			zoomControl: true
      	    };
      	    map = new google.maps.Map(document.getElementById("map"), myOptions);
      	    
      		google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
      			//watch for geoposition change
      			watchID = navigator.geolocation.watchPosition(geo_success, geo_error, { maximumAge: 5000, timeout: 5000, enableHighAccuracy: true });   
      		});
      		
      		$("#map_zoom_in").click(function(){
      			map.setZoom(map.getZoom() + 1);
      			return false;
      		});
      		
      		$("#map_zoom_out").click(function(){
      			map.setZoom(map.getZoom() - 1);
      			return false;
      		});
      		
      	} 
      }
      
      function geo_error(error){
      	//alert error for debug
          alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
      }
      
      function geo_success(position) {
      	
      	map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
      	map.setZoom(15);
      
          var info = 
          ('Latitude: '         + position.coords.latitude          + '<br>' +
          'Longitude: '         + position.coords.longitude         + '<br>' +
          'Altitude: '          + position.coords.altitude          + '<br>' +
          'Accuracy: '          + position.coords.accuracy          + '<br>' +
          'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '<br>' +
          'Heading: '           + position.coords.heading           + '<br>' +
          'Speed: '             + position.coords.speed             + '<br>' +
          'Timestamp: '         + new Date(position.timestamp));
      
      	var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      	if(!marker){
      		//create marker
      		marker = new google.maps.Marker({
      			position: point,
      			map: map
      		});
      	}else{
      		//move marker to new position
      		marker.setPosition(point);
      	}
      	if(!infowindow){
      		infowindow = new google.maps.InfoWindow({
      		    content: info
      		});
      	}else{
      		infowindow.setContent(info);
      	}
      	google.maps.event.addListener(marker, 'click', function() {
      	  infowindow.open(map,marker);
      	}); 
      }
      </script>
      
      </head> 
      <body> 
      
      <div data-role="page" id="index">
      	<div data-role="header" data-theme="b"><h1>Page Header</h1></div>
      	<div data-role="content">
      		<a href="#map_page" data-role="button" data-inline="true">Map</a>
      	</div>
      	<div data-role="footer" data-theme="b"><h4>Page Footer</h4></div>
      </div>
      
      <div data-role="page" id="map_page" data-rel="back">
      	<div data-role="header" data-theme="b">
      		<a href="#index" data-icon="arrow-l">Back</a>
      		<h1>Map Header</h1>
      	</div>
      	<div data-role="content" style="padding:0;">
      		<div id="map" style="width:100%;height:100%;"></div>
      	</div>
      	<div data-role="footer" data-theme="b">
      		<div data-role="controlgroup" data-type="horizontal">
      			<a id="map_zoom_in" href="#" data-role="button" data-icon="plus" data-iconpos="notext"></a>
      			<a id="map_zoom_out" href="#" data-role="button" data-icon="minus" data-iconpos="notext"></a>
      		</div>
      	</div>
      </div>
      
      </html>
      
  10. Shafique

    well the sample is a great one but I need help in how to add static markers on the map...

  11. mouradovitch

    Thanks for this great work
    i try to run the App in Chrom, but I always get an error message
    code:1 message: user denied geolocation .
    has someone an idea ?

    • Possible you browse by the file protocol, but Chrome has a security restriction for the file protocol. Just host file and browse from a server or localhost (in example http://localhost/index.html)

      • mouradovitch

        Thank u sir .. now it works ..
        I have another question
        when I test the app in chrome browser, it works correctly. but when I test it in the chrome emulator (ripple emulator), after the 10 seconds (timeout) I get automatically the position of the city of waterloo ..
        has someone an idea ?

        • It's because ripple emulator have own gps simulator with default geo location of Waterloo city. To change gps location open Geo location tab from left side and drag map to new location or change latitude and longitude. While change geo location data it's simulate gps and call navigator.geolocation.watchPosition function and update position on app map. Here is screenshot.

  12. Shivansh

    Nice Work!!!

    Thumbs up bro...

    Well done 🙂

    Thanks a lot.

    I love this post, it is very easy to understand and implement.

    much of my logics has been cleared.

    thanks again 🙂 🙂

    • Thanks, but now I use native java development with Android SDK and Google Maps Android API because it is faster then PhoneGap app 🙂

      • Shivansh

        i have 2 questions,

        1. After putting static marker on map, those static markers are not showing info window , what do i do to make every marker show info window even it is placed statically?

        2. map is refreshing after a particular interval and looses the current focus and loads the coordinates of user's location and i need that on a particular event like a button click.

        please help buddy

        • Add marker after map created, then add infowindow, then add marker click event to open infowindow:

          map = new google.maps.Map(document.getElementById("map"), myOptions);
          
          //create markers
          //first marker
          markers = new Array();
          markers[0] = new google.maps.Marker({
          	position: new google.maps.LatLng(54.6871, 25.2796),
          	map: map
          });
          //first marker infowindow content
          markers[0].infowindow = new google.maps.InfoWindow({
          	content: 'marker 1 InfoWindow content'
          });
          //first marker click event open infowindow
          google.maps.event.addListener(markers[0], 'click', function() {
          	markers[0].infowindow.open(map, markers[0]);
          });
          
          //second marker
          markers[1] = new google.maps.Marker({
          	position: new google.maps.LatLng(54.8984,23.9035),
          	map: map
          });
          //second marker infowindow content
          markers[1].infowindow = new google.maps.InfoWindow({
          	content: 'marker 2 InfoWindow content'
          });
          //second marker click event open infowindow
          google.maps.event.addListener(markers[1], 'click', function() {
          	markers[1].infowindow.open(map, markers[1]);
          });
          

          For button just add navigator.geolocation.getCurrentPosition for click event

          $("#show_my_location").click(function(){
          	watchID = navigator.geolocation.getCurrentPosition(geo_success, geo_error, { maximumAge: 5000, timeout: 5000, enableHighAccuracy: true });
          	return false;
          });
          

          Here is full code with 2 pages, map on second page with static markers and show location button on footer:

          <!DOCTYPE html>
          <html> 
          <head>
              <meta charset="utf-8">
              <meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1">
              <title>Map</title>
              
              <link rel="stylesheet" href="css/jquery.mobile-1.0.1.css" />
              
              <script type="text/javascript" src="js/jquery-1.6.4.js"></script>
              <script type="text/javascript" src="js/jquery.mobile-1.0.1.js"></script>
              <script type="text/javascript" src="http://www.google.com/jsapi"></script>
              <script type="text/javascript" src="js/cordova-1.5.0.js"></script>
              
          <script type="text/javascript">
          
          var map;
          var marker;
          var infowindow;
          var watchID;
          
          $(document).ready(function(){
          	document.addEventListener("deviceready", load_map, false);
          	//for testing in Chrome browser uncomment
          	//load_map();
          });
          
          $(document).bind("pageshow", function(){
              if($("#map:visible").length){
                  show_map();
              }
          });
          
          function load_map(){
          	google.load("maps", "3.11", {"callback": onDeviceReady, other_params: "sensor=true&language=en"});
          }
          
          //PhoneGap is ready function
          function onDeviceReady() {
          	$(window).unbind();
          	$(window).bind('pageshow resize orientationchange', function(e){
          		max_height();
          	});
          	max_height();
          }
          
          function max_height(){
          	var h = $('div:visible[data-role="header"]').outerHeight(true);
          	var f = $('div:visible[data-role="footer"]').outerHeight(true);
          	var w = $(window).height();
          	var c = $('div:visible[data-role="content"]');
          	var c_h = c.height();
          	var c_oh = c.outerHeight(true);
          	var c_new = w - h - f - c_oh + c_h;
          	var total = h + f + c_oh;
          	
          	if(c_oh < c.get(0).scrollHeight){
          		c.height(c.get(0).scrollHeight);
          	}else{
          		c.height(c_new);
          	}
          }
          		
          function show_map(){
          	if(!map){
          	    var latlng = new google.maps.LatLng(55.17, 23.76);
          	    var myOptions = {
          			zoom: 6,
          			center: latlng,
          			streetViewControl: true,
          			mapTypeId: google.maps.MapTypeId.ROADMAP,
          			zoomControl: true
          	    };
          	    map = new google.maps.Map(document.getElementById("map"), myOptions);
          		
          		//create markers
          		//first marker
          		markers = new Array();
          		markers[0] = new google.maps.Marker({
          			position: new google.maps.LatLng(54.6871, 25.2796),
          			map: map
          		});
          		//first marker infowindow content
          		markers[0].infowindow = new google.maps.InfoWindow({
          			content: 'marker 1 InfoWindow content'
          		});
          		//first marker click event open infowindow
          		google.maps.event.addListener(markers[0], 'click', function() {
          			markers[0].infowindow.open(map, markers[0]);
          		});
          		
          		//second marker
          		markers[1] = new google.maps.Marker({
          			position: new google.maps.LatLng(54.8984,23.9035),
          			map: map
          		});
          		//second marker infowindow content
          		markers[1].infowindow = new google.maps.InfoWindow({
          			content: 'marker 2 InfoWindow content'
          		});
          		//second marker click event open infowindow
          		google.maps.event.addListener(markers[1], 'click', function() {
          			markers[1].infowindow.open(map, markers[1]);
          		});
          		
          		$("#map_zoom_in").click(function(){
          			map.setZoom(map.getZoom() + 1);
          			return false;
          		});
          		
          		$("#map_zoom_out").click(function(){
          			map.setZoom(map.getZoom() - 1);
          			return false;
          		});
          		
          		$("#show_my_location").click(function(){
          			watchID = navigator.geolocation.getCurrentPosition(geo_success, geo_error, { maximumAge: 5000, timeout: 5000, enableHighAccuracy: true });
          			return false;
          		});
          		
          	} 
          }
          
          function geo_error(error){
          	//alert error for debug
              alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
          }
          
          function geo_success(position) {
          	
          	map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
          	map.setZoom(15);
          
              var info = 
              ('Latitude: '         + position.coords.latitude          + '<br>' +
              'Longitude: '         + position.coords.longitude         + '<br>' +
              'Altitude: '          + position.coords.altitude          + '<br>' +
              'Accuracy: '          + position.coords.accuracy          + '<br>' +
              'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '<br>' +
              'Heading: '           + position.coords.heading           + '<br>' +
              'Speed: '             + position.coords.speed             + '<br>' +
              'Timestamp: '         + new Date(position.timestamp));
          
          	var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
          	if(!marker){
          		//create marker
          		marker = new google.maps.Marker({
          			position: point,
          			map: map
          		});
          	}else{
          		//move marker to new position
          		marker.setPosition(point);
          	}
          	if(!infowindow){
          		infowindow = new google.maps.InfoWindow({
          		    content: info
          		});
          	}else{
          		infowindow.setContent(info);
          	}
          	google.maps.event.addListener(marker, 'click', function() {
          	  infowindow.open(map,marker);
          	}); 
          }
          </script>
          
          </head> 
          <body> 
          
          <div data-role="page" id="index">
          	<div data-role="header" data-theme="b"><h1>Page Header</h1></div>
          	<div data-role="content">
          		<a href="#map_page" data-role="button" data-inline="true">Map</a>
          	</div>
          	<div data-role="footer" data-theme="b"><h4>Page Footer</h4></div>
          </div>
          
          <div data-role="page" id="map_page" data-rel="back">
          	<div data-role="header" data-theme="b">
          		<a href="#index" data-icon="arrow-l">Back</a>
          		<h1>Map Header</h1>
          	</div>
          	<div data-role="content" style="padding:0;">
          		<div id="map" style="width:100%;height:100%;"></div>
          	</div>
          	<div data-role="footer" data-theme="b">
          		<div data-role="controlgroup" data-type="horizontal">
          			<a id="map_zoom_in" href="#" data-role="button" data-icon="plus">Zoom In</a>
          			<a id="map_zoom_out" href="#" data-role="button" data-icon="minus">Zoom Out</a>
          			<a id="show_my_location" href="#" data-role="button" data-icon="minus">Show my location</a>
          		</div>
          	</div>
          </div>
          
          </html>
          
          • Shivansh

            Thanks a lot,

            It helped so much.

            you are great 🙂

            thanks again 😉

          • Jack

            hi sir
            how to use the current position is automatically located and given a target destination address of the user (marker).

            • You can create static user markers just after map created:

              map = new google.maps.Map(document.getElementById("map"), myOptions);
              
              //create user markers
              markers = new Array();
              markers[0] = new google.maps.Marker({
              	position: new google.maps.LatLng(54.687156, 25.279651),
              	map: map
              });
              
              markers[1] = new google.maps.Marker({
              	position: new google.maps.LatLng(54.898496,23.903542),
              	map: map
              });
              

              More info https://developers.google.com/maps/documentation/javascript/examples/marker-simple

              So you will have position marker by variable marker and user markers by array markers.

  13. mouradovitch

    hi sir
    i will get the Bounds and i have added this 3 lines
    bounds = map.getBounds();
    ne = bounds.getNorthEast();
    sw = bounds.getSouthWest();
    but i get the Error "has no method getBounds".
    has someone an idea ?

    • mouradovitch

      I found the error, the problem was the position of the 3 lines 😉

  14. mouradovitch

    hello sir
    i have a question about the function max_height()
    what is the difference between:
    var c_h = c.height(); and
    var c_oh = c.outerHeight(true);
    and what means this if-Condition
    if(c_h<c.get(0).scrollHeight){
    c.height(c.get(0).scrollHeight);
    }else{
    c.height(c_new);
    }
    has someone an idea ?
    Thanks

    • var c_h = c.height(); it is content height without padding, border, margin.
      var c_oh = c.outerHeight(true); it is content height with padding, border, margin

      when content scroll view height large then content height,

      if(c_h<c.get(0).scrollHeight){

      then set content height same as scroll view

      c.height(c.get(0).scrollHeight);

      Else set content height to windows height without footer and header

      c.height(c_new);

      Simply when no scroll then stretch content to fill window.

  15. mouradovitch

    thank you sir ..
    I have another question about the option enableHighAccuracy and the Event tilesloaded
    are they required ? and why they are used ?
    thank you very much .

    • If enableHighAccuracy is true and if the device is able to provide a more accurate position, it will do so. You can try false, may get position faster and not accurate. tilesloaded event is fired when the visible map tiles have finished loading. So till map not loaded, there is nothig to do with map.

      • mouradovitch

        Thanks a lot, 🙂

  16. Pingback: Header + map + footer using 100% height | Technology & Programming

  17. Amoun

    Bravo !!Merci pour ce grand travail ! 🙂

  18. Jack

    how to display the tracking?

  19. yere

    how to add a marker through sqlite

  20. manolo

    Y si en lugar de usar eclipse usas dreamweaver....sabes algun buen tutorial para eclipse, gracias

  21. Reena kumari

    I downloade the appliction and try to run in my project But its not working. it give the error code: 3 timeout error. i increase the time but not able to get the output. plz help me..

    • Also must be enabled GPS on device. If using Android Virtual Device coordinates for GPS must be set, look for AVD Geoposition in post.

  22. Reena kumari

    Thank u.i got the output..

  23. Rahat

    Thanks sir for this great blog post..
    i downloaded you map project source code..it works fine..
    even i have run the index.html file on my firefox browser, at first it worked nice and it was showing my coordinates but after that whenever i am trying to run that code it is just showing the map, not my point and that pin..
    even when i am using this code on my project some time it works well and some time it doesn't.
    i have tried this both on actual device and browser..
    can you please help me...

    • Try to check for javascript errors in browser console (press F12 and click on Console tab).

      • Rahat

        one more thing....i did some changes and now its working fine on firefox browser...but then i build it as a android project and create apk file...i tried to run the apk file on my device..now map is showing but current location point is not showing on the mobile...

  24. Marcin

    Hello Aleksandras !

    Its really nice work that you make. It work nice but i have one big problem. If you have multiple pages and if you will turn on automatic back buttons, for example:

    The back button will not work not only on that page but even on all pages 🙁

    Please check that and answer if you can 🙂

    Best regards
    Marcin

    • Marcin

      The code to back button is data-add-back-btn="true"

      • Hi, yes seems there is problem with bind function. I just rewritten code with latest jquery mobile version 1.4.3 and auto back button working now with new code:

        function onDeviceReady() {
        	$(window).on("pagecontainershow", function( event, ui ) {
        		//init map when map page show
        		if($(":mobile-pagecontainer").pagecontainer("getActivePage").attr('id') == 'map_page'){
        			max_height();
        			show_map();
        		}
        	});
        	$(window).on("orientationchange resize", function( event, ui ) {
        		if($(":mobile-pagecontainer").pagecontainer("getActivePage").attr('id') == 'map_page'){
        			max_height();
        		}
        	});
        }
        

        Here is project source http://polyetilen.lt/en/files/2014/09/map3.7z

  25. Marcin

    I notice that there is some bug. If you have multilevel pages for example if you hit from main menu: Select City (first page) -> New York (second page) -> Hotels (this is the button to map page in New York page). Then the map zoom dont work ... Can you check that ? Is there some completle refresh Google Map on enter to the map page ?

  26. Marcin

    Or just try go to "map" page, zoom in, then go to "test" page and back to "map" page and the map dont work (zoom in, zoom out, refresh map), thats strange ...

    • I didn't found this bug in project map3.7z, after navigation over map->test->back->map then zoom buttons in page header are working normally. Try test you project in browser with opened console (F12 for chrome or firefox) and watch for javascript errors.

      • Marcin

        Unfornatelly i have this problem. I think the best solution will be separate the map page to map.html page. This should load the map after each visit on map page ? For now i have index.html and map.html but map not appear after click button from index.html ... 🙁

      • Marcin

        Please see the YouTube movie what i have on mind. The map just dont refresh after zoom in (project map3.7z). https://www.youtube.com/watch?v=LEY7ynr5e-4&feature=youtu.be

        • Seems when map hidden it resize to zero, so when show it again need to trigger resize event. I added this in show_map function:

          if(!map){
          	...
          }else{
          	var center = map.getCenter();
          	google.maps.event.trigger(map, "resize");
          	map.setCenter(center);
          }
          

          And updated map3.7z file.

          • Marcin

            For short while that fix is worked ! But after few minutes again the same. Even "Go back" button stop work 🙁 Can the map be refresh all the time after open map page ? Please see the actual movie:
            https://www.youtube.com/watch?v=Z3L7XB1waHM&feature=youtu.be

            • I tried on actual device working normally. For virtual device it is super slow. Back button is generating automatically by jQuery mobile, so I don't know why it's stop working. You can refresh map every time remove if(!map) in function show_map() and this will generate new map every time page open. Or simply just use for map Google Maps Embed API https://developers.google.com/maps/documentation/embed/guide generate iframe html code and insert to page.

  27. Marcin

    Even if I remove if(!map) the map dont refresh after zoom in in my android device. Go back button dont work properly. I really dont know why that is happen 🙁 Mayby is some way to clear DOM on enter map page ? I really confused and i will try embed solution.

  28. Marcin

    I make it working - just change script to cordova 1.9. API Level 8, Android 2.2.

  29. pfageo

    svp Monsieur pour moi ça marche pas il m'affiche seulement map sans coordonnées de localisation. j'ai essayé d'installet cordova de vouveau et de creer mon projet mais en vain. svp aidez moi c urgent

  30. vinod

    marker click event open infowindow not working...
    infowindow coming but going last one

    for(i=0;i<5; i++)
    {
    var contentString='';
    var mark = 'markers';
    var inf;

    var icon='lightblue'+(i+1)+'.gif';
    var lat=safeZoneList[i].zone_lat;
    var lng=safeZoneList[i].zone_lng;
    contentString =('Safezone Name : ' + safeZoneList[i].zone_name + '' +
    'Longitude : ' + lat + '' +
    'Altitude : ' + lng + '');

    //alert("contentString 2: : "+contentString);

    //alert(" count : "+(m+i));

    markers = (mark+(i+1)); //for increment

    markers = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    icon:'imgs/'+icon,
    map: map
    });

    markers.infowindow = new google.maps.InfoWindow({
    content: contentString
    });

    google.maps.event.addListener(markers, 'click', function() {
    markers.infowindow.open(map, markers);
    });

    }

    Info window coming for last one, not for all

    • Because you create infowindow on variable markers, so after loop ends variable markers have only last marker:

      for(i=0;i<5; i++){
      	...
      	//marker creation
      	markers = new google.maps.Marker...
      	...
      	//infowindow creation
      	markers.infowindow = new google.maps.InfoWindow...
      }
      

      You can create array of markers with own infowindow for each marker:

      var markers = new Array();
      for(i=0; i<5; i++){
      	...
      	//marker creation
      	markers[i] = new google.maps.Marker({
      		position: new google.maps.LatLng(lat, lng),
      		icon:'imgs/'+icon,
      		map: map
      	});
      
      	//infowindow creation
      	markers[i].infowindow = new google.maps.InfoWindow({
      		content: contentString
      	});
      
      	google.maps.event.addListener(markers[i], 'click', function() {
      		markers[i].infowindow.open(map, markers[i]);
      	});
      }
      

Leave a Reply to Aleksandras Cancel reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.