Google Chrome on_load not starting Google Map

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Google Chrome on_load not starting Google Map

Post by Eric! »

I've been playing around with a javascript tool that can run inside the blogger.com template that allows you to have a google map and plots points on it based on information parsed from the blog text.

An example of someone using it is:
http://svnakia.blogspot.com

It works fine in IE and FF (in spite of a few technical errors like a some script placed outside of the header tag). I can't however get it to work in Google Chrome. It seems to try to load the google map API before the DOM is finished (just a guess) and it fails immediately in initializing the Google Map. I've moved that example page on to a different server and played with different aspects of the page including using the newer Google Map v3 API, cleaning up the HTML and experimented on a few things but I still can't get Chrome to work (other browsers are fine).

Does anyone have any thoughts? I've not spent much time with javascript triggers so hopefully you'll see something basic in the page I posted.

Thanks in advance.
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: Google Chrome on_load not starting Google Map

Post by Eric! »

Ok, I tried to strip out the relevant bits from the page so you don't have to click on the link and see the source code. Some of the javascript is generated by blogger.com and some is merged via the template.

Remember it works fine in FF and IE, so there must be something subtle that I'm missing.

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <script type="text/javascript">(function() { var a=window;function c(b){this.t={};this.tick=function(d,i,e){e=e?e:(new Date).getTime();this.t[d]=[e,i]};this.tick("start",null,b)}var f=new c;a.jstiming={Timer:c,load:f};try{var g=null;if(a.chrome&&a.chrome.csi)g=Math.floor(a.chrome.csi().pageT);if(g==null)if(a.gtbExternal)g=a.gtbExternal.pageT();if(g==null)if(a.external)g=a.external.pageT;if(g)a.jstiming.pt=g}catch(h){};a.tickAboveFold=function(b){b=b;var d=0;if(b.offsetParent){do d+=b.offsetTop;while(b=b.offsetParent)}b=d;b<=750&&a.jstiming.load.tick("aft")};var j=false;function k(){if(!j){j=true;a.jstiming.load.tick("firstScrollTime")}}a.addEventListener?a.addEventListener("scroll",k,false):a.attachEvent("onscroll",k);
 })();</script>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<meta name="MSSmartTagsPreventParsing" content="true" /> 
<meta name="generator" content="Blogger" /> 

	<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAHY8IKWmLy4n3kfkceKSh9RSCkSE6GxV14ZcEg3hGZPHB5oQIgRSLoGTmvQHWZ1YFSeOCjXDh2DkGaw" type="text/javascript"></script> 

<script type="text/javascript">
<!--
// Adapted from map_blog PHP/JS script by Eric Baicy. This is essentially
// using his code, except that everything is handled in JS, so no PHP hosting
// is required. The following comments are from Eric's version of the file,
// edited only as required to match this version. Thanks Eric!
//
// August 2006 - V1.0 By Eric Baicy
// December 2008 - Scott Emmons - JS only version
// July 2010 - V2.0- Eric Baicy rewritten to work on blogger.com
//
//  Feel free to copy and use this script, but please
//  leave this header intact. 
//  
//  If you want to use this on a commercial site which charges
//  a fee to access this script, you must first obtain permision
//  to use it.  http://www.sailsarana.com
//  
//  This is Javascript that will parse a standard
//  blog file (or any test-type file) and search for the
//  tags: {GMST}stuff-in-between{GEND}
//  where the "stuff-in-between" contains a position
//  of latitude and longitude and some text comments.
//  For example:
//  	{GMST}latdeg|latmin|N[S]|londeg|lonmin|E[W]|Label|Description{GEND} 
//  	Where latdeg = is the degrees of latitude
// 		latmin = the decimal minutes.  If you're using
//		  degrees, minutes and seconds, just convert the seconds to minutes and add to minutes
// 		N[S] = the hemisphere, N = North, S = South. 
//  		londeg = is the degrees of longitude
//		longmin = the degrees of longitude in minutes
//  	E|W = the other hemisphere, E = East, W =West.
//      {GMST}23|16.265|N|106|27.255|W|Waiting out the hurricanes!|Marina Mazatlan{GEND}
//        would be 23d 16.265' North, 106d 27.255' West with a description and a label.
//
// ========================================
var gmarkers = [];
var map;
// arrays to hold copies of the markers and html used by the sidebar
// because the function closure trick doesnt work there
var htmls = [];     

// This function picks up the click and opens the corresponding info window
function myclick(i) 
{
gmarkers[i].openInfoWindowHtml(htmls[i]);
}
 
