之前在Google Earth Client 端用KML做数据展示, 其中每个元素点击之后都会弹出balloon, 每个ballon会通过javascript(Ajax)调用后台程序, 呈现动态内容.
<BalloonStyle> <text> <![CDATA[ <html> <body id="body" style="margin:0; padding:0; width:400px; height:150px; overflow: hidden;"> Loading.... <script type="text/javascript"> var refreshContent= function() { var httpRequest= new XMLHttpRequest(); httpRequest.open( 'GET', '${address}/elementDetails!detailsOnMap.action?elementId=$[id]', true ); httpRequest.onreadystatechange = function( ) { if( httpRequest.readyState == 4 ) { if( httpRequest.status >= 300 ) { document.getElementById( "body" ).innerHTML= 'Error ' + httpRequest.status; } else { document.getElementById( "body" ).innerHTML= httpRequest.responseText; } } }; httpRequest.send(); } refreshContent(); </script> </body> </html> ]]> </text> </BalloonStyle>
这个BalloonStyle会被应用到指定的元素上, 点击该元素, 就会弹出action请求回来的内容.
后来需要在网页端也能集成显示.
各个元素显示都没有问题, 但是就是点击的时候, Balloon里出现的只有
Loading....
看了一下Google Earth Plugin API, 说是为了安全起见, 默认屏蔽了下面的内容:
JavaScript CSS
<iframe>
tags
<embed>
tags
<object>
tags为了兼容Google Earth Client端的成像, 所以决定不改KML的内容. 在网页端的程序做一些处理.
//为所有的地图上的所有元素增加click事件
google.earth.addEventListener(
ge.getGlobe(), 'click', function(event) {
var obj = event.getTarget();
//判断是否为KmlPlacemark
if (obj.getType() == 'KmlPlacemark' ){
//阻止默认事件处理
event.preventDefault();
var placemark = obj;
var placemark_name = placemark.getName();
//获取非安全的Balloon内容, 包括HTML和javascript脚本
var placemark_desc = placemark.getBalloonHtmlUnsafe();
//从原有placemark_desc中提取访问的URL
var url = getURL(placemark_desc);
//create new balloon with rendered content
var balloon = ge.createHtmlStringBalloon('');
balloon.setFeature(placemark);
if(url){
//动态请求URL, 并将内容赋予balloon
setHTMLContent(balloon,url);
}else{
//如果原有balloon里没有URL, 则显示原来的内容
obj.setContentString(placemark_desc);
}
ge.setBalloon(balloon);
}});
下面是里面用的的两个JS方法function getURL(content){ var durl=/(http:\/\/[^\']+)\'/i; url = content.match(durl); return url.length > 0 ? url[1] : ''; }
var setHTMLContent= function(obj, url) {
var httpRequest= new XMLHttpRequest();
httpRequest.open( 'GET', url, true );
httpRequest.onreadystatechange = function( ) {
if( httpRequest.readyState == 4 ) {
if( httpRequest.status >= 300 ) {
obj.setContentString('Error ' + httpRequest.status);
}
else {
var content = '<div id="body" style="margin:0; padding:0; width:400px; overflow: hidden;">'+
httpRequest.responseText
+'</div>';
obj.setContentString(content);
}
}
};
httpRequest.send();
}
现在在网页上点击placemark, 动态内容就可以显示出来了!