1 2 /** 3 * @name CeL map function 4 * @fileoverview 5 * 本檔案包含了 map 的 functions。 6 * @since 7 */ 8 9 10 if (typeof CeL === 'function') 11 CeL.setup_module('interact.integrate.map', 12 { 13 require : '', 14 code : function(library_namespace, load_arguments) { 15 16 // requiring 17 //var ; 18 eval(library_namespace.use_function(this)); 19 20 21 22 23 /** 24 * null module constructor 25 * @class map 的 functions 26 */ 27 CeL.interact.integrate.map 28 = function() { 29 // null module constructor 30 }; 31 32 /** 33 * for JSDT: 有 prototype 才會將之當作 Class 34 */ 35 CeL.interact.integrate.map 36 .prototype = { 37 }; 38 39 40 41 42 43 44 45 46 // init function 47 48 var SL=new Debug.log,sl=function(){SL.log.apply(SL,arguments);},err=function(){SL.err.apply(SL,arguments);},warn=function(){SL.warn.apply(SL,arguments);}; 49 50 var gMap,mapO,mData,lostItem,gLocal,dLoc={tw:[23.7,121]}; // 台灣: 23.7,121 51 52 53 addLoad(function(){ 54 var b=SL.setBoard('log'); 55 if(window.location.protocol=='file:'&&b)b.style.display='block'; // 強制顯示 log 56 57 if(init&&init.run)sl('Page loaded. Prepare to initial..'); 58 59 if(typeof GLatLng=='undefined'){sl('GMap does not loaded.');return;} 60 61 for(var i in dLoc) 62 dLoc[i]=new GLatLng(dLoc[i][0],dLoc[i][1]); 63 64 setTimeout('init(0);',0); 65 }); 66 67 init.run=1; 68 function init(i){ 69 if(!arguments.callee.run)return; 70 71 var m=0,n; 72 switch(i){ 73 case m++: 74 setSize(); 75 if(typeof preLoadMap=='function')preLoadMap(); 76 break; 77 case m++: 78 catchFile.sn='map-files'; 79 catchFile.f=function(url,success,captureId){ 80 sl('Capture '+(success?'succeeded':'failed')+': <a href="'+url+'">'+url+'</a>'); 81 }; 82 catchFile([ 83 'map.js', 84 'map.css' 85 ]); 86 break; 87 case m++: 88 initMap(); 89 initSearch(); 90 if(window.location.protocol=='file:')setTimeout('mapO.removeTM();',3000); // 3000: 適当。隨 client 而有不同。 91 break; 92 case m++: 93 readLoc(); 94 break; 95 case m++: 96 loadMapData(); 97 break; 98 case m++: 99 placeMapItem(); 100 break; 101 case m++: 102 if(typeof additionalFunc=='function')additionalFunc(); 103 break; 104 } 105 m=['Starting initial process. Catch files..','Catch done. Initial all components..','Map loaded. Loading address records..','address loaded. Loading map data..','map data loaded. placing map items..','placing done. Do additional works..','Initial done.']; 106 sl('init: '+m[i]); 107 if(arguments.callee.run && ++i<m.length) 108 setTimeout('init('+i+');',1); 109 } 110 111 function setOverviewMap(i){ 112 var m=mapO.overviewMap,n; 113 if(m && (n=m.getOverviewMap())){ 114 // 因為有時來不及反應,所以放這邊。 115 if(!i)n.addControl(new GMenuMapTypeControl(1)),i=1,setTimeout('setOverviewMap(1);',500); 116 else m.hide(); 117 }else /*m.show(),*/setTimeout('setOverviewMap();',500); 118 } 119 120 121 function initSearch(){ 122 if(typeof google!='undefined' && google.load)google.load("search","1",{callback:function(){ 123 gLocal=new getSearch(function(r){ 124 google.search.LocalSearch.resizeStaticMapUrl(r,100,140); 125 mapO.setLatLng(r.address||r.titleNoFormatting,r.lat,r.lng); 126 sA(r.address,r.titleNoFormatting,r.phone.join('<br/>')+'<br/>'+r.address); 127 // http://code.google.com/apis/ajaxsearch/documentation/reference.html#_class_GlocalResult 128 var h='<div style="background-color:#fef;margin-left:3em;margin-right:3em;padding-top:.5em;padding-bottom:.5em;font-size:.8em;clear:both;margin-bottom:40px;"><b onclick="sA(\''+UnicodeToHTML(r.address,2)+'\',\''+UnicodeToHTML(r.titleNoFormatting,2)+'\',\''+UnicodeToHTML(r.phone.join('<br/>')+'<br/>'+r.address,2)+'\');" title="'+r.titleNoFormatting+'" style="color:#94e;cursor:pointer;"><img style="margin-top:-.5em;float:left;margin-right:1em;" src="'+r.staticMapUrl+'"/>'+r.title 129 +'</b><br/>'+r.address+'<br/>'+r.phone.join('<br/>')+(r.phone.length?'<br/>':'')/*+r.listingType+'<br/>'*/+r.content+'<br/>('+r.lat+','+r.lng+') <a href="'+r.url+'" target="_blank">Use Google Maps</a></div>'; 130 if(sA2.c)sA2.c.innerHTML+=h;else sl(h); 131 },'Local'); 132 sl('initSearch: local search initialed.'); 133 }}); 134 else sl('initSearch: Can not initial local search. Please load API.'); 135 } 136 137 138 var _map_tmp_message; 139 initMap.flag={backgroundColor:'#DDE'}; 140 function initMap(){ 141 var a,m,i,_f=arguments.callee; 142 mapO=new gMap('map_canvas',dLoc.tw,_f.flag); 143 //if(!mapO)return 1; 144 145 //mapO.geocoder.setBaseCountryCode('TW'); 146 sl('initMap: set geocoder country code: '+mapO.geocoder.getBaseCountryCode()); 147 148 // 要先 show 才能得到 getOverviewMap() 149 if(m=mapO.overviewMap) 150 // IE7 上 .hide() 時 .show() 會出錯 151 // 2008/9/6 22:37:33 IE6 也會出錯了 152 if(navigator.userAgent.indexOf('MSIE')==-1) 153 m.show(),setOverviewMap(); 154 155 // small mark template http://econym.googlepages.com/custom.htm http://mapki.com/wiki/Available_Images http://econym.googlepages.com/geicons.htm http://code.google.com/apis/maps/documentation/overlays.html#Icons_overview 156 // iconSize 的處理還是有問題。 157 mapO.icon(_f.iconOption||{ 158 shadow:'http://labs.google.com/ridefinder/images/mm_20_shadow.png', 159 iconSize:new GSize(12,20), 160 shadowSize:new GSize(22,20), 161 iconAnchor:new GPoint(6,20), 162 infoWindowAnchor:new GPoint(5,1) 163 },1); 164 mapO.icon(_f.iconArray||[ 165 {image:'http://labs.google.com/ridefinder/images/mm_20_green.png'},//http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png//{shadow:'http://maps.google.com/mapfiles/kml/pal5/icon14s.png',image:'http://maps.google.com/mapfiles/kml/pal5/icon14.png'},// 166 {image:'http://labs.google.com/ridefinder/images/mm_20_yellow.png'}, 167 {image:'http://labs.google.com/ridefinder/images/mm_20_green.png'},//{icon:G_DEFAULT_ICON}, 168 {image:'http://labs.google.com/ridefinder/images/mm_20_orange.png'},//'http://maps.google.com/mapfiles/arrow.png', 169 '' 170 ]); 171 mapO.runAfterAdd=function(o){getO.add(o.address,o.name);showML.sel(o);showML();}; 172 mapO.runOnClick=function(o){showML.sel(o);showML();}; 173 mapO.runAfterRemove=function(o){if(showML.sel()==o)showML.sel(null,1);showML();}; 174 mapO.notFound=function(a,d){sl('<em>沒找到 ['+a+'] '+d.name+'</em>');return false;}; 175 // 在 unload 的時候呼叫 GUnload 以避免瀏覽器 memory leak。 176 addListener(0,'unload',function(){try{GUnload();}catch(e){}}); 177 178 a=function(htm,t,js,ico){ 179 return '<div class="cm_line" title="'+t+'" onclick="'+js+'" onmouseover="this.className=\'cm_line_mo\';" onmouseout="this.className=\'cm_line\';"><img style="height:1em;width:1em;" src="'+(ico||'http://www.google.com/mapfiles/markerTransparent.png')+'"/> '+htm+'</div>'; 180 }; 181 if(m=mapO.map) 182 // use google's message 183 i=function(i){try{ 184 eval('_map_tmp_message=p('+i+');',m); 185 var a=_map_tmp_message; 186 //sl('setContextMenu '+i+': '+a); 187 return a&&a.length<8?a:''; 188 }catch(e){}}, 189 mapO.setContextMenu([ 190 a(i(10985)||'Zoom in','將地圖於此放大','mapO.showContextMenu(0),mapO.map.zoomIn(mapO.clickLatLng,true);','http://www.google.com/mapfiles/zoom-plus.png') 191 ,a(i(10986)||'Zoom out','將地圖於此縮小','mapO.showContextMenu(0),mapO.map.zoomOut(mapO.clickLatLng,true);','http://www.google.com/mapfiles/zoom-minus.png') 192 ,a(/*i(11047)||*/'Set Center','將地圖於此置中','mapO.showContextMenu(0),mapO.setCenter(mapO.clickLatLng);','http://www.google.com/mapfiles/center.png') 193 ,'<hr/>' 194 ,a('Search near','搜尋附近','mapO.showContextMenu(0),showNeighbor(mapO.clickLatLng);','http://maps.google.com/mapfiles/kml/pal2/icon13.png') 195 ].join('')), 196 GEvent.addListener(m,"click",function(){ 197 mapO.showContextMenu(0); 198 }),GEvent.addListener(m,"dragstart",function(){ 199 mapO.showContextMenu(0); 200 }); 201 } 202 203 204 function readLoc(){ 205 if(loadMapData.dataF)catchFile([loadMapData.dataF,mapO.locFP=loadMapData.dataF+'.adr.csv']); 206 mapO.readLoc(); 207 } 208 209 210 //loadMapData.baseD=''; 211 // 預設可使用之模板 212 loadMapData.getHTM=function(d,type){ 213 var l=mData[d.name||d.address],a=[mapO.getPoint(d,type)],r=[]; 214 if(d.address||'')a.unshift(d.address); 215 l=l?l.link:''; 216 if(!loadMapData.baseD)loadMapData.baseD=''; 217 if(d.name) // 不能用 this.baseD 218 r.push('<em>'+(l?'<a href="'+loadMapData.baseD+l+'" target="_blank">'+d.name+'</a>':d.name)+'</em>'); 219 if(d.dscr)r.push(d.dscr); 220 r.push('<div class="adr">'+a.join('<br/>')+'</div>'); 221 if(typeof d.getLength=='function')r.push('length: '+(d.getLength()/1000).toFixed(3)+'km'); 222 if(typeof d.getArea=='function')r.push('面積: '+d.getArea().toFixed(3)+'m²'); 223 //if(showNeighbor.pointer&&d.getLatLng)r.push('距離 '+showNeighbor.pointer.distanceFrom(d.getLatLng())); 224 //r.push(,'<hr class="sp"/><span onclick="">search near</span>'); 225 return r.join('<br/>').replace(/(<\/(div|p)>)\s*<br\/?>/g,'$1'); 226 }; 227 loadMapData.lessItems=3; 228 loadMapData.forEach=function(mapData,index){}; 229 /* 230 loadMapData.zIndexP=function(){ 231 sl('click '+this.name); 232 return -1; 233 }; 234 */ 235 function loadMapData(){ 236 /* load: 這裡假設 data 中標題可作為id(獨一無二) 237 map data: [標題 敘述(description) link _data_] 238 _data_: search string/kind additional description/data of different kind of data 239 search string/additional description (用括弧框起來的) 240 'marker' lat lng 241 'polyline' points levels 242 'polygon' points levels 243 244 mData[標題||address]={}; 245 */ 246 mData={}; 247 var i=0,m,t,_f=arguments.callee; 248 _f.run=1; 249 250 try{t=getU(_f.dataF);}catch(e){sl('Get data file ['+_f.dataF+'] error: '+e.message);} 251 if(t)t=parseCSV(t);//t.replace(/\r+/g,'').replace(/\n+$/,'').replace(/^\n+/,'').split('\n'); 252 else t=[],showML.write('No list got of ['+_f.dataF+'].'); 253 254 showML.write('總共 '+t.length+' 筆資料正處理中,請稍候…'); 255 sl('loadMapData: Found '+t.length+' lines. Parsing.. (<em onclick="if(loadMapData.run)loadMapData.run=0,sl(\'User stopped.\');" style="cursor:pointer;">stop</em>)'); 256 for(;i<t.length&&_f.run;i++){ 257 //sl(t[i][7]); 258 //if(t[i] && (m=t[i].replace(/\\n/g,'<br/>').split('\t')).length>_f.lessItems) 259 if(t[i].length>_f.lessItems) 260 _f.forEach(t[i],i); 261 } 262 _f.run=0; 263 } 264 265 266 placeMapItem.done=function(i){ 267 //sl('placing done.'); 268 showML.refresh=1,showML(); 269 // workaround 權宜之計: iconSize 的處理還是有問題。 270 setTimeout('if(mapO)mapO.iconA[2].image=G_DEFAULT_ICON.image;',500); 271 }; 272 placeMapItem.step=function(i){ 273 var _t=this; 274 if(_t.run&&i<_t.stepA.length&&(!_t.loadMax||i<_t.loadMax)) 275 mapO.add(mData[_t.stepA[i++]]),setTimeout('placeMapItem.step('+i+');',0/*i>40?400:i+i*i/4*/); 276 else if(_t.done)_t.done(i); 277 }; 278 placeMapItem.loadMax=80; 279 function placeMapItem(){ 280 var _f=arguments.callee,i; 281 if(_f.noPlace){ // 一開始不列出點 282 if(typeof _f.noPlace=='function')_f.noPlace(); 283 return; 284 } 285 286 lostItem={}; 287 _f.run=1; 288 //showML(); 289 showML.refresh=0; 290 if(_f.step){ 291 _f.stepA=[]; 292 for(i in mData) 293 lostItem[i]=mData[i],_f.stepA.push(i);//,mapO.add(mData[i]); 294 setTimeout('placeMapItem.step(0);',0); 295 }else{ 296 for(i in mData)mapO.add(mData[i]); 297 if(_f.done)_f.done(); 298 } 299 } 300 301 302 303 // interface 304 305 // 2008/9/6 15:7:34 306 //setSize.size=[880,320,240]; // width, height, menuWidth 307 setSize.size='95%,70%,25%'.split(','); // width, height, menuWidth 308 setSize.setContainer=function(){ 309 try{ 310 this.menuC=(this.menu=document.getElementById('markerList')).parentNode; // menuC: menu container 311 return this.container=document.getElementById('map_canvas').parentNode; 312 }catch(e){} 313 }; 314 function setSize(){ 315 var _f=arguments.callee,s=_f.size,_s=s.join('\0').split('\0'),m,a=function(i,k){ 316 if(!isNaN(s[i]))s[i]+='px'; 317 if(typeof _s[i]=='string'&&(m=_s[i].match(/^(\d+)%$/))) 318 k=k?'Height':'Width', 319 _s[i]=Math.floor((window.innerHeight?window['inner'+k]:document.documentElement&&document.documentElement.clientHeight?document.documentElement['client'+k]:document.body['offset'+k])*m[1]/100); 320 }; 321 322 /* 323 // from getWinStatus() 324 with(document.body.style)width=height='100%'; 325 sl('setSize: window.inner: '+window.innerWidth+','+window.innerHeight); 326 sl('setSize: window.page: '+window.pageXOffset+','+window.pageYOffset); 327 sl('setSize: screen: '+screen.width+','+screen.height); 328 sl('setSize: document.documentElement.client: '+document.documentElement.clientWidth+','+document.documentElement.clientHeight); 329 sl('setSize: document.body.scroll: '+document.body.scrollWidth+','+document.body.scrollHeight); 330 sl('setSize: document.body.offset: '+document.body.offsetWidth+','+document.body.offsetHeight); 331 sl('setSize: document.body.client: '+document.body.clientWidth+','+document.body.clientHeight); 332 */ 333 334 a(0); 335 a(1,1); 336 a(2); 337 //sl('setSize: '+_s); 338 339 a=_f.container; 340 if(!a&&!(a=_f.setContainer()))return; 341 342 with(a.style)width=s[0],height=s[1]; 343 with(_f.menuC.style)width=s[2],height=s[1]; 344 345 _f.menu.style.height=(_s[1]-_f.menu.offsetTop)+'px'; 346 347 //sl('setSize: '+a.offsetWidth+'-'+_f.menuC.offsetWidth+'='+(a.offsetWidth-_f.menuC.offsetWidth)); 348 //sl('setSize: '+_s[0]+'-'+_s[2]+'='+(_s[0]-_s[2])); 349 initMap.flag.size=[ 350 a.offsetWidth-_f.menuC.offsetWidth-(navigator.userAgent.indexOf('MSIE')==-1?13:1), // 13: 和 scrollbar 有關嗎?? 351 (navigator.userAgent.indexOf('MSIE')==-1?_s[1]:_s[1]) // _s[1] 不能改成 a.offsetHeight 352 ]; 353 } 354 355 356 357 showML.refresh=1; 358 showML.closeMark='×'; 359 showML.indexA='iA'; 360 showML.selClass='sel'; 361 showML.specialKind='sp'; 362 showML.isSelR=new RegExp('(^|\\s+)'+showML.selClass); 363 //showML.selO=null; 364 showML.sel=function(o,removed){ 365 var _t=this; 366 if(typeof o!='undefined'){ 367 // GMarker.setImage(src) 368 if(!removed&&_t.selO&&_t.selO.setImage) 369 try{_t.selO.setImage(mapO.icon().image);}catch(e){} // 用 try 是因為有時被刪了可是卻還是在(動作太快?),這時要 setImage 會出錯。 370 _t.selO=o; 371 if(o&&o.setImage)o.setImage(mapO.icon(showSP.selectedI).image); 372 } 373 return _t.selO; 374 }; 375 showML.getName=function(o){ 376 var name=o.parentNode.attributes.getNamedItem(this.indexA),type; 377 if(name&&(name=name.nodeValue)&&(type=name.match(/^([a-z]+),(.+)$/i))){ 378 //sl('showML.getName: ['+type[1]+'] '+type[2]+'('+getO.alias(type[2])+','+mapO.getO(type[1],getO.alias(type[2]))+')'); 379 //name=,type=type[1]; 380 return [getO.alias(type[2]),type[1]]//[name,type]; 381 } 382 }; 383 showML.write=function(t){ 384 try{document.getElementById('markerList').innerHTML=t;}catch(e){} 385 }; 386 function showML(o){ 387 if(!mapO)return; // 尚未 initial? 388 389 var _f=arguments.callee; 390 if(o){ 391 var name,type; 392 if(type=_f.getName(o)){ 393 name=type[0],type=type[1]; 394 if(o.className=='closeMark') 395 mapO.remove(name,type); 396 else{ 397 showML.sel(mapO.getO(type,name));//.setImage(mapO.icon(2).image); 398 mapO.show(name,type); 399 o=o.parentNode; 400 for(var i=0,LI=o.parentNode.parentNode.getElementsByTagName('li');i<LI.length;i++) 401 if(_f.isSelR.test(LI[i].className))LI[i].className=LI[i].className.replace(_f.isSelR,''); 402 o.className+=' '+_f.selClass; 403 } 404 } 405 return false; 406 } 407 408 if(!_f.refresh)return; 409 //alert(mapO.getOArray('type').join('\n')); 410 411 var t=['<ol>'],a,i,j,id,OK={}; 412 for(j in mapO.supportKind()){ 413 a=mapO.getO(j); 414 for(i in a){ 415 //sl(a[i].name+','+a[i].address); 416 if(a[i].name in lostItem)delete lostItem[a[i].name]; 417 else if(('address' in a[i]) && (a[i].address in lostItem))delete lostItem[a[i].address]; 418 419 id=typeof a[i].getLatLng=='function'?a[i].getLatLng():a[i].name; 420 if(!(id in OK)) 421 OK[id]=1, 422 t.push('<li '+_f.indexA+'="'+j+','+i+'" class="'+(j=='marker'?'':_f.specialKind)+' '+(_f.sel()==a[i]?_f.selClass:'')+'"' 423 +'><a href="#" title="'+UnicodeToHTML(( 424 ((a[i].name+'').indexOf(id)!=-1||(a[i].dscr+'').indexOf(id)!=-1?'':id+'\n') 425 +(a[i].dscr||i) 426 +(showNeighbor.pointer&&typeof a[i].getLatLng=='function'?'\n距離定點 '+(a[i].getLatLng().distanceFrom(showNeighbor.pointer.getLatLng())/1000||0).toFixed(3)+' km':'') 427 ).replace(/<br\/?>/gi,'\n').replace(/\n{2,}/g,'\n'),2)+'" onclick="return showML(this);" onmouseover="showSP(this,1);" onmouseout="showSP(this);">' 428 +(a[i].name||i).replace(/<[^>]+>/g,'') 429 +'</a> [<a href="#" class="closeMark" onclick="return showML(this);" title="關閉">'+_f.closeMark+'</a>]</li>');// title="remove marker" 430 } 431 } 432 for(i in lostItem)t.push('<li class="lost"><a href="#" onclick="mData['+dQuote(i,0,"'")+'].show=1;mapO.add(mData['+dQuote(i,0,"'")+']);return false;" title="'+UnicodeToHTML(mData[i].name||mData[i].type||'')+'">'+i+'</a></li>'); 433 t.push('</ol>'); 434 //sl(UnicodeToHTML(t.join('')),1); 435 _f.write(t.join('')); 436 if(typeof dealLink=='function')setTimeout('dealLink(0,1);',0); 437 return false; 438 } 439 440 441 // show spot 442 showSP.defaultI=0; // default icon index 443 showSP.selectedI=2; // selected icon index 444 function showSP(o,i){ 445 var _f=arguments.callee; 446 if(o){ 447 var name,type; 448 if(type=showML.getName(o)){ 449 name=type[0],type=type[1]; 450 o=mapO.getO(type,name); 451 if(o&&o.setImage&&o!=showML.sel()) 452 //sl('showSP: set icon of ['+o.name+'] to '+i), 453 o.setImage(mapO.icon(i).image); 454 } 455 return false; 456 } 457 458 } 459 460 // 應用 461 462 function removeAll(){ 463 showML.refresh=0,lostItem={}; 464 if(mapO)mapO.removeAll(); // 尚未 initial? 465 if(showML)showML.sel(null,1),showML.refresh=1,showML(); 466 } 467 468 469 // 不能造成 type 改變! 470 function normalize_address(t) { 471 var _f = arguments.callee, a = '0123456789'; 472 if (!_f.dc) { 473 _f.nr = new RegExp('[' + a + ']', 'g'); 474 _f.dc = {}; 475 for ( var i = 0; i < a.length; i++) 476 _f.dc[a.charAt(i)] = i; 477 } 478 return t.replace(/[\s ]+/g, '').replace(_f.nr, function($0) { 479 return _f.dc[$0]; 480 }) 481 //.replace(/號([^樓]+樓|之.{1,2})$/,'號'); 482 ; 483 }; 484 485 /* 486 http://www.post.gov.tw/post/internet/f_searchzone/sz_a_b_ta.jsp#a 487 縣市 488 鄉鎮市區 【市】為縣轄市 489 村里 直轄市:台北市、高雄市及省轄市:基隆市、新竹市、台中市、嘉義市、台南市以外地區由於路名結構變化較大,有些地區沒有路、街,僅有「村」、「里」名稱 490 鄰 491 路街 路名中不可使用(全、半形)阿拉伯數字,必須一律使用中文數字,如中正二路等,惟門牌號不必輸入。 新村、山莊、新城、工業區等與街、路同級之名稱 492 段 493 巷 文字巷 494 弄 495 號 496 \d(之\d)樓(之\d) 497 498 縣市鄉鎮區村里鄰路街段巷弄號樓 499 500 TODO: 501 806台灣高雄市前鎮區光華二路413號 502 503 */ 504 CeL.interact.integrate.map 505 . 506 /** 507 * 解析地址 508 * @param {String} address 地址 509 * @returns 510 * @memberOf CeL.interact.integrate.map 511 */ 512 parse_address = function (address) { 513 var a = {}, i, v, w = '縣市鄉鎮區村里鄰路街段巷弄號樓', 514 r = new RegExp('[^' + w + ']+([' + w + '])', 'g'); 515 516 var _ = address.replace(/[ \s]+/g, '').replace(/號([^樓F]{1,6})F$/, '號$1樓') 517 .replace(/^(\d{3,5})?[台臺]灣/, '$1').replace(/^\d+/, function($0) { 518 r.zip = $0; 519 return ''; 520 }).replace(r, function($0, $1) { 521 v = $0; 522 if (/縣市/.test(i = $1) && !r.zip) 523 v.replace(/^\d{3}\d{2}?}/, function($0) { 524 r.zip = $0; 525 return ''; 526 }); 527 a[i] = v; 528 //sl(v); 529 return ''; 530 }); 531 // sl('['+address+'] --- ['+_+']'); 532 return _ ? 0 : address; 533 }; 534 535 536 // 地址轉 index 537 getO.n={}; // name(address) to mapO.getO's name 538 getO.add=function(alias,name,type){ 539 if(alias&&name&&alias!=name){ 540 if(type&&mapO.getO(type,alias)&&!mapO.getO(type,name)){ 541 var t=name;name=alias,alias=t; 542 } 543 //sl('getO.add: ['+alias+'] set to ['+name+']'), 544 this.n[alias]=name; 545 } 546 }; 547 getO.alias=function(name){return this.n[name]||name;}; 548 function getO(name){ 549 return mapO.getO(arguments.callee.n[name]||name); 550 } 551 552 553 554 555 /* search address 556 sA(index of mData) 557 sA({type(where):'',name:'',description:''}) 558 sA(type(where),name,description) 559 */ 560 function sA(i,a,b){ 561 if(!mData)return; // 尚未 initial? 562 if(!(i in mData)||arguments.length>1) 563 //sl('sA: search '+i), 564 mapO.searchPoint.apply(mapO,arguments); 565 else 566 //sl('sA: call mData['+i+']('+mData[i].type+')'), 567 mapO.searchPoint(mData[i]); 568 return false; 569 } 570 571 // 先找尋現有資料 572 function sA2(adr,noFit){ 573 var _f=arguments.callee; 574 575 if(!noFit){ 576 showFit(adr 577 ,function(k,o){return k&&(o.name+o.description).indexOf(k)!=-1;} 578 ,function(k){_f(adr,1);} 579 ); 580 return; 581 } 582 583 if(typeof adr_to_mData!='object'||mapO.LatLngR.test(adr))return sA(adr); 584 585 //return sA(adr_to_mData[adr]||adr); 586 587 588 if(!_f.c)_f.c=document.getElementById('guess'); 589 590 if(!(adr in adr_to_mData)&&(adr.toLowerCase() in adr_to_mData)) 591 //sl('sA2: ['+adr+']→['+adr.toLowerCase()+']'), 592 adr=adr.toLowerCase(); 593 if(adr_to_mData[adr] in mData){ 594 var a=adr_to_mData[adr]; 595 mData[a].show=1; // 置中 596 sA(a); 597 if(showML.selO)mapO.showWindow(showML.selO); 598 }else if(!_f.c)sA(adr); 599 else mapO.getLocations(adr,function(r){ 600 var cM='<div style="float:right;cursor:pointer;" title="close" onclick="sA2.c.style.display=\'none\';">[×]</div>'; 601 if(gLocal){gLocal.searcher.setCenterPoint(showNeighbor.pointer.getLatLng()||mapO.setCenter()||'台灣');gLocal.s(adr);} 602 if(!r.length){_f.c.innerHTML=cM+'使用 GClientGeocoder.getLocations 沒找到 [<span style="color:#e23;">'+adr+'</span>]:<br/>'+mapO.GeoStatus(mapO.getLocations.errno),_f.c.style.display='block';return;} 603 if(r.length==1&&adr==r[0][2]){sA(adr);if(showML.selO)mapO.showWindow(showML.selO);return;} 604 var i=0,t=[cM+'對於 [<span style="color:#e23;">'+adr+'</span>],您是不是指:<ol>']; 605 for(;i<r.length;i++) 606 if(r[i][0]) 607 //sl('sA2: '+r[i]), 608 t.push('<li><span title="'+r[i][0]+','+r[i][1]+'">〒</span> <span class="point" onclick="sA(this.title);if(showML.selO)mapO.showWindow(showML.selO);return false;" title="'+r[i][2]+'">'+r[i][2]+'</span></li>'); 609 t.push('</ol>'); 610 _f.c.innerHTML=t.join(''); 611 _f.c.style.display='block'; 612 });//sA(adr); 613 return false; 614 } 615 616 617 618 /* 619 從 mData show 符合條件的 620 */ 621 showFit.showZoom=40; // 這以下就 zoom 622 showFit.limit=80; // 最多取點數 623 function showFit(k,func,notFound){ 624 if(typeof k=='undefined'||!func)return; 625 removeAll(); 626 showML.write('頁面資料讀取中,請稍候…'); 627 628 var i,p=[],b,_f=arguments.callee; 629 for(i in mData) 630 if(func(k,b=mData[i],i) && (b=mapO.searchPoint.call(mapO,b))) // 確定有找到才 c++ 631 if(p.push(b), _f.limit&&p.length>_f.limit)break; 632 633 if(p.length<_f.showZoom) 634 if(p.length){ 635 // zoom 636 b=new GLatLngBounds(); 637 for(i=0;i<p.length;i++) 638 b.extend(p[i]); 639 mapO.setCenter({p:b.getCenter(),m:'pan',z:mapO.map.getBoundsZoomLevel(b)}); 640 }else if(notFound)notFound(k); 641 642 return p; 643 } 644 645 646 647 /* 只顯示附近的spot 648 showNeighbor('高雄市苓雅區'); 649 650 bug: 651 652 TODO: 653 setZoom: getBoundsZoomLevel 654 addSelf: 加入此點,使之受到管控。預設 false 655 不在管控內 656 */ 657 showNeighbor.pointer=null; // default GMarker 658 showNeighbor.addPointer=function(a){ 659 var _m=mapO.map,m=mapO.addMarker( 660 new GLatLng(22.62,120.33)//dLoc.tw 661 ,{draggable:true,title:'請拖曳我,以找出鄰近的點。',icon:mapO.icon(3)} 662 ); 663 GEvent.addListener(m,"dragend",function(){ 664 showNeighbor(m.getLatLng()); 665 }); 666 667 if(this.l)GEvent.removeListener(this.l); 668 this.l=GEvent.addListener(_m,"click",function(overlay,point){ 669 var i,p=[5,10,15,20,30,50],s='<br/><a href="#" onclick="return showNeighbor.byD();" title="search near">搜尋附近</a>'; 670 for(i=0;i<p.length;i++)s+=' <a href="#" onclick="return showNeighbor.byD('+p[i]+');">'+p[i]+'</a>'; 671 s+=' km'; 672 if(overlay==m)m.openInfoWindowHtml('經緯度: '+m.getLatLng()+s); 673 else if(!overlay&&point) 674 p=m.getLatLng(),m.setLatLng(point), 675 m.openInfoWindowHtml(point+'<br/>from: '+p+',<br/>distance: '+(p.distanceFrom(point)/1000).toFixed(3)+'km'+s); 676 }); 677 678 return this.pointer=m; 679 }; 680 showNeighbor.arg={ // 傳給 .getNeighbor() 的參數 681 //f:'n[i]=n[i][1][2];', // 不能改變結構!因為需要 getBoundsZoomLevel 682 d:30, 683 c:9 684 }; 685 showNeighbor.forEach=function(a){ 686 //sl('showNeighbor.forEach: ['+(typeof a[1][2])+'] '+a[1][2]); 687 sA(a[1][2]); 688 }; 689 showNeighbor.byD=function(d){ 690 var _t=this; 691 if(d)_t.arg.d=d; 692 if(_t.pointer)_t(_t.pointer.getLatLng()); 693 return false; 694 }; 695 showNeighbor.notFound=function(address,address_not_found){ 696 showML.write('抱歉,找不到 <em>'+address+'</em>'+(address_not_found?'':' 附近的點')+'。'); 697 }; 698 function showNeighbor(l,f){//(location | [location, address], addSelf) 699 if(!l)return; 700 showML.write('頁面資料讀取中,請稍候…'); 701 var _f=arguments.callee,i,o,adr; 702 if(l instanceof Array)adr=l[1],l=l[0]; 703 //sl('showNeighbor: ['+l+','+adr+'] '+(l instanceof GLatLng)+', '+mapO.getLatLng(l+'')); 704 if(!(l instanceof GLatLng)) 705 // 無此資料。嘗試取得 loc.. 706 return mapO.getLatLng(l+'',[function(p){_f([p,adr||l]);},function(p){if(p)return _f([p,adr||l]);_f.notFound&&_f.notFound(adr||l,1);}]); 707 o=mapO.getNeighbor(l,_f.arg); 708 if(o.length){ 709 removeAll(); 710 var bounds=new GLatLngBounds(); 711 bounds.extend(l); 712 for(i=0;i<o.length;i++){ 713 if(!isNaN(o[i][1][1])) 714 //sl('Add to bound: '+o[i][1][0]+','+o[i][1][1]), 715 bounds.extend(new GLatLng(o[i][1][0],o[i][1][1])); 716 //sl('add ['+o[i][1][2]+'] by '+(_f.forEach+'').slice(0,20)+'..'); 717 _f.forEach(o[i]); 718 } 719 if(!mapO.searchPoint.show) // 若設了 searchPoint.show,還是會被其他的奪去… 720 mapO.setCenter({p:bounds.getCenter(),m:'pan',z:mapO.map.getBoundsZoomLevel(bounds)}); 721 }else _f.notFound(l); 722 if(_f.pointer)_f.pointer.setLatLng(l),_f.pointer.openInfoWindowHtml('搜尋 '+(adr?'<em title="'+l+'">'+adr+'</em> ':l)+' 四周 '+_f.arg.d+' km<br/>找到 '+o.length+'/(最多 '+_f.arg.c+') 個點。'); 723 //sl('showNeighbor: search around '+l+' (四周 '+_f.arg.d+' km) get '+o.length+'/(max '+_f.arg.c+') results.'); 724 } 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 // =================================================== 740 /* 741 ** use Yahoo! Map to get position of a address 742 743 _=this 744 745 TODO: 746 747 748 HISTORY: 749 2008/7/31 19:56:29 create 750 751 752 http://tw.developer.yahoo.com/maps/ 753 http://developer.yahoo.com/maps/ajax/V3.8/index.html 754 */ 755 var 756 getLatLon= 757 758 (function(){ 759 760 var 761 762 // class private ----------------------------------- 763 764 // class name 765 n='getLatLon', 766 767 // running now 768 r=0, 769 770 // interval/timeout seed 771 s=''+Math.random()*1e12, 772 773 774 // { address: [function(lat, lng, address), not found function(address)], .. } 775 o={}, 776 777 // queue: [ adr, .. ] 778 q=[], 779 780 781 // map object 782 m, 783 784 // initial 785 i=function(){ 786 if(typeof YMap!='function'){ 787 //sl(n+': Please include YMap first!'); 788 return 1; 789 } 790 791 var o=document.createElement('div'); 792 document.body.appendChild(o); 793 o.style.width=o.style.height='1px'; // =0 會造成 .getArea() 出問題 794 YEvent.Capture(m=new YMap(o),EventsList.onEndGeoCode,c); 795 o.style.visibility='hidden'; 796 //o.style.display='none'; // 會造成 .getArea() 出問題 797 798 //s=Math.random()*1e12+''; 799 }, 800 801 802 // do query 803 d=function(){ 804 //sl(n+'.do query: '+q[0]); 805 if(!q||!q.length)r=0; 806 else m.geoCodeAddress(q.shift()); 807 }, 808 809 810 // catch function 811 c=function(r){ 812 var a=r.Address,f; 813 814 if(f=_.interval) 815 setTimeout(n+'("'+s+'");',f); 816 else d(); 817 818 if(a in o) 819 if(f=o[a],r.success)f[0](r.GeoPoint.Lat,r.GeoPoint.Lon,a); 820 else f[1]&&f[1](a); 821 delete o[a]; 822 }, 823 824 825 // instance constructor --------------------------- 826 _=function(a,f,nf){ // address, function, not found function 827 if(a===s)return d(); 828 829 if(!a||!f || !m&&i())return 1; 830 831 o[a+='']=[f,nf]; 832 833 //sl(n+': ('+q.length+')'+[a,f,nf]); 834 q.push(a); 835 836 if(!r)r=1,d(); 837 }; 838 839 840 // class public interface --------------------------- 841 842 // interval (ms) 843 _.interval=0; 844 845 846 // class constructor --------------------------- 847 848 i(); 849 850 851 return _; 852 })(); // (function(){ 853 854 // =================================================== 855 856 857 /* old 858 // use Yahoo! Map 859 860 // interval 861 //getLatLon.t=200; 862 863 // { address: [function, not found function], .. } 864 getLatLon.o={}; 865 866 // queue: [ adr, .. ] 867 getLatLon.q=[]; 868 869 // initial 870 getLatLon.i=function(){ 871 if(typeof YMap!='function'){ 872 //sl('getLatLon: Please include YMap first!'); 873 return 1; 874 } 875 var c=document.createElement('div'); 876 document.body.appendChild(c); 877 c.style.width=c.style.height=0; 878 YEvent.Capture(this.m=new YMap(c),EventsList.onEndGeoCode,this.c); 879 c.style.display='none'; 880 this.T=Math.random()*1e12+''; 881 }; 882 883 // catch function 884 getLatLon.c=function(r){ 885 var t=getLatLon; 886 if(t.t)setTimeout('getLatLon.d("'+t.T+'");',t.t);else getLatLon.d(); 887 var f=t.o; 888 if(r.Address in f) 889 if(f=f[r.Address],r.success)f[0](r.GeoPoint.Lat,r.GeoPoint.Lon,r.Address); 890 else f[1]&&f[1](r.Address); 891 delete t.o[r.Address]; 892 } 893 894 // do query 895 getLatLon.d=function(){ 896 var _f=arguments.callee,_t=this,a,f,n; 897 //sl('getLatLon.d: '+_t.q[0]); 898 if(!_t.q||!_t.q.length)_t.r=0; 899 else _t.m.geoCodeAddress(_t.q.shift()); 900 }; 901 902 903 // running 904 //getLatLon.r=0; 905 906 function getLatLon(adr,f,nf){ 907 var _f=arguments.callee; 908 if(adr===_f.T)return _f.d(); 909 if(!adr||!f || !_f.m&&_f.i())return; 910 911 if(!_f.q)_f.q=[]; 912 //sl('getLatLon: ('+_f.q.length+')'+[adr,f,nf]); 913 _f.o[adr]=[f,nf]; 914 _f.q.push(adr); 915 916 if(!_f.r){_f.r=1;_f.d();} 917 } 918 */ 919 920 921 922 923 924 925 926 927 // =================================================== 928 929 /* 930 main map function 931 932 _=this 933 934 TODO: 935 936 */ 937 938 //var 939 gMap= 940 941 (function(){ 942 943 // class private ----------------------------------- 944 var 945 946 // class interface ----------------------------------- 947 _=function(){ 948 // Dynamic Loading http://code.google.com/apis/ajax/documentation/#Dynamic 949 //if(typeof GMap=='undefined')google.load("maps","2",{language:"ja_JP",callback:mapsLoaded}); 950 951 // init member 952 var _t=this,i; 953 // initial instance object 954 _t.locArray=[],_t.locArray2=[],_t.locArray_u={},_t.locArray2_u={},_t.iconA=[],_t.iconO={},_t.dMarkerO={}; 955 _t.kinds={marker:GMarker,polyline:GPolyline,polygon:GPolygon,xml:GGeoXml}; // If this failed, maybe GMap didn't loaded? 956 for(i in _t.kinds) 957 if(i in _t)throw 'Error: ['+i+'] is already a member of me!'; 958 else _t[i]={}; 959 960 961 // 調整 GLatLng 的顯示 962 GLatLng.prototype.toS=function(p){ 963 if(!p)p=_t.precision||0; 964 return Number(this.lat()).toFixed(p)+','+Number(this.lng()).toFixed(p); 965 }; 966 GLatLng.prototype.toString=function(p){return '('+this.toS(p)+')';}; 967 968 969 /* 970 http://blog.wctang.info/2007/07/use-google-map-api-without-api-key.html 971 Geocode 查詢每天有 50000 次的限制 使用 Geocoder 就是要連到 Google 去做查詢,而現在 Google 在做 Geocode 查詢時會在 Server 端做 API key 的檢查,這個就躲不掉了 972 http://blog.wctang.info/2007/07/use-google-map-geocoder-without-api-key.html 973 974 975 */ 976 if(GBrowserIsCompatible()&&!_t.geocoder) 977 with(_t.geocoder=new GClientGeocoder()) 978 setCache(null), // disable cache, 因為找到的都被管控了。 979 setBaseCountryCode('tw'); // 語系 980 981 //_t.readLoc(); 982 _t.initMap.apply(_t,arguments);//return _t.initMap.apply(_t,arguments); 983 }; 984 985 986 // class public ----------------------------------- 987 988 989 // prototype ----------------------------------- 990 _.prototype={ 991 992 // 這些函數可重寫 993 notFound:function(address,data){ 994 return 1;//throw 'Address ['+address+'] not found!'; 995 }, 996 // 增加 overlay 後 997 runAfterAdd:function(obj,type,data,name){}, 998 // 移除 overlay 後 999 runAfterRemove:function(obj,type){}, 1000 // 按 overlay 時 1001 runOnClick:function(obj,type){}, 1002 1003 precision:6, // 精度,算到小數點下第幾位。GMap 2008:6 1004 1005 defaultZoom:14, // 預設縮放 1006 1007 /* 1008 map, // GMap obj 1009 1010 TODO: 1011 use GMarkerManager, http://code.google.com/apis/maps/documentation/overlays.html#Marker_Manager 1012 1013 1014 //handle array: 1015 marker={'lat,lng':GMarker}, // GMarker 地圖標記 1016 polyline={points:GPolyline}, // GPolyline 折線 1017 polygon={points:GPolygon}, // GPolygon 多邊形 1018 xml={URL:GGeoXml}, // GGeoXml: xml/kml 1019 */ 1020 kinds:{}, 1021 supportKind:function(k){ 1022 return k?k in this.kinds:this.kinds; 1023 }, 1024 1025 getKind:function(o){ 1026 for(var i in this.kinds) 1027 if(o instanceof this.kinds[i])return i; 1028 }, 1029 1030 1031 // 讀入先前 catch 的經緯度,存loc而不必每次search 1032 readLoc:function(){ 1033 var _t=this,t,i=0,l,a; 1034 if(!_t.locFP)_t.locFP='map_loc.dat'; // 紀錄 LatLng/地址 可供 searchPoint() 使用 1035 // GDownloadUrl(url,callback) 1036 try{t=getU(_t.locFP);}catch(e){} 1037 _t.adr_to_loc={}; 1038 if(!t||!(t=t.replace(/\r/g,'').split('\n')).length)return; 1039 1040 sl('Get '+t.length+' catched address records from ['+_t.locFP+'].'); 1041 for(;i<t.length;i++) 1042 if((a=t[i].split(' ')).length>1 && (l=a[0].split(',')).length==2) 1043 _t.adr_to_loc[a[1]]=new GLatLng(l[0],l[1]) 1044 //,sl('readLoc: ['+a[1]+'] '+_t.adr_to_loc[a[1]]) 1045 ; 1046 else sl('readLoc: error data: '+t[i]); 1047 }, 1048 1049 // ** important ** 這邊不能作 object 之 initialization,否則因為 object 只會 copy reference,因此 new 時東西會一樣。initialization 得在 _() 中作! 1050 // locArray[]=[lat,lng,adr] sort by lat 給 writeLoc() & getNeighbor() 用,僅包含需要 search 的。 1051 locArray:[], 1052 // 寫入 catched 的經緯度 1053 writeLoc:function(s){ 1054 var _t=this,i,t=[],l,a=_t.precision,b,c; 1055 //sl('writeLoc: We will write data to ['+_t.locFP+'].'); 1056 if(!_t.locFP)return; 1057 1058 for(i in _t.adr_to_loc) 1059 if(l=_t.adr_to_loc[i])try{ 1060 if(isNaN(b=Number(l.lat()))||isNaN(c=Number(l.lng())))throw new Error(1,'經緯度非數字'); 1061 t.push([b.toFixed(a),c.toFixed(a),i]); 1062 }catch(e){sl('writeLoc: Error: '+e.message+': ['+l+'] '+i+', ('+l.lat()+','+l.lng()+')');} 1063 1064 sl('writeLoc: '+_t.locArray.length+'→'+t.length); 1065 // 不相同時才作處理 1066 if(t.length!=_t.locArray.length){ 1067 t.sort(function(l,r){return l[0]-r[0]||l[1]-r[1];}); 1068 for(a=_t.locArray=[],b=_t.locArray_u={},c=[],i=0;i<t.length;i++) 1069 if(l=t[i]){ 1070 if((l[0]+','+l[1]) in b)sl('writeLoc: 重複住址@ '+l[0]+','+l[1]+': '+b[l[0]+','+l[1]][2]+' , '+l[2]); 1071 a.push(b[l[0]+','+l[1]]=l); 1072 c.push(l[0]+','+l[1]+' '+l[2]); 1073 //sl('writeLoc: '+i+'/'+t.length+' '+c[c.length-1]); // 多!! 1074 } 1075 //sl('writeLoc: '+(typeof simpleWrite)+','+_t.locFP); 1076 if(typeof simpleWrite=='function'){ 1077 c=c.join('\n'); 1078 if(typeof simpleRead=='function' && simpleRead(_t.locFP,'utf-8')==c) 1079 sl('writeLoc: 欲寫入之內容('+c.length+' chars)與標的檔相同。檔案並未變更。'); 1080 else 1081 //sl('writeLoc: Write '+c.length+' chars to ['+_t.locFP+'].'), 1082 simpleWrite(_t.locFP,c,'utf-8'); 1083 }//else sl('writeLoc: <em>Warning: function.js is not included?</em>'); 1084 } 1085 if(s)sl('<textarea>'+t.join('\n')+'</textarea>'); 1086 return t; 1087 }, 1088 // locArray2[]=[lat,lng,adr] sort by lat 給 getNeighbor() 用,包括所有不需要 search 的地址。 1089 locArray2:[], 1090 locArray_u:{},locArray2_u:{}, // 預防重複: locArray_u['lat,lng']=obj of locArray or locArray2 1091 /* 取得鄰近的地點: 經緯度, 最大距離(km) http://blog.ben.idv.tw/2007/06/blog-post.html http://hk.geocities.com/hk_weather/big5/others/calculators.html http://blog.xuite.net/joy715/blog/9285691 http://iask.sina.com.cn/b/6263160.html 1092 mapO.getNeighbor([22.620096,120.333381],"sl(n[i][1][2]);"); 1093 return: 1094 f.d: 距離(km) 1095 f.c: 最多取用點數,<=0:全取,未設:default 1096 f.s: 最後時選取與否的篩選設置之函數 傳回數值越大越後面 1097 f.D: 計算距離之函數,將用來比較 1098 default [ [較準確的距離, [lat,lng,adr]],.. ] 1099 求得較大概的距離(以距離平方比計算,比較快) 1100 [ [距離, [lat,lng,adr]],.. ] f.D=function(p,l){var a=l.lat()-p[0],b=l.lng()-p[1];return a*a+b*b;} 1101 1102 f.f: 對選出之 spot 作最後處置之函數 1103 default [ [較準確的距離, [lat,lng,adr]],.. ] 1104 傳回地址 [ adr1, adr2,.. ] f.f= 'n[i]=n[i][1][2];' 1105 傳回 obj [ [lat,lng,adr],.. ] f.f= 'n[i]=n[i][1];' 1106 求得較準確的距離 [ [距離, [lat,lng,adr]],.. ] f.f= 'n[i][1]=l.distanceFrom(n[i][1]);' 1107 */ 1108 getNeighbor:function(l,f){ 1109 var _t=this,lat,lng,i,n=[],p=function(A){ 1110 // 計算最接近上限mLat之loc 1111 // c: 誤差 1112 var i=0,j=A.length,a,b,c=f._d,mLat=lat-c; 1113 if(!j)return; 1114 //sl(mLat+'~'+(lat+c)); 1115 do{ 1116 //sl(Math.floor((i+j)/2)+'/'+A.length+','+A[a=Math.floor((i+j)/2)]); 1117 b=A[a=Math.floor((i+j)/2)][0]; 1118 if(b>mLat)j=a;else if(b<mLat)i=a; 1119 }while(i<j-1&&Math.abs(b-mLat)>c); 1120 //sl('start: from ['+a+'/'+A.length+'] '+A[a].join(':')+' to '+(lat+c));var tt=[]; 1121 for(i=a,mLat=lat+c,a=lng-c,b=lng+c;i<A.length&&A[i][0]<mLat;i++) 1122 if(/*tt.push('- '+A[i]+': '+a+','+c+','+b),*/c=A[i][1],a<c&&c<b) 1123 //n.push([j=f.D(A[i],l),A[i]]),sl('distance: '+j.toFixed(2)+' to '+A[i]); 1124 n.push([f.D(A[i],l),A[i]]); 1125 //sl(tt.join('<br/>')); 1126 }; 1127 if(typeof l=='string')l=l.split(','); 1128 //if(typeof l=='function'&&l.lat&&l.lng)lat=typeof l.lat=='function'?l.lat():l.lat,lng=typeof l.lng=='function'?l.lng():l.lng; 1129 if(l instanceof GLatLng)lat=l.lat(),lng=l.lng(); 1130 else lat=l[0],lng=l[1],l=new GLatLng(lat,lng); 1131 // 這邊起 l 為原始點之 GLatLng 1132 if(typeof f!='object') 1133 f=isNaN(f)?{f:f}:{d:f}; 1134 f._d=(f.d>0?f.d:20)/111; // 1度的實際長度~111公里。 1135 if(!f.D)f.D=function(p,l){ 1136 //var a=lat-p[0],b=lng-p[1];return a*a+b*b; // 大概的,比較快。 1137 return l.distanceFrom(new GLatLng(p[0],p[1])); // real distance 1138 }; 1139 1140 //sl(lng+', '+lat+'; '+f._d); 1141 _t.writeLoc(); 1142 p(_t.locArray); 1143 _t.locArray2.sort(function(l,r){return l[0]-r[0]||l[1]-r[1];}); 1144 //sl('['+_t.locArray2.length+']<br/>* '+_t.locArray2.join('<br/>* ')); 1145 p(_t.locArray2); 1146 //sl('Get '+n.length+' records near ('+lat+','+lng+').'); 1147 1148 // 由近至遠 sort 1149 if(typeof f.s=='undefined')f.s=function(l,r){return l[0]-r[0];}; // l, r: [distance by f.D,[lat,lng,adr]] 1150 if(f.s)n.sort(f.s); 1151 //for(i=0;i<n.length;i++)sl('getNeighbor '+i+': '+n[i][0]+' '+n[i][1][2]); 1152 if(typeof f.c=='undefined'||f.c&&!isNaN(f.c)&&n.length>f.c) 1153 n=n.slice(0,f.c>0?f.c:9); // 預設取 9 個 1154 1155 if(typeof f.f=='string')f.f=new Function('n','i','l',f.f); 1156 //sl('Run: [~'+n.length+'] by '+f.f); 1157 if(typeof f.f=='function') 1158 for(i=0;i<n.length;i++)f.f(n,i,l); 1159 1160 return n; 1161 }, 1162 /* 1163 http://econym.googlepages.com/geomulti.htm 1164 http://econym.googlepages.com/didyoumean.htm 1165 enum GGeoStatusCode http://code.google.com/intl/zh-CN/apis/maps/documentation/reference.html#GGeoStatusCode 1166 */ 1167 GeoStatus:function(c){ 1168 var m=this.GeoStatusM; 1169 if(!m){ 1170 this.GeoStatusM=m={ 1171 G_GEO_SERVER_ERROR:'伺服器錯誤。', 1172 G_GEO_MISSING_QUERY:'輸入空地址。', 1173 G_GEO_UNKNOWN_ADDRESS:'找不到指定地址的對應地理位置。可能地址比較新,無法解析地址,地址不正確,或者缺少該地址的數據。', 1174 G_GEO_UNAVAILABLE_ADDRESS:'由於合法性或合同原因,無法返回給定地址的地理位置信息。', 1175 G_GEO_BAD_KEY:'給定的密鑰無效或與給定的 host ('+window.location.host+') 不匹配。', 1176 G_GEO_TOO_MANY_QUERIES:'給定的密鑰超出了 24 小時的請求限制。', 1177 //404:'沒找到網頁', 1178 403:'Probably an incorrect error caused by a bug in the handling of invalid JSON', 1179 G_GEO_SUCCESS:'查詢成功' 1180 }; 1181 var i,v; 1182 for(i in m)try{ 1183 if(!isNaN(v=eval(i))&&v!=i)m[v]=m[i]; 1184 }catch(e){} 1185 } 1186 return m[c]||''; 1187 }, 1188 /* mapO.getLocations('taiwan',function(r){}); 1189 arguments: 1190 address, function([[lat,lng,adr], ..]), data object 1191 address, [deal function, (預設0: 傳入 [[lat,lng,adr], ..], 1: 傳入 GClientGeocoder.getLocations)], data object 1192 1193 http://code.google.com/apis/maps/documentation/services.html#Geocoding_Structured 1194 http://code.google.com/apis/kml/documentation/kmlreference.html#placemark 1195 http://www.step1.cn/googleapi/map/kml.htm#Placemark 1196 1197 to use: 1198 mapO.getLocations('宿舍',function(r){for(var i=0;i<r.length;i++)sl(i+'/'+r.length+' '+r[i]);}); 1199 */ 1200 getLocations:function(adr,func,d){ 1201 var _t=this,_f=arguments.callee,a 1202 // country code 1203 ,cc={TW:'台灣',US:'United States',JP:'日本',CN:'中国',KR:'大韓民國',KP:'朝鮮',UK:'United Kingdom'} 1204 ,ga=function(p){ // 從 Placemark 得到住址(address)資料 1205 var c,a,b; 1206 if(c=p.AddressDetails.Country){ 1207 b=c.CountryNameCode; 1208 a=b in cc?[cc[b]]:[]; 1209 if(c=c.AdministrativeArea){ 1210 if(b=c.AdministrativeAreaName)a.push(b); 1211 if(c=c.SubAdministrativeArea){ 1212 if(b=c.SubAdministrativeAreaName)a.push(b); 1213 if(c=c.Locality){ 1214 if(b=c.PostalCode)a.unshift('['+b.PostalCodeNumber+']'); 1215 if(b=c.LocalityName)a.push(b); 1216 if((c=c.Thoroughfare)&&(b=c.ThoroughfareName)) 1217 a.push(b); 1218 } 1219 } 1220 } 1221 a=a.join(' '); 1222 } 1223 return p.address?p.address+' ('+a+')':a; 1224 }, 1225 // 預設代為處理函數組 1226 f=[ 1227 // 代為處理傳入 [lat,lng,adr] 1228 function(r){ 1229 _f.errno=r.Status.code; 1230 if(r instanceof GLatLng) 1231 r=[[r.lat(),r.lng(),adr]]; 1232 else if(r.Status.code==G_GEO_SUCCESS){ 1233 //sl('getLocations: Get '+r.Placemark.length+' place(s) of ['+r.name+'].'); 1234 //sl('getLocations: [0]: '+r.Placemark[0].name); 1235 var i=0,n=r.name,p=r.Placemark,l,a; 1236 for(r=[];i<p.length;i++) 1237 a=ga(p[i])||n+'('+i+')', 1238 //sl('getLocations: ('+p[i].Point.coordinates+') '+a), 1239 l=p[i].Point.coordinates,r.push([l[1],l[0],a]), 1240 _t.adr_to_loc[a]=new GLatLng(l[1],l[0]); 1241 }else r=[]; 1242 return func(r); 1243 } 1244 , 1245 // 代為處理傳入 Placemark 1246 function(r){ 1247 _f.errno=r.Status.code; 1248 if(r instanceof GLatLng) 1249 r={Status:{code:G_GEO_SUCCESS},Placemark:[{Point:{coordinates:[r[0],r[1]]}}]}; 1250 else if(r.Status.code==G_GEO_SUCCESS){ 1251 //sl('getLocations: find '+r.Placemark.length+' records, '+r.Placemark[0].Point.coordinates+': '+r.Placemark[0].address); 1252 //if(r.Placemark.length==1){var l=r.Placemark[0].Point.coordinates;_t.adr_to_loc[r.Placemark[0].address]=new GLatLng(l[1],l[0]);} 1253 for(var i=0,n=r.name,p=r.Placemark,l;i<p.length;i++)l=p[i].Point.coordinates,_t.adr_to_loc[ga(p[i])||n+'('+i+')']=new GLatLng(l[1],l[0]); 1254 }//else sl('getLocations: search ['+adr+'] fault: ['+r.Status.code+'] '+_t.GeoStatus(r.Status.code)); 1255 return func(r); 1256 } 1257 ]; 1258 1259 if(func instanceof Array) 1260 a=func[1], 1261 f= typeof a=='function'?a 1262 :typeof a=='number' && f[a]? f[a] 1263 :f[0], 1264 func=func[0]; 1265 else f=f[0]; 1266 1267 return _t.getLatLng(adr+='',[f,function(){return _t.geocoder.getLocations(adr,f);}],d); 1268 }, 1269 1270 // 直接手動設定 1271 setLatLng:function(adr,lat,lng){ 1272 if(!(lat instanceof GLatLng))lat=new GLatLng(lat,lng); 1273 this.adr_to_loc[adr]=lat; 1274 sl('setLatLng: '+lat+' '+adr); 1275 return lat; 1276 }, 1277 1278 // 經緯度 RegExp 1279 LatLngR:/^\s*(\d{1,3}(\.\d+)?)\s*,\s*(\d{1,3}(\.\d+)?)\s*$/, 1280 1281 /* 未設定 func 則僅回傳 catched 的位置 1282 You can define your method by .f(adr,c), for example: search by specified SQL server. 1283 1284 TODO: 1285 繼承 Geocoding cache 1286 */ 1287 getLatLng:function(adr,func,d){ // string address, (function(GLatLng) | [func:function(GLatLng), deal_func:function(GLatLng, address)]), data object 1288 //if(!adr)return; 1289 var _t=this,m,a,f,c=function(p){ 1290 if(!p)sl('getLatLng: Search failed: '+adr); 1291 if(p)_t.adr_to_loc[adr]=p; 1292 return func(p,adr)||p; 1293 }; 1294 1295 if(func instanceof Array) 1296 f=func[1],func=func[0]; 1297 1298 //sl('getLatLng: search '+adr); 1299 // 檢測是否為經緯度 1300 if(m=adr.match(_t.LatLngR)){ 1301 if(a=(d&&d.description||adr).replace(/<[/]?([bh]r|p)[^>]*>/ig,'\n').match(/[^\r\n]+[市區街路][^\r\n]+/)) 1302 //sl('('+m[1]+','+m[3]+') ['+a[0]+']'), 1303 if(!((m[1]+','+m[3]) in _t.locArray2_u))_t.locArray2.push(_t.locArray2_u[m[1]+','+m[3]]=[m[1],m[3],a[0]]); 1304 m=new GLatLng(m[1],m[3]); 1305 return func?func(m):m; 1306 // 搜尋已知地址 1307 }else if((m=_t.adr_to_loc) && (m=m[adr]))//sl('getLatLng: deal adr_to_loc['+adr+']='+m[adr]+' get '+(func?c(m):m)/*+' by '+func*/), 1308 return func?c(m):m; 1309 // 搜尋未知地址 1310 else if(func) 1311 //sl('<em>Not catched: '+adr+'</em>'), 1312 return _t.geocoder.getLatLng(adr,typeof f=='function'?function(m){f(m,adr);}:c); // 原來需要用 arguments.callee.f,但若已經用 var 定義則可直接使用。 1313 }, 1314 1315 /* 1316 d={ 1317 name:'', // 這邊 name 被當作 id, title 1318 description:'HTML', 1319 type:'', 1320 data:['',''] 1321 //選用 optional: 1322 htm:'HTML' / function(obj){return 'HTML';}, 1323 //尚未用到︰ 1324 link:'', 1325 }; 1326 */ 1327 add:function(d,force){ 1328 if(!d||typeof d!='object')return this; 1329 var _t=this,o=_t.supportKind(d.type); 1330 if(!o){_t.searchPoint(d);return this;} 1331 1332 //if(!(d.type in _t))_t[d.type]={}; 1333 var _S=_t[d.type],_m=this.map,a; 1334 //if(typeof _S!='object')sl('add: typeof ['+d.type+'] = '+(typeof _S)); 1335 if((d.name in _S)&&!force)return this; // 已存在 1336 1337 o=_t.kinds[d.type]; 1338 if(d.type=='marker'){ 1339 o=new o(new GLatLng(d.data[0],d.data[1]),_t.getMarkerO(d)); 1340 //if(d.zIndexP)o._zIndexProcess=o._zIndexProcess,o.zIndexProcess=d.zIndexP; // ** 可以利用 zIndexP 來在 infowindow is opened 時設定 z-index.. 沒用 @ 2008/6/30 19:43:43 1341 }else a={points:d.data[0],levels:d.data[1],numLevels:4,zoomFactor:16}, 1342 o=new o.fromEncoded(d.type=='polyline'?a:{polylines:[a],fill:true,outline:true});//geodesic:true Geodesic means 'along great circle' 1343 1344 _t._add(o,d); 1345 1346 return this; 1347 }, 1348 searchPoint:function(adr,name,description){ 1349 var _f=arguments.callee,_t=this,type='marker',_M=_t[type],_m=_t.map,latlng,d; 1350 if(typeof adr=='object')d=adr,adr=adr.type;else d={type:adr,show:_f.show}; // 預設 searchPoint.show 1351 if(!d.name)d.name=name||adr; 1352 if(typeof d.description=='undefined') 1353 if(description)d.description=description; 1354 else if(d.name!=adr)d.description=adr; 1355 if(!d.type)return; 1356 if(isNaN(d.retry)&&!_t.geocoder.getCache())d.retry=2; // 找不到時重試次數 1357 1358 try{ 1359 if(adr in _M) 1360 //sl('We already have ['+adr+']'), 1361 _t.show(_M[adr],type); 1362 else _t.getLatLng(adr+='',function(point){ 1363 if(!point){ 1364 if(d.retry){ 1365 //sl('try once more('+d.retry+'): ['+adr+']'); 1366 d.retry--,_f.call(_t,d);return false; 1367 }else{ 1368 //sl('searchPoint: not found function: '+_t.notFound); 1369 return _t.notFound(adr,d); 1370 } 1371 }else{ 1372 if(adr in _M)return; // 可能經過太久才被 load? 1373 1374 // ** 注意:這邊沒設 _M[adr]=_M[point.toUrlValue(_t.precision)] 1375 var p=new GMarker(latlng=point,_t.getMarkerO(d)); 1376 if(!d.name)d.name=p+''; 1377 //sl('found '+point+' '+d.name+', icon: '+p.getIcon().iconSize); 1378 //point='loc: '+point; 1379 if(typeof d.description=='undefined')d.description=point; 1380 else if(d.description==adr)d.description+='<br/>'+point; 1381 //_M=_M[adr]; 1382 if(!('address' in p))p.address=adr;else throw 'GMarker.address was used: ['+p.address+']!'; 1383 //sl('Last add '+adr+'..'); 1384 _t._add(p,d,type); 1385 } 1386 },d); 1387 }catch(e){sl('searchPoint: Error: '+adr+', '+_M+': '+e.message);}//throw e; 1388 return latlng; 1389 }, 1390 // private: 註冊 o 成為內容 d={},並設定 click 等 event 1391 _add:function(o,d,type){ 1392 if(!o)return; 1393 if(!d)d=o; 1394 if(!type)type=d.type; 1395 var _t=this,_S=_t[type],_m=this.map; 1396 1397 //if(d.name)_S[d.name]=o; // 或許已經設定過了,這邊就需要跳過。 1398 if(((d.name||d)+'') in _S) 1399 sl('_add: Warning: Type '+type+' 已存在 ['+(d.name||d)+']'+(_S[d.name||d].getLatLng?' '+_S[d.name||d].getLatLng():'')+('address' in _S[d.name||d]?' '+_S[d.name||d].address:'')+'!' 1400 //+'<br/>_add: 將以 ['+(o.name||d.name||d)+']'+(o.getLatLng?' '+o.getLatLng():'')+(o.address?' '+o.address:'')+' 覆寫。' 1401 ); 1402 _S[d.name||d]=o; // 必設!! 1403 1404 if(_m)_m.addOverlay(o);//_t._addOverlay(o);// 1405 //if(o.getIcon)sl('_add: show '+o.getIcon().iconSize+' '+o.getIcon().image); 1406 o.name=d.name,o.dscr=d.description; // GMarker 中這兩個本來就有被用,偵測也只會發現已使用。 1407 // another way to add tooltip: GControlPosition 1408 if(!('sHtm' in o)){ 1409 if('htm' in d)o.sHtm=typeof d.htm=='function'?d.htm.call(d,o,type):d.htm; 1410 else o.sHtm=(d.name?'<em>'+d.name+'</em>'+(d.description?'<br/>':''):'')+(d.description||''); 1411 }else throw '['+type+'].sHtm was used: ['+o.sHtm+']!'; 1412 if(!('sHtmF' in o)){ 1413 if('htmF' in d) 1414 o.sHtmF=typeof d.htmF=='function'?d.htmF.call(d,o,type):d.htmF; 1415 }else throw '['+type+'].sHtmF was used: ['+o.sHtm+']!'; 1416 // openInfoWindowTabs: http://www.geocodezip.com/mapXmlTabsPlus.asp 1417 GEvent.addListener(o,"click",function(e){ 1418 _t.showWindow(o); 1419 _t.runOnClick(o,type,e&&e.target||window.event&&window.event.srcElement); 1420 }); 1421 if(d.show)_t.show(o,type); 1422 _t.runAfterAdd(o,type,d,d.name||d); 1423 }, 1424 _addOverlay:function(o){ 1425 var _t=this,_m=_t.map; 1426 if(!_t._aa)_t._aa=[]; 1427 if(o){_t._aa.push(o);return;} 1428 var i; 1429 while(i=_t._aa.shift()) 1430 _m.addOverlay(i); 1431 }, 1432 1433 1434 // icon setup 1435 defaultIconIndex:0, 1436 iconA:[], 1437 iconO:{}, 1438 icon:function(index){ 1439 var _t=this; 1440 if(index instanceof Array){ 1441 // 設定 icon 1442 _t.iconA=[]; 1443 for(var a,i=0,p,u;i<index.length;i++) 1444 if(u=index[i]){ 1445 if(typeof u=='string')u={image:u}; 1446 if(u instanceof Object){ 1447 _t.iconA.push(a=new GIcon(u.icon||_t.iconA[_t.defaultIconIndex]||G_DEFAULT_ICON)); 1448 //a=new GIcon(u.icon||_t.iconA[_t.defaultIconIndex]||G_DEFAULT_ICON); 1449 for(p in _t.iconO) // default first 1450 //sl('icon: set icon['+(_t.iconA.length-1)+'].'+p+'='+_t.iconO[p]), 1451 a[p]=_t.iconO[p]; 1452 if('temp' in u){ // template 2 1453 for(p in u.temp) 1454 //sl('icon: template set icon['+(_t.iconA.length-1)+'].'+p+'='+u.temp[p]), 1455 a[p]=u.temp[p]; 1456 delete u.temp; 1457 } 1458 for(p in u) // user set last 1459 //sl('icon: specified set icon['+(_t.iconA.length-1)+'].'+p+'='+u[p]), 1460 a[p]=u[p]; 1461 //_t.iconA.push(new GIcon(a)); 1462 }else _t.iconA.push(u); 1463 } 1464 return _t.iconA.length; 1465 } 1466 1467 if(index instanceof Object){ 1468 //sl('icon: set default icon option'); 1469 for(i in index) 1470 //sl('icon: set default ['+i+']=['+index[i]+']'), 1471 _t.iconO[i]=index[i]; 1472 return; 1473 } 1474 1475 // return icon[index] 1476 if(isNaN(index)||index<0||index>=_t.iconA.length)index=_t.defaultIconIndex; 1477 //sl('icon: return icon['+index+'] '+(_t.iconA[index]?_t.iconA[index].iconSize+' '+_t.iconA[index].image:'G_DEFAULT_ICON')); 1478 return _t.iconA[index]||G_DEFAULT_ICON; 1479 }, 1480 1481 dMarkerO:{}, // default marker option 1482 getMarkerO:function(mo,setMO){ // setMO: set default, 1: add, 2:reset 1483 var _t=this,i,a={icon:1,title:1,zIndexProcess:1,draggable:1}; // class GMarkerOptions 1484 _t.dMarkerO.icon=_t.icon(); 1485 if(setMO){ 1486 if(setMO==2)_t.dMarkerO={}; 1487 setMO=_t.dMarkerO; 1488 }else{ 1489 // 複製一份 1490 setMO={}; 1491 for(i in _t.dMarkerO) 1492 //sl('getMarkerO: from default ['+i+']=['+_t.dMarkerO[i]+']'), 1493 setMO[i]=_t.dMarkerO[i]; 1494 } 1495 if(mo instanceof Object) 1496 for(i in a) 1497 if(a[i]&&typeof mo[i]!='undefined') 1498 //sl('getMarkerO: set ['+i+']=['+mo[i]+']'), 1499 setMO[i]=mo[i]; 1500 //sl('getMarkerO: icon: '+setMO.icon.iconSize+' '+setMO.icon.image); 1501 return setMO; 1502 }, 1503 1504 /* 增加自己控制的 marker,會自動顯現,但不會列入管控,得自己設定。 1505 usage: 1506 mapO.addMarker(dLoc.tw,{draggable:true}); 1507 */ 1508 addMarker:function(loc,opt){ 1509 var _t=this,_m=_t.map,m; 1510 if(_m){ 1511 if(loc instanceof Array)loc=new GLatLng(loc[0],loc[1]); 1512 m=new GMarker(loc,_t.getMarkerO(opt)); 1513 //sl('addMarker icon: '+_t.getMarkerO(opt).icon.iconSize+' '+_t.getMarkerO(opt).icon.image); 1514 //sl('addMarker iconSize: '+_t.getMarkerO(opt).iconSize); 1515 _m.addOverlay(m); 1516 } 1517 return m; 1518 }, 1519 1520 1521 // f={p:position, m:method(pan/panBy/set), z:zoom} 1522 setCenter:function(f){ 1523 var _m=this.map; 1524 if(f instanceof GLatLng||!(f instanceof Object))f={p:f}; 1525 1526 //sl('setCenter: setZoom ['+(f.z||null)+'] @ '+f.p+' by method ['+(f.m||'setCenter')+'].'); 1527 if(!isNaN(f.z))_m.setZoom(f.z); 1528 if(f.p){ 1529 if(f.p instanceof Array)f.p=new GLatLng(f.p[0],f.p[1]); 1530 if(f.m=='pan')_m.panTo(f.p); 1531 else if(f.m=='panBy')_m.panBy(f.p); 1532 else _m.setCenter(f.p); 1533 } 1534 1535 return _m.getCenter(); 1536 }, 1537 1538 // zoom above 19 You can set zoom up to 30 by using setCenter() not by setZoom() or zoomIn() firefox: 45.1238,-123.1138 http://esa.ilmari.googlepages.com/highres.htm 1539 /* 1540 eval('err_noImage=p(10121);',mapO.map); 1541 sl(err_noImage); 1542 */ 1543 zoom:function(z){ 1544 var _t=this,_m=_t.map,m; 1545 if(typeof z=='string'&&(m=z.match(/^[+-]/)))z=_m.getZoom()+(m[0]=='+'?z:-z); 1546 if(z)_m.setZoom(z);//try{_m.setCenter(_m.getCenter(),z);}catch(e){} // 中文中, enableContinuousZoom()? 這麼搞會出錯 1547 return _m.getZoom(); 1548 }, 1549 // show, or focus. f={noCenter:false, redraw: false} 1550 show:function(name,type,f){ 1551 var _t=this,_S=_t[type],_m=_t.map,inC; // inC: in control 1552 if(typeof name=='string') 1553 if(name in _S)_S=_S[name],inC=1; 1554 else _S=0; 1555 else _S=name; 1556 if(typeof _S!='object'||!_S)return; 1557 1558 if(_S.isHidden&&_S.isHidden())_S.show(); 1559 if(typeof f!='object')f={noCenter:f}; // default: don't set to center 1560 if(!f.noCenter){ 1561 var p=_t.getPoint(_S,type); 1562 //sl('show: center= '+p); 1563 if(_m){ 1564 _m.setCenter(p); 1565 if(_m.getZoom()<9)_m.setZoom(_t.defaultZoom); 1566 if(inC)_t.showWindow(_S,p); // 未管控就 showWindow 會有奇妙的結果。 1567 } 1568 } 1569 if(f.redraw && _S.redraw)_S.redraw(true); // Front/back order of markers can be messed simply by moving them in south-north direction. (v1) http://koti.mbnet.fi/ojalesa/exam/anim_v2.html 1570 1571 return _t; 1572 }, 1573 1574 // show HTML window (obj, point) o.sHtmF=show HTML flag: {maxContent:'', ..}: see class GInfoWindowOptions 1575 showWindow:function(o,p){ 1576 //sl('showWindow: '+(p||o.openInfoWindowHtml)); 1577 if(typeof o.openInfoWindowHtml=='function') 1578 o.openInfoWindowHtml(o.sHtm,o.sHtmF); // enableMaximize() 1579 else this.map.openInfoWindowHtml(p||this.getPoint(o),o.sHtm,o.sHtmF); 1580 }, 1581 1582 // get the GLatLng of the object 1583 getPoint:function(o,type){ 1584 if(!type)type=this.getKind(o); 1585 //sl('getPoint: ['+type+']'+o.name); 1586 if(type=='marker'&&typeof o.getLatLng=='function')return o.getLatLng(); 1587 1588 if(typeof o.getBounds=='function') 1589 return o.getBounds().getCenter(); 1590 1591 if(typeof o.getCenter=='function') 1592 return o.getCenter(); 1593 1594 if(typeof o.getVertexCount=='function') 1595 return o.getVertex(Math.floor(o.getVertexCount()/2)); 1596 }, 1597 1598 getZoom:function(o,type){ 1599 if(!type)type=this.getKind(o); 1600 //sl('getPoint: ['+type+']'+o.name); 1601 1602 if(typeof o.getBounds=='function') 1603 return this.getBoundsZoomLevel(o.getBounds()); // 得到適當的 zoom 1604 1605 //if(type=='marker')return _t.defaultZoom; 1606 return _t.defaultZoom; 1607 }, 1608 1609 1610 initMap:function(id,latlng,f){ // container, center, other initial setting flags 1611 var _t=this,_m,a; 1612 // 檢查當前瀏覽器是否支持地圖 API 庫 1613 if(GBrowserIsCompatible()){ 1614 // 指定GMap使用的圖層 @ id 1615 if(typeof id=='string')id=document.getElementById(id); 1616 if(!id)return _t; 1617 _t.canvas=id; // container object 1618 1619 if(!f)f={}; 1620 if(!f.size) 1621 f.size=f.x&&f.y?[f.x,f.y]:[640,320]; 1622 if(f.size instanceof Array)f.size=new GSize(f.size[0],f.size[1]); 1623 1624 _m=_t.map=new GMap2(id,f);//=new google.maps.Map2(); 1625 // 設定中心點座標 1626 _m.setCenter(latlng||new GLatLng(0,0),7); // default center. 1627 //_m.setMapType(G_HYBRID_MAP); 1628 _m.addMapType(G_PHYSICAL_MAP); // 地形圖 1629 _m.addMapType(G_SATELLITE_3D_MAP); // with the Google Earth Browser Plug-in 1630 1631 // 控制元件 客制化: http://julian.norway.idv.tw/index.php/archives/322 1632 //_m.addControl((new GHierarchicalMapTypeControl()).addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", true)); 1633 //_m.removeMapType(G_HYBRID_MAP); 1634 _m.addControl(a=_t.overviewMap=new GOverviewMapControl(new GSize(_m.getSize().width/2.5,_m.getSize().height/2))); // 可折疊的縮小圖 1635 a.hide(); // show(), hide(). 1636 //a.getOverviewMap().addControl(new GMenuMapTypeControl(1)); must use setTimeout: getOverviewMap() is not available until after the module has loaded. 1637 _m.addControl(new GLargeMapControl()); // 加入地圖縮放工具 1638 _m.addControl(new GMenuMapTypeControl(1));//GMapTypeControl(1) // 切換地圖型態的按鈕 1639 _m.addControl(new GScaleControl()); // 地圖比例尺 1640 _m.enableScrollWheelZoom(); 1641 _m.enableContinuousZoom(); // 平滑放大 1642 1643 GEvent.addListener(_m,'mouseover',function(){_m.showControls();}); 1644 GEvent.addListener(_m,'mouseout',function(){_m.hideControls();}); 1645 }else{ 1646 sl('<em>抱歉,您的瀏覽器不支援 Google Maps!</em>'); 1647 } 1648 return _t; 1649 }, 1650 1651 1652 1653 /* 移除所有管控項 1654 c.f., this.map.clearOverlays() 1655 */ 1656 removeAll:function(type){ 1657 var _t=this,i,o; 1658 if(!type)for(i in _t.kinds) 1659 arguments.callee.call(this,i); 1660 else{ 1661 //sl('removeAll: ('+(typeof type)+') ['+type+'], '+(typeof _t[type])); 1662 //o=[];for(i in _t[type])o.push(i);for(i=0;i<o.length;i++)_t.remove(o[i],type); 1663 for(i in _t[type])_t.remove(i,type); 1664 //_t[type]={}; 1665 } 1666 }, 1667 1668 remove:function(n,type){ 1669 var _S=this[type]; 1670 if(n in _S){ 1671 //sl('remove '+type+' ['+n+']: '+(_S[n].name||_S[n].address||_S[n].dscr)); 1672 this.map.removeOverlay(_S[n]); 1673 delete _S[n]; 1674 this.runAfterRemove(n,type); 1675 } 1676 return this; 1677 }, 1678 1679 // http://econym.googlepages.com/example_context.htm 1680 setContextMenu:function(o){ 1681 var _t=this,_m=_t.map,h; 1682 if(!_m)return; 1683 1684 if(typeof o!='object'){ 1685 h=o; 1686 o=document.createElement('div'); 1687 o.className='gMap_contextMenu'; 1688 o.innerHTML=h; 1689 } 1690 1691 if(_t.contextMenu) 1692 _t.contextMenu.replaceNode(o); 1693 else _m.getContainer().appendChild(_t.contextMenu=o) 1694 ,GEvent.addListener(_m,'singlerightclick',function(p,t){ 1695 _t.clickLatLng=_m.fromContainerPixelToLatLng(_t.clickPoint=p); 1696 var x=p.x,y=p.y,w=_m.getSize().width-o.offsetWidth,h=_m.getSize().height-o.offsetHeight; 1697 if(x>w&&w>0)x=w; 1698 if(y>h&&h>0)y=h; 1699 (new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(x,y))).apply(o); 1700 _t.showContextMenu(1); 1701 }); 1702 1703 _t.showContextMenu(0); 1704 return o; 1705 }, 1706 showContextMenu:function(v){ 1707 var o=this.contextMenu; 1708 if(o)o.style.visibility=v||typeof v=='undefined'?'visible':'hidden'; 1709 }, 1710 1711 // get overlay 1712 getO:function(type,name){ 1713 var s=this[type]; 1714 return name?name in s?s[name]:null:s; 1715 }, 1716 1717 // get name of the type 1718 getOArray:function(type){ 1719 var i,a=[],o=this[type]; 1720 if(o)for(i in o)a.push(i); 1721 return a; 1722 }, 1723 1724 1725 /* 1726 var i,t=[],o; 1727 o=GGeoXml.prototype;//GMap2.prototype 1728 sl('['+(typeof o)+'] '+(o+'').replace(/\n/g,'<br/>')+'<hr/>',1);for(i in o)t.push('['+(typeof o[i])+'] '+i);sl(t.sort().join('<br/>')); 1729 1730 TODO: 1731 GEvent.addListener(map,"addoverlay",function(overlay){if(overlay.name){}}); 1732 */ 1733 loadXML:function(URL){ 1734 var _t=this,x=new GGeoXml(URL); 1735 // .getDefaultCenter(), .getDefaultBounds() 可能是 null 1736 _t.setCenter({p:x.getDefaultCenter(),z:x.getDefaultBounds(),m:'pan'}); 1737 _t.map.addOverlay(x); 1738 return _t.xml[URL]=x; 1739 }, 1740 1741 //resize map 1742 resize:function(x,y){ 1743 with(this.map.getContainer().style) 1744 width=x+'px',height=y+'px'; 1745 }, 1746 1747 // 去除商標, Copyright message 1748 removeTM:function(l){ 1749 var a=this.canvas; 1750 if(!a)return; 1751 a=a.getElementsByTagName('a'),i=a.length,t=1; 1752 //sl('removeTM: '+UnicodeToHTML(document.getElementById('map_canvas').innerHTML)); 1753 for(;i>0&&(t||l);){ 1754 i--; 1755 // http://www.google.com/intl/en_ALL/help/terms_maps.html 1756 if(t && a[i].href.indexOf('terms_maps')!=-1 && a[i].parentNode.tagName.toLowerCase()=='div'){ 1757 //sl('removeTM: remove copyright: '+a[i].href); 1758 //sl('removeTM: remove copyright: '+UnicodeToHTML(a[i].parentNode.innerHTML)); 1759 removeNode(a[i].parentNode,1); // 連這div都刪除會有奇怪現象發生 1760 t=0; 1761 }else if(l && a[i].innerHTML.indexOf('poweredby.png')!=0){ 1762 //sl('removeTM: remove logo: '+UnicodeToHTML(a[i].parentNode.innerHTML)); 1763 removeNode(a[i].parentNode,1); 1764 l=0; 1765 } 1766 } 1767 } 1768 1769 }; // _.prototype= 1770 1771 1772 return _; 1773 })(); // (function(){ 1774 1775 // =================================================== 1776 1777 1778 /* 2008/9-10/1 1779 搜尋用代理工具 1780 1781 usage: 1782 google.load("search","1",{language:"ja_JP",callback:loadSearch}); 1783 function loadSearch(){ 1784 gSearch=new getSearch(function(r,p){ 1785 sl('<a href="'+r.unescapedUrl+'">'+r.title+'</a><br/><div style="margin-left:3em;font-size:.8em;">'+r.content+'</div>'); 1786 }); 1787 } 1788 1789 1790 TODO: 1791 Yahoo! Search BOSS http://developer.yahoo.com/search/boss/ 1792 1793 LocalSearch: 1794 http://www.google.com/uds/samples/apidocs/static-tiles.html 1795 http://code.google.com/apis/ajaxsearch/documentation/reference.html#_class_GlocalSearch 1796 1797 */ 1798 function getSearch(fn,kind){ // deal function, kind: Web/Local 1799 if(!kind)kind='Web'; 1800 var _t=this,_s=typeof google!='undefined'?google.search:0; 1801 if(!_s||!_s[kind+'Search'])return; 1802 _s=_t.searcher=new _s[kind+'Search'](); 1803 1804 if(kind=='Local'){ 1805 //sl('Set center: '+'Taiwan'); 1806 _s.setCenterPoint('台灣');//Taiwan 1807 _s.setResultSetSize(google.search.Search.LARGE_RESULTSET); 1808 //_s.setCenterPoint("93108"); 1809 }else{ 1810 _s.setNoHtmlGeneration(); 1811 //.addSearcher(_s,(new google.search.SearcherOptions()).setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN)); 1812 } 1813 1814 _s.setResultSetSize(google.search.Search.LARGE_RESULTSET); 1815 1816 _s.setSearchCompleteCallback(_t,_t.searchComplete[kind],[_s]); 1817 if(fn)_t.sf=fn; 1818 return _t; 1819 } 1820 getSearch.prototype={ 1821 1822 // country translate 1823 countryT:{Taiwan:'台灣'}, 1824 1825 searchComplete:{ 1826 Local:function(searcher){ 1827 var r=searcher.results,i=0,a,b,j; 1828 if(r&&r.length>0)for(;i<r.length;i++){ 1829 o=r[i],a=o.country; 1830 if(a in this.countryT)a=this.countryT[a]; 1831 o.address=a+o.region+o.city+o.streetAddress; 1832 o.phone=[]; 1833 if(a=o.phoneNumbers) 1834 for(j=0;j<a.length;j++) 1835 o.phone.push((a[j].type?a[j].type+': ':'')+a[j].number); 1836 this.sf(o); 1837 } 1838 /* 1839 var imageUrl = GlocalSearch.computeStaticMapUrl(searcher.results, 350, 400); 1840 document.getElementById("resultsImg").src = imageUrl; 1841 */ 1842 }, 1843 Web:function(searcher){ 1844 var s=searcher,p=s.cursor.currentPageIndex,i=0,r=s.results; 1845 //sl('<hr/>page '+p+':'); 1846 if(r&&r.length)for(;i<r.length;i++) 1847 this.sf(r[i],p); 1848 s.gotoPage(p+1); // 這會一直執行到不能執行為止。(2008/7: 0-3) 1849 } 1850 1851 }, // searchComplete 1852 1853 1854 // deal function 1855 sf:function(r,p){ 1856 }, 1857 1858 s:function(w){ 1859 //sl('getSearch: search ['+w+']'); 1860 if(w)this.searcher.execute(w); 1861 } 1862 1863 }; 1864 1865 1866 1867 1868 1869 1870 1871 1872 return ( 1873 CeL.interact.integrate.map 1874 ); 1875 } 1876 1877 1878 }); 1879 1880