function start_map() 
{
	if (GBrowserIsCompatible()) {
        var i = 0;

	// Get the text of the page
	var d=window.content.document.body.innerHTML;

	// Regular expression to fetch out position reports
        var exp = new RegExp("\{GMST\}(.+)\{GEND\}","g");
        var num=0;
        var lines = []
	
	// Loop over filling lines array with matching entries
        var match = exp.exec(d);
        do {
          if (match!=null && match.length>1) {
  	    for (var i=1; i<match.length; i++) {
		lines[num]=match[i];
		num++;
  	    }
	    match=exp.exec(d);
          }
        } while (match!=null && match.length>1);

      // this variable will collect the html which will eventually be placed in the sidebar
      var sidebar_html = "";  
      // arrays to hold copies of the markers and html used by the sidebar
      // because the function closure trick doesnt work there
 
      // A function to create the marker and set up the event window
      function createMarker(point,name,html) {
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });
        // save the info we need to use later for the sidebar
        gmarkers[i] = marker;
        htmls[i] = html;
        // add a line to the sidebar html
        sidebar_html += '<a href="javascript:myclick(' + i + ')">' + name + '</a><br>';
        i++;
        return marker;
      }

        i=0;

  	// create the map with hardcoded point as the center just to get things started
  		
      	var lat_min=16.265;
      	var lon_min=27.255;
      	var latdeg=23;
      	var londeg=106;
	var hemi1=1;
	var hemi2=-1;
      	latdeg=hemi1 * (latdeg + lat_min/60);
      	londeg=hemi2 * (londeg + lon_min/60);
 
        map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(latdeg,londeg), 13);  // set center and zoom level       
        map.setMapType(G_SATELLITE_MAP);
        map.setZoom(8);

        // === Define the function thats going to process the text strings passed from the php script ===

   function parseit() {

        // === split the document into lines by pulling in the php data string from the server===
        for (var i=0; i<lines.length; i++) {
          	if (lines[i].length > 1) {
	            // === split each line into parts separated by "|" and use the contents ===
	            parts = lines[i].split("|");
	            var latdeg = parseFloat(parts[0]);
	            var londeg = parseFloat(parts[3]);
	            var latmin = parseFloat(parts[1]);
	            var lonmin = parseFloat(parts[4]);
	            var hemi1=-1;
	            var hemi2=-1;
	            if(parts[2]=='n') hemi1=1;
	  			if(parts[2]=='N') hemi1=1;
		  		if(parts[5]=='e') hemi2=1;
		  		if(parts[5]=='E') hemi2=1;
	
	            latdeg=hemi1 * (latdeg + latmin/60);
	      		londeg=hemi2 * (londeg + lonmin/60);
	
	            var html = parts[6];
	            var label = parts[7];
                     if(label.search("\{GEND\}")>0) label=label.substring(0,label.search("\{GEND\}")); // truncate for firefox
	            var point = new GLatLng(latdeg,londeg);

				//center map on first point in file because it is the newest blog entry.
	            if(i==0) map.setCenter(new GLatLng(latdeg,londeg), 8);       

	            var marker = createMarker(point,label,html);
	            map.addOverlay(marker);
		        
		        // put the assembled sidebar_html contents into the sidebar div
		        document.getElementById("sidebar").innerHTML = sidebar_html;
		      } // end of if statement
	 		} // end of loop				 		
         } // end of function parseit()
          
      parseit(); 

    }

    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}
-->
</script>

 <script type="text/javascript"> 
    function setAttributeOnload(object, attribute, val) {
      if(window.addEventListener) {
        window.addEventListener("load",
          function(){ object[attribute] = val; }, false);
      } else {
        window.attachEvent('onload', function(){ object[attribute] = val; });
      }
    }
  </script> 
</head>

<body onload="start_map()">
<iframe src="http://www.blogger.com/navbar.g?targetBlogID=7310305&blogName=Web+Log+of+Sailing+Vessel+NAKIA&publishMode=PUBLISH_MODE_BLOGSPOT&navbarType=BLUE&layoutType=CLASSIC&searchRoot=http%3A%2F%2Fsvnakia.blogspot.com%2Fsearch&blogLocale=en_US&homepageUrl=http%3A%2F%2Fsvnakia.blogspot.com%2F" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" height="30px" width="100%" id="navbar-iframe" allowtransparency="true" title="Blogger Navigation and Search"></iframe> 
<div></div>


<!-- Begin #content - Centers all content and provides edges for floated columns -->

<div id="content">
<!-- Blog Header -->
<div id="header"><div>
  <h1 id="blog-title">
Web Log of Sailing Vessel NAKIA
  </h1>
  <p id="description">News and views from the crew of the Hans Christian 33, Nakia.</p>
</div></div>

<!-- Begin #main - Contains main-column blog content -->
<div id="main"><div id="main2"><div id="main3">
<div align="center">
    <table border=1 width="200px">      <tr>
        <td>
           <div id="map" style="width: 320px; height: 320px"> <font size="2" color="#000000">

			<p align="center"><br><br>Loading Map</p></font>
        </td>
        <td width = 20 valign="top" style="text-decoration: underline; color: #4444ff;">
           <div id="sidebar" style="width: 111px; height: 23px"><font size="2" color="#000000">

			<p align="center"></p></font></div>
        </td>
      </tr>
    </table>     
</div>
I also took the time to move it to my server (changed the API key for the domain) and took out all the blogger.com javascript stuff with it's triggers. So it looks like this

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<meta name="MSSmartTagsPreventParsing" content="true" /> 
<meta name="generator" content="Blogger" /> 

	<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAHY8IKWmLy4n3kfkceKSh9RSCkSE6GxV14ZcEg3hGZPHB5oQIgRSLoGTmvQHWZ1YFSeOCjXDh2DkGaw" type="text/javascript"></script> 

<script type="text/javascript">
<!--
// Adapted from map_blog PHP/JS script by Eric Baicy. This is essentially
// using his code, except that everything is handled in JS, so no PHP hosting
// is required. The following comments are from Eric's version of the file,
// edited only as required to match this version. Thanks Eric!
//
// August 2006 - V1.0 By Eric Baicy
// December 2008 - Scott Emmons - JS only version
// July 2010 - V2.0- Eric Baicy rewritten to work on blogger.com
//
//  Feel free to copy and use this script, but please
//  leave this header intact. 
//  
//  If you want to use this on a commercial site which charges
//  a fee to access this script, you must first obtain permision
//  to use it.  http://www.sailsarana.com
//  
//  This is Javascript that will parse a standard
//  blog file (or any test-type file) and search for the
//  tags: {GMST}stuff-in-between{GEND}
//  where the "stuff-in-between" contains a position
//  of latitude and longitude and some text comments.
//  For example:
//  	{GMST}latdeg|latmin|N[S]|londeg|lonmin|E[W]|Label|Description{GEND} 
//  	Where latdeg = is the degrees of latitude
// 		latmin = the decimal minutes.  If you're using
//		  degrees, minutes and seconds, just convert the seconds to minutes and add to minutes
// 		N[S] = the hemisphere, N = North, S = South. 
//  		londeg = is the degrees of longitude
//		longmin = the degrees of longitude in minutes
//  	E|W = the other hemisphere, E = East, W =West.
//      {GMST}23|16.265|N|106|27.255|W|Waiting out the hurricanes!|Marina Mazatlan{GEND}
//        would be 23d 16.265' North, 106d 27.255' West with a description and a label.
//
// ========================================
var gmarkers = [];
var map;
// arrays to hold copies of the markers and html used by the sidebar
// because the function closure trick doesnt work there
var htmls = [];     

// This function picks up the click and opens the corresponding info window
function myclick(i) 
{
gmarkers[i].openInfoWindowHtml(htmls[i]);
}
 
function start_map() 
{
	if (GBrowserIsCompatible()) {
        var i = 0;

	// Get the text of the page
	var d=window.content.document.body.innerHTML;

	// Regular expression to fetch out position reports
        var exp = new RegExp("\{GMST\}(.+)\{GEND\}","g");
        var num=0;
        var lines = []
	
	// Loop over filling lines array with matching entries
        var match = exp.exec(d);
        do {
          if (match!=null && match.length>1) {
  	    for (var i=1; i<match.length; i++) {
		lines[num]=match[i];
		num++;
  	    }
	    match=exp.exec(d);
          }
        } while (match!=null && match.length>1);

      // this variable will collect the html which will eventually be placed in the sidebar
      var sidebar_html = "";  
      // arrays to hold copies of the markers and html used by the sidebar
      // because the function closure trick doesnt work there
 
      // A function to create the marker and set up the event window
      function createMarker(point,name,html) {
        var marker = new GMarker(point);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });
        // save the info we need to use later for the sidebar
        gmarkers[i] = marker;
        htmls[i] = html;
        // add a line to the sidebar html
        sidebar_html += '<a href="javascript:myclick(' + i + ')">' + name + '</a><br>';
        i++;
        return marker;
      }

        i=0;

  	// create the map with hardcoded point as the center just to get things started
  		
      	var lat_min=16.265;
      	var lon_min=27.255;
      	var latdeg=23;
      	var londeg=106;
	var hemi1=1;
	var hemi2=-1;
      	latdeg=hemi1 * (latdeg + lat_min/60);
      	londeg=hemi2 * (londeg + lon_min/60);
 
        map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(latdeg,londeg), 13);  // set center and zoom level       
        map.setMapType(G_SATELLITE_MAP);
        map.setZoom(8);

        // === Define the function thats going to process the text strings passed from the php script ===

   function parseit() {

        // === split the document into lines by pulling in the php data string from the server===
        for (var i=0; i<lines.length; i++) {
          	if (lines[i].length > 1) {
	            // === split each line into parts separated by "|" and use the contents ===
	            parts = lines[i].split("|");
	            var latdeg = parseFloat(parts[0]);
	            var londeg = parseFloat(parts[3]);
	            var latmin = parseFloat(parts[1]);
	            var lonmin = parseFloat(parts[4]);
	            var hemi1=-1;
	            var hemi2=-1;
	            if(parts[2]=='n') hemi1=1;
	  			if(parts[2]=='N') hemi1=1;
		  		if(parts[5]=='e') hemi2=1;
		  		if(parts[5]=='E') hemi2=1;
	
	            latdeg=hemi1 * (latdeg + latmin/60);
	      		londeg=hemi2 * (londeg + lonmin/60);
	
	            var html = parts[6];
	            var label = parts[7];
                     if(label.search("\{GEND\}")>0) label=label.substring(0,label.search("\{GEND\}")); // truncate for firefox
	            var point = new GLatLng(latdeg,londeg);

				//center map on first point in file because it is the newest blog entry.
	            if(i==0) map.setCenter(new GLatLng(latdeg,londeg), 8);       

	            var marker = createMarker(point,label,html);
	            map.addOverlay(marker);
		        
		        // put the assembled sidebar_html contents into the sidebar div
		        document.getElementById("sidebar").innerHTML = sidebar_html;
		      } // end of if statement
	 		} // end of loop				 		
         } // end of function parseit()
          
      parseit(); 

    }

    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}
-->
</script>
</head>

<body onload="start_map()">
<iframe src="http://www.blogger.com/navbar.g?targetBlogID=7310305&blogName=Web+Log+of+Sailing+Vessel+NAKIA&publishMode=PUBLISH_MODE_BLOGSPOT&navbarType=BLUE&layoutType=CLASSIC&searchRoot=http%3A%2F%2Fsvnakia.blogspot.com%2Fsearch&blogLocale=en_US&homepageUrl=http%3A%2F%2Fsvnakia.blogspot.com%2F" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" height="30px" width="100%" id="navbar-iframe" allowtransparency="true" title="Blogger Navigation and Search"></iframe> 
<div></div>


<!-- Begin #content - Centers all content and provides edges for floated columns -->

<div id="content">
<!-- Blog Header -->
<div id="header"><div>
  <h1 id="blog-title">
Web Log of Sailing Vessel NAKIA
  </h1>
  <p id="description">News and views from the crew of the Hans Christian 33, Nakia.</p>
</div></div>

<!-- Begin #main - Contains main-column blog content -->
<div id="main"><div id="main2"><div id="main3">
<div align="center">
    <table border=1 width="200px">      <tr>
        <td>
           <div id="map" style="width: 320px; height: 320px"> <font size="2" color="#000000">

			<p align="center"><br><br>Loading Map</p></font>
        </td>
        <td width = 20 valign="top" style="text-decoration: underline; color: #4444ff;">
           <div id="sidebar" style="width: 111px; height: 23px"><font size="2" color="#000000">

			<p align="center"></p></font></div>
        </td>
      </tr>
    </table>     
</div>
Where IE and FF work, Chrome still fails to load it.

Lastly I should note I've also tried to strip out all the parsing and plotting of points on the map to where it just simply tries to initialize the map, and it fails. Does anyone see a problem in here from a Javascript point of view? Some outdated thing I'm using that Chrome might not support and just bails?
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: Google Chrome on_load not starting Google Map

Post by Eric! »

Sorry for all the multiple posts, but I've narrowed it down to some Javascript problem with Chrome.

Somewhere in this block of code after running start_map() it bails. By commenting them out I can get the map to load. The commented lines are shown

Code: Select all

function start_map() 
{
        var i = 0;
// Get the text of the page
//	var d=window.content.document.body.innerHTML;
// Regular expression to fetch out position reports
//        var exp = new RegExp("\{GMST\}(.+)\{GEND\}","g");
//        var num=0;
//        var lines = [];
// Loop over filling lines array with matching entries
//        var match = exp.exec(d);
//        do {
//          if (match!=null && match.length>1) {
// 	    for (var i=1; i<match.length; i++) {
//		lines[num]=match[i];
//		num++;
//  	    }
//	    match=exp.exec(d);
//          }
//        } while (match!=null && match.length>1);
[snip..]
Several of these lines of code by themselves cause Chome to fail. An interesting one in particular is
var d=window.content.document.body.innerHTML;

Anyone know why? I'm trying to read the DOM body and apply a regex function to pull out values.
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: Google Chrome on_load not starting Google Map

Post by Eric! »

Apparently windows.content.document.body.innerHTML doesn't work on chrome, but document.body.innerHTML does.
Post Reply