Software Archive
Read-only legacy content

Google Maps Incomplete refresh

Keith_G_
Beginner
761 Views

I made some sample apps with simple google maps in the XDK with and without app framework that worked, but now that i'm working on the real thing the map is not loading properly, either in a browser or in the emulator.  Is it possible that loading the map on a page different than the main page is the problem?  I found this document:  https://software.intel.com/sites/default/files/managed/2c/2a/fast-track-to-intel-xdk-new-unit06-geo.pdf that describes the problem on the bottom of page 6 - 8, "In some user-cases .. your map may only partially instantiate"  I tried to use the code suggested:  " 
setTimeout("$('#map').gmap('refresh')",500);", and found that I needed to include a javascript file, "ui/jquery.ui.map.full.min.js", which I found here: http://code.google.com/p/jquery-ui-map/source/checkout.  I no longer get any errors, but the map still doesn't instantiate.  I'll include the code below, but the question is:  How do I get my map to work?  Thanks.(I left as much as possible in the code, warts and all, so you can see all the crazy things I've tried.)

		<script src="intelxdk.js"></script>
		<script type="text/javascript">
			var _map = null;
			    var myLatLng;
			    var currentLatitude = "";
			    var currentLongitude = "";
			    var options = {
			        timeout: 10000,
			        maximumAge: 11000,
			        enableHighAccuracy: true
			    };
			/* Intel native bridge is available */
			var onDeviceReady=function(){
                if (intel.xdk.geolocation !== null) {
                intel.xdk.geolocation.watchPosition(suc, fail, options);
                } else {
//					document.getElementById("geostat").innerHTML="Intel nav not ready";
					initialize();
                }
				//hide splash screen
				intel.xdk.device.hideSplashScreen();
			};
            function ready() {
			    if (navigator.geolocation) {
//					document.getElementById("geostat").innerHTML="In ready";
			          navigator.geolocation.getCurrentPosition(showPosition);
			    } else {
//					document.getElementById("geostat").innerHTML="Browser nav not ready";
			    }
			};
            function showPosition(position) {
			    currentLatitude = position.coords.latitude;
			    currentLongitude = position.coords.longitude;
//				document.getElementById("geostat").innerHTML="Browser nav ready";
			    initialize();
			};

		if(typeof intel === 'undefined') {
		    document.addEventListener( "DOMContentLoaded", ready, false );
		} else {
			document.addEventListener("intel.xdk.device.ready",onDeviceReady,false);
		}
			    //Success callback
			    var suc = function(p) {
			        console.log("geolocation success", 4);
//					document.getElementById("geostat").innerHTML="Intel nav success";
			        //Draws the map initially
			        if (_map === null) {
			            currentLatitude = p.coords.latitude;
			            currentLongitude = p.coords.longitude;
			            initialize();
			        } else {
			            myLatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
			        }
			    };
			    
			    var fail = function() {
			        console.log("Geolocation failed. \nPlease enable GPS in Settings.", 1);
//			        document.getElementById("geostat").innerHTML="Intel nav fail";

			    };
			function donateFn() {
//				intel.xdk.device.launchExternal("http://www.volunteerlogin.org/GLBTNearMe/donate.html");
				window.open('http://www.volunteerlogin.org/GLBTNearMe/donate.html');
			};
			function mapformredirect() {
				window.location.href="index.html#mapmainpage";
			}

			function getinitparams() {
				var zip = document.getElementById('distform').elements["zipcode"].value;
				var params = "" ;
			    if ( (zip == null || zip == "") &&
					 (currentLatitude == "") ) {
			        alert("You must enter a zip code or turn on navigation (GPS).");
				} else {
					var miles = document.getElementById('distform').elements["milesdist"].value;
					if ( currentLatitude != "" ) 
						params = "latitude=" + currentLatitude + "&longitude=" + currentLongitude;
					else
						params = "zip=" + zip;
					if ((miles.length > 0) && (miles > 0))
						params+= "&miles=" + miles;
				}
				return params;
			};

			function listformFn() {
				var params = getinitparams();
				var cat = document.getElementById('distform').elements["category"].value;
				params += "&category=" + encodeURI(cat);
				listpagefunc(params,cat);
			};
			function nationalFn() {
				var params = "national=Yes";
				listpagefunc(params,"National");
			};
			function listpagefunc(params,natnl) {
			    var xmlhttp;
				try {
				    xmlhttp=new XMLHttpRequest();
				} catch(e) {
					xmlhttp = false;
				}
				if (xmlhttp) {
				    xmlhttp.onreadystatechange=function()
				    {
				      if (xmlhttp.readyState==4 && xmlhttp.status==200)
				      {
//							alert(xmlhttp.responseText);
							var rList = JSON.parse(xmlhttp.responseText);
    						var numberList = 	document.getElementById("natlisting");
						    var i;
							var namedist = '<p  class="nlist">' + natnl + '</p>';
						    for(i = 0; i<rList.length; i++) {
                    //create new li element
//					            var newNumberListItem = document.createElement("li");
                    //create new text node
								namedist += "<br>" + rList.Name;
								var dist = rList.Distance;
								if (dist > 0)
									namedist += ' - ' + dist + ' Miles';
								var address1 = rList.Address1;
								if (address1.length > 0)
									namedist += "<br>" + address1;
								var address2 = rList.Address2;
								if (address2.length > 0)
									namedist += "<br>" + address2;
								var city = rList.City;
								var state = rList.State;
								var zip  = rList.Zip;
								if (city.length > 0)
									namedist += "<br>" + city + ', ' + state + ' ' + zip;
								var phone = rList.Phone;
								if (phone.length > 0)
									namedist += "<br>Phone: " + phone;
								var hotline = rList.Hotline;
								if (hotline.length > 0) {
									var c = hotline.substr(0,1);
									if (c >= '0' && c <= '9') {
										namedist += "<br>Hotline: " + hotline;
									}
								}
								var internet = rList.Internet;
								if (internet.length > 0)
									namedist += "<br>Email: " + internet;
								var web = rList.Web;
								if (web.length > 0)
									namedist += '<br>Web: <a href="' + web + '">' + web + '</a>';
/*								var subcat = rList.sub-cat;
								if (subcat.length > 0)
									namedist += "<br>Sub-category: " + subcat; // can't use sub-cat */
								namedist += "<br>";
						    }
							numberList.innerHTML=namedist;

							activate_subpage("#natsp");
					  }
					}
				}
				xmlhttp.open("GET","https://www.volunteerlogin.org/GLBTNearMe/AppResults.php" + '?' + params, true);
			    xmlhttp.send(null);
			};
		</script>
		<!--   
   You may substitute jQuery for the App Framework selector library.
   See http://app-framework-software.intel.com/documentation.php#afui/afui_jquery
  -->
		<script type="application/javascript" src="app_framework/2.1/appframework.js"></script>
		<script type="application/javascript" src="app_framework/2.1/appframework.ui.js" data-ver="1"></script>
		<script src="cordova.js"></script>
		<script src="xhr.js"></script>
		<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

		<script type="application/javascript" src="js/jquery.min.js"></script>
		<script type="text/javascript" src="ui/min/jquery.ui.map.full.min.js">
		</script>
		<script type="application/javascript" src="js/index_user_scripts.js"></script>
		<script type="application/javascript" src="js/af_subpage.js"></script>
		<script type="text/javascript">
			/* Intel native bridge is available */
			af.feat.nativeTouchScroll = true;
			af.ui.ready(
			    function(){
			    //do something
//					alert("ui ready");
/*					if(typeof intel === 'undefined') {
					    ready();
					} else {
						onDeviceReady();
					}*/
				}
			);
		</script>
		<style>
			#map_canvas {
			        width:  100%;
			        height: 380px;
			    }
		</style>
		<script>
			function initialize() {
			        var mapCanvas = document.getElementById('map_canvas');
					var latlng = new google.maps.LatLng(currentLatitude, currentLongitude);
			        var mapOptions = {
			            center: latlng,
				        zoomControl: true,
			/*	        zoomControlOptions: {
				            style: google.maps.ZoomControlStyle.SMALL,
			//	            position: google.maps.ControlPosition.LEFT_TOP
				        },*/
			            zoom: 12,
			            mapTypeId: google.maps.MapTypeId.ROADMAP
			        }
			        _map = new google.maps.Map(mapCanvas, mapOptions);
					setTimeout("$('#map_canvas').gmap('refresh')",500);
			/*		var marker = new google.maps.Marker({
						position: latlng,
						map: _map,
						title: 'Current Position',
						zIndex: 1000
					});
					marker.setMap(_map);*/
			    };
		</script>

...

            <div class="upage panel" id="mapmainpage" data-header="af-header-1" data-footer="af-footer-1">
                <div class="upage-outer">
                    <header class="container-group inner-element uib_w_1 header-img" data-uib="app_framework/header" data-ver="1" id="af-header-1">
                        <img class="displaycenter" src="images/glbtnearmelogo.png">
                    </header>
                    <div id="mapmainpagesub" class="upage-content ">

                        <div id="buttonback" style="width:100%;    margin-left: auto;
    margin-right: auto;
"><a class="buttoncenter widget uib_w_4 orangeButton" data-uib="app_framework/button" data-ver="1" href="#mainpage" data-transition="fade">Back</a>
                        </div>
                        <!-- buttonback -->
                        <br>
                        <div id="map_canvas" data-appbuilder-object="page" style=""></div>
                    </div>
                    <!-- mapmainpagesub" upage-content -->
                    <footer class="inner-element uib_w_2 footer-txt" data-uib="app_framework/footer" data-ver="1" id="af-footer-1">
;/footer>

                </div>
                <!-- /upage-outer -->
            </div>
            <!-- /upage -->

 

0 Kudos
5 Replies
Elroy_A_Intel
Employee
761 Views

I recommend that you add the function that initializes the map to a DOM event. 

Don't forget to include your API_KEY.

For example,

<!DOCTYPE html><!--HTML5 doctype-->
<html>
<head>
    <title>Your New Application</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0" />
    <style type="text/css">
        /* Prevent copy paste for all elements except text fields */
        *  { -webkit-user-select:none; -webkit-tap-highlight-color:rgba(255, 255, 255, 0); }
        input, textarea  { -webkit-user-select:text; }
        body { background-color:white; color:black }
    </style>
    <style type="text/css">
        html { height: 100% }
        body { height: 100%; margin: 0; padding: 0 }
        #buttons-div { height: 5% }
        #map-canvas { height: 95% }
    </style>
    <script src='intelxdk.js'></script>
    <script type="text/javascript">
        /* Intel native bridge is available */
        var onDeviceReady=function(){
        //hide splash screen
        intel.xdk.device.hideSplashScreen();
        };
        document.addEventListener("intel.xdk.device.ready",onDeviceReady,false);
    </script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY_REQUIRED"></script>
    

<script type="text/javascript">
        var map=null;

        function initialize() {
            var mapOptions = {
              center: new google.maps.LatLng(-34.397, 150.644),
              zoom: 8
            };
            map = new google.maps.Map(document.getElementById("map-canvas"),
                mapOptions);
        }
        google.maps.event.addDomListener(window, 'load', initialize);

        function loadpos(){
            map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
        }
    </script>

</head>
<body>
    <!-- content goes here-->
    <div id="buttons-div">
        <button onclick="loadpos()">Load Map over Palo Alto, CA</button>
    </div>
    <div id="map-canvas"/>
</body>
</html>

This code has been successfully tested on Android, iOS and Windows Phone devices.

For more information on using the Google Maps Javascript API, go to .https://developers.google.com/maps/documentation/javascript/tutorial

0 Kudos
Keith_G_
Beginner
761 Views

Hi Elroy:

Thanks for your reply.  Unfortunately, adding the DOM event did nothing.  I don't have an API key, as I 'm using the basic model.  The problem is not that the map doesn't load (as mentioned in my post), but that it doesn't load completely (see the pdf document referenced). 

I just ran an experiment to test my theory in my post - I started with Intel's app_framework example and added a sub-page and another page.  When the map div is on the main page, it works beautifully.  When it is on a sub-page or another page, it fails to load at all.  I'm thinking there is some kind of interference going on here with either app-framework or other pages.

Since I can't have the map on my main page, the question is how do I fix this problem?  Should I abandon App-Framework?  Will that help?  Or is there a better solution?

Thanks!

Keith

0 Kudos
Keith_G_
Beginner
761 Views

Hi Elroy:

Sorry, but another update.  I checked out a project I had without app-framework, and when the map is on the main page, it loads fine.  When it is on another page, it fails to load completely (same behavior as mentioned before.)

The problem is that the google map does not load completely on any page other than the main page.  I bet there is a nice solution to get this to work, can you please help me? 

Thanks!

Keith

0 Kudos
Grant_E_
Beginner
761 Views

Hi Keith

I have had the same problem recently and would like to offer the solution I found to the problem. I think you would have noticed that this is not only an xdk problem but a problem which occurs in a number of situations when loading a google map onto a div that is initially hidden. There are solutions to this problem that can be found with a Google search, however I could not solve the problem using any of the found solutions in intel xdk.

My solution is as follows:

Instead of calling initialize() when the doc is ready, I call it after the call to change pages.

$.ui.loadContent("page_name",false,false,"slide"); 

initializeMap(lat,lng);

The $.ui.loadContent() method changes the current page so that the div is already visible when the gmap is initialized. The initializeMap() method is the equivalent to your initialize() method with the addition of parameters for the center of the map.

Hope this helps!

Regards
Grant

0 Kudos
J_W
Beginner
761 Views

Which browser do you use?  Is it IE? IE sucks and not friendly with Google's js code.   

0 Kudos
Reply