Google Maps Hacks By Schuyler Erle, Rich Gibson ............................................... Publisher: O'Reilly Pub Date: January 2006 Print ISBN-10: 0-596-10161-9 Print ISBN-13: 978-0-59-610161-9 Pages: 366 Table of C ontents | I ndex Want to find every pizza plac e within a 1 5 - mile radius ? Where the dog parks are in a new town? T he mos t c entral meeting plac e for your c las s , c lub or group of friends ? T he c heapes t gas s tations on a day- to- day bas is ? T he loc ation of c onvic ted s ex offenders in an area to whic h you may be c ons idering moving? T he applic ations , s erendipitous and s erious , s eem to be infinite, as developers find ever more c reative ways to add to and c us tomize the s atellite images and underlying A P I of G oogle M aps . Written by Sc huyler E rle and Ric h G ibs on, authors of the popular Mapping Hacks , Google Maps Hacks s hares dozens of tric ks for c ombining the c apabilities of G oogle M aps with your own datas ets . Suc h divers e information as apartment lis tings , c rime reporting or flight routes c an be integrated with G oogle's s atellite imagery in c reative ways , to yield new and us eful applic ations . T he authors begin with a c omplete introduc tion to the "s tandard" features of G oogle M aps . T he adventure c ontinues with 6 0 us eful and interes ting mapping projec ts that demons trate ways developers have added their own features to the maps . A fter that's given you ideas of your own, you learn to apply the tec hniques and tools to add your own data to c us tomize and manipulate G oogle M aps . E ven G oogle s eems to be tac itly bles s ing what might be s een as unauthorized us e, but maybe they jus t know a good thing when they s ee one. With the tric ks and tec hniques you'll learn from Google Maps Hacks , you'll be able to adapt G oogle's s atellite map feature to c reate interac tive maps for pers onal and c ommerc ial applic ations for bus ines s es ranging from real es tate to pac kage delivery to home s ervic es , trans portation and more. I nc ludes a foreword by G oogle M aps tec h leads , J ens and L ars Ras mus s en. Google Maps Hacks By Schuyler Erle, Rich Gibson ............................................... Publisher: O'Reilly Pub Date: January 2006 Print ISBN-10: 0-596-10161-9 Print ISBN-13: 978-0-59-610161-9 Pages: 366 Table of C ontents | I ndex Copyright Dedication Forew ord Credits About the Authors Contributors Preface Putting the World in the World Wide Web Why Google Maps Hacks? How to Use This Book How This Book Is Organized Conventions Used in This Book Using Code Examples How to Contact Us Got a Hack? Safari Enabled Chapter 1. You Are Here: Introducing Google Maps Section 1.1. Hacks 19: Introduction Hack 1. Get Around http://maps.google.com Hack 2. Find Yourself (and Others) on Google Maps Hack 3. Navigate the World in Your Web Brow ser Hack 4. Get the Bird's-Eye View Hack 5. Driven to a Better User Interface Hack 6. Share Google Maps Hack 7. Inside Google Maps URLs Hack 8. Generate Links to Google Maps in a Spreadsheet Hack 9. Use del.icio.us to Keep Up w ith Google Maps Chapter 2. Introducing the Google Maps API Section 2.1. Hacks 1016: Introduction Hack 10. Add a Google Map to Your Web Site Hack 11. Where Did the User Click? Hack 12. How Far Is That? Go Beyond Driving Directions Hack 13. Create a Route w ith a Click (or Tw o) Hack 14. Create Custom Map Markers Hack 15. Map a Slideshow of Your Travels Hack 16. How Big Is the World? Chapter 3. Mashing Up Google Maps Section 3.1. Hacks 1728: Introduction Hack 17. Map the New s Hack 18. Examine Patterns of Criminal Activity Hack 19. Map Local Weather Conditions Hack 20. Track Official Storm Reporting Hack 21. Track the International Space Station Hack 22. Witness the Effects of a Nuclear Explosion Hack 23. Find a Place to Live Hack 24. Search for Events by Location Hack 25. Track Your UPS Packages Hack 26. Follow Your Packets Across the Internet Hack 27. Add Google Maps to Any Web Site Hack 28. How Big Is That, Exactly? Chapter 4. On the Road w ith Google Maps Section 4.1. Hacks 2941: Introduction Hack 29. Find the Best Gasoline Prices Hack 30. Stay Out of Traffic Jams Hack 31. Navigate Public Transportation Hack 32. Locate a Phone Number Hack 33. Why Your Cell Phone Doesn't Work There Hack 34. Publish Your Ow n Hiking Trail Maps Hack 35. Load Driving Directions into Your GPS Hack 36. Get Driving Directions for More Than Tw o Locations Hack 37. View Your GPS Tracklogs in Google Maps Hack 38. Map Your Wardriving Expeditions Hack 39. Track Your Every Move w ith Google Earth Hack 40. The Ghost in Google Ride Finder Hack 41. How Google Maps Got Me Out of a Traffic Ticket Chapter 5. Google Maps in Words and Pictures Section 5.1. Hacks 4250: Introduction Hack 42. Get More out of What You Read Hack 43. Don't Believe Everything You Read on a Map Hack 44. You Got Your A9 Local in My Google Maps! Hack 45. Share Pictures w ith Your Community Hack 46. Brow se Photography by Shooting Location Hack 47. Geotag Your Ow n Photos on Flickr Hack 48. Tell Your Community's Story Hack 49. Generate Geocoded RSS from Any Google Map Hack 50. Geoblog w ith Google Maps in Thingster Chapter 6. API Tips and Tricks Section 6.1. Hacks 5161: Introduction Hack 51. Make a Fullscreen Map the Right Way Hack 52. Put a Map and HTML into Your Info Window s Hack 53. Add Flash Applets to Your Google Maps Hack 54. Add a Nicer Info Window to Your Map w ith TLabel Hack 55. Put Photographs on Your Google Maps Hack 56. Pin Your Ow n Maps to Google Maps w ith TPhoto Hack 57. Do a Local Zoom w ith GxMagnifier Hack 58. Find the Right Zoom Level Hack 59. Show Lots of StuffQuickly Hack 60. Make Things Happen When the Map Moves Hack 61. Use the Right Developer's Key Automatically Chapter 7. Extreme Google Maps Hacks Section 7.1. Hacks 6270: Introduction Hack 62. Find the Latitude and Longitude of a Street Address Hack 63. Read and Write Markers from a MySQL Database Hack 64. Build Custom Icons on the Fly Hack 65. Add More Imagery w ith a WMS Interface Hack 66. Add Your Ow n Custom Map Hack 67. Serve Custom Map Imagery Hack 68. Automatically Cut and Name Custom Map Tiles Hack 69. Cluster Markers at High Zoom Levels Hack 70. Will the Kids Barf? (and Other Cool Ways to Use Google Maps) Colophon Index C opyright © 2 0 0 6 O 'Reilly M edia, I nc . A ll rights res erved. P rinted in the U nited States of A meric a. P ublis hed by O 'Reilly M edia, I nc ., 1 0 0 5 G ravens tein H ighway N orth, Sebas topol, C A 9 5 4 7 2 . O 'Reilly books may be purc has ed for educ ational, bus ines s , or s ales promotional us e. O nline editions are als o available for mos t titles (s afari.oreilly.com). For more information, c ontac t our c orporate/ins titutional s ales department: (8 0 0 ) 9 9 8 - 9 9 3 8 or c orporate@ oreilly.c om. Editor: Simon Cover St.L aurent Designer: Production J amie Editor: P eppard Interior Designer: M arc ia Friedman D avid Futato Copyeditor: D erek D i M atteo Indexer: N anc y Robert Romano, J es s amyn Illustrators: C rumpton Read, and L es ley Boras h Printing History: J anuary Firs t Cover Karen M ontgomery Illustrator: 2006: E dition. N uts hell H andbook, the N uts hell H andbook logo, and the O 'Reilly logo are regis tered trademarks of O 'Reilly M edia, I nc . T he Hacks s eries des ignations , Google Maps Hacks , the image of an antique globe, and related trade dres s are trademarks of O 'Reilly M edia, I nc . M any of the des ignations us ed by manufac turers and s ellers to dis tinguis h their produc ts are c laimed as trademarks . Where thos e des ignations appear in this book, and O 'Reilly M edia, I nc . was aware of a trademark c laim, the des ignations have been printed in c aps or initial c aps . While every prec aution has been taken in the preparation of this book, the publis her and authors as s ume no res pons ibility for errors or omis s ions , or for damages res ulting from the us e of the information c ontained herein. Small print: T he tec hnologies dis c us s ed in this public ation, the limitations on thes e tec hnologies that tec hnology and c ontent owners s eek to impos e, and the laws ac tually limiting the us e of thes e tec hnologies are c ons tantly c hanging. T hus , s ome of the hac ks des c ribed in this public ation may not work, may c aus e unintended harm to s ys tems on whic h they are us ed, or may not be c ons is tent with applic able us er agreements . Your us e of thes e hac ks is at your own ris k, and O 'Reilly M edia, I nc . dis c laims res pons ibility for any damage or expens e res ulting from their us e. I n any event, you s hould take c are that your us e of thes e hac ks does not violate any applic able laws , inc luding c opyright laws . I SBN : 0 - 5 9 6 - 1 0 1 6 1 - 9 [M ] Dedication For Heather, Molly, Maddy, and Spencer, for everything. Rich For Jo, who knows. Schuyler Foreword When we firs t entered the exc iting world of geography, we brought with us an idea that there c ould be more to online maps than, well, maps . We hoped to build a Web s ite not limited to providing maps and driving direc tions , but one that c ould s erve as a platform for all manners of loc ation- bas ed information and s ervic es . O r to put it in G oogle terms : a s tarting point for organizing the world's information geographic ally. For this and other reas ons we were thrilled to s ee "hac kers " have a go at G oogle M aps almos t immediately after we launc hed the s ite bac k in early February. L iterally within days , their blogs des c ribed the inner workings of our maps more ac c urately than our own des ign doc uments did, and s oon the mos t amazing "hac ks " s tarted to appear: P hilip L inds ay's G oogle M aps "s tandalone" mode, P aul Rademac her's H ous ing M aps , and C hris Smoak's Bus mons ter, to mention a few. I t was an exc iting day for our s mall team when we learned that premier publis hing hous e O 'Reilly was c ons idering writing an entire book about G oogle M aps H ac ks , and we were pleas ed to be able to announc e our offic ial maps A P I program at O 'Reilly's Where 2 .0 c onferenc e in J une. I t is both humbling and flattering to witnes s the as tounding c reativity s urrounding our maps as c hronic led in this wonderful bookalready a few s hort months after Where 2 .0 , thous ands of programmers from around the world feature G oogle M aps in their inc reas ingly impres s ive and s uc c es s ful c reations . M apping and geography is a wonderful field, and c learly the Web has made it pos s ible to explore and advanc e the millennia- old field in new and exc iting ways . T here's s o muc h more to do, and this marvelous book will s erve as a great res ourc e for mapping enthus ias ts . We hope you will enjoy it as muc h as we did! J ens Ras mus s en and L ars Ras mus s en Google Maps team Credits A bout the A uthors C ontributors About the Authors Rich Gibson believes that the world is made of s tories , and has unlimited c urios ity in the world. H e indulges his brilliant, s emimanic c hildren in s uper- long s torytimes , weird s c ienc e projec ts , and adventures of many varieties . I t is only the s teady s upport of his loving wife that permits him to organize his ec c entric ity into oc c as ional c oherent burs ts of c reative produc tivity. L ife is very, very good. Schuyler Erle is a linguis t by training and a Free Software developer by voc ation. H e got into G I S and digital c artography with Ric h s everal years ago, while trying to analyze the bes t lines - of- s ight for a rural wireles s c ommunity network. H e ac tually believes that maps and G I S, properly applied, c an tell c ompelling s tories , and help improve people's lives . A s of this writing, he lives with his wife near 4 2 .3 7 5 N , 7 1 .1 0 6 W. Contributors T he following people c ontributed their writing, c ode, and ins piration to Google Maps Hacks : Tom C arden (tom@ tom- c arden.c o.uk) writes pas s enger flow s imulations for Y RM A rc hitec ts , L ondon, and is s tudying for an E ngD in V irtual E nvironments I maging and V is ualization at U nivers ity C ollege L ondon's Bartlett Sc hool of G raduate Studies . H e als o gives oc c as ional lec tures for the Bartlett's M Sc A daptive A rc hitec ture and C omputation. O nline, he is a c ontributor to the O penStreetM ap projec t (opens treetmap.org), an ac tive member of the c ommunity formed around the P roc es s ing development environment (proc es s ing.org) and pos ts s poradic ally to his weblog, Random E tc (www.tom- c arden.c o.uk/weblog). O ffline, he c an often be found at I s lington's T inderbox c offee s hop, s taring thoughtfully into a latte and c ontemplating a world empowered by mas s ively dis tributed c ollaborative mapping s oftware. Reverend D aniel C att res ides in Stoke- on-Trent, U .K. (5 3 .0 1 3 , - 2 .1 7 5 6 ) with his wife, C harlie C att, and daughter, M odes ty B C att. A long- time keen walker, he firs t bec ame involved with mapping in 1 9 9 8 , produc ing 3 D views of national parks from map s c ans and O rdnanc e Survey data. H is interes t was foiled for a long time by the lac k of open and free mapping data in the U .K. and not living in L ondon. I n 2 0 0 5 , preG oogle M aps A P I , when G oogle M aps hac king was really s c ary, this interes t was rekindled in the form of www.geobloggers .c om an ongoing projec t to c ons ume, aggregate, vis ualize and pus h geoRSS- formatted data. H e has a B.A . from Staffords hire U nivers ity and publis hes his thoughts at http://geobloggers .blogs pot.c om and http://3 6 0 .yahoo.c om/revdanc att. H e c an be c ontac ted at revdanc att@ yahoo.c om or Yahoo! I ns tant M es s enger at revdanc att@ yahoo.c om. D rew C elley is a giant fire- breathing mons ter, s tanding 3 0 0 feet tall. H e c an s ometimes be found toppling buildings and knoc king over elevated railways , but s pends mos t of his time as a U N I X Sys tems A dminis trator in P itts burgh, P enns ylvania. When he is n't rampaging through the c ity, D rew likes to tinker with tec hnology and help forge s nippets of T he Future into exis tenc e by writing hac ks , s oftware, and letters to c ertain politic al offic ials . H e is the c oc reator of WiFiM aps .c om and has a s lew of other experiments and projec ts he's been working on, whic h you c an read more about at http://www.zhrodague.net/~drew. I n his s pare time, he c an be found gardening, brewing, printing, or s earc hing for his next c ontrac t. Steve C oas t (s teve@ as klater.c om) s tarted and runs O pens treetmap.org from L ondon (the one in E urope), a projec t to c ollaboratively generate free geodata. H e c ons ults with two friends through Somethingmodern.c om, doing a wide range of heavylifting c omputer work. J ared C os ulic h c reated the C ommunityWalk s ite http://c ommunitywalk.c om to let you s hare your c ommunity with the world, after work and on weekends while s itting in his apartment at 3 7 .8 0 2 5 6 5 , - 1 2 2 .4 1 6 0 5 1 , watc hing the touris ts wander by on their way to the c urvy part of L ombard Street. A ndru E dwards is a geek entrepreneur whos e duties inc lude ac ting as C E O of G ear L ive M edia, a tec hnology blog network, and being the primary organizer and planner of the Seattle M ind C amp overnight geek c onfab event. A ndru's goal is to us e tec hnology and new media to c reate c ommunity both online and off. C hris G oad is a c omputer s c ientis t by training (P hD Stanford, 1 9 8 0 ). H e worked as a res earc h as s oc iate at Stanford from 1 9 8 0 to 1 9 8 3 and c ofounded two c ompanies : Silma in 1 9 8 3 and M ap Bureau in 1 9 9 3 . H is areas of work have inc luded applic ations of mathematic al logic to c omputation, c omputer vis ion, s imulation s oftware for 3 D mec hanic al s ys tems , programming language des ign, and the s emantic web. D uring the las t four years , he has c onc entrated on applic ations of s emantic web tec hnology to c artography, and on the des ign and implementation of Fabl, a programming language that repres ents programs as s emantic web objec ts . C hris lives in A s toria, O regon and works at M ap Bureau. See http://fabl.net/c hris goad. M ic hal G uerquin and Zac h Frazier c alc ulated the s ize of the G oogle M aps c ac he of the map of the world. M ic hal's web s ite is http://mic hal.guerquin.c om. J ohn T. G uthrie experiments with c ode and mathematic al c ounterexamples at http://c ounterexample.org. C hris H eathc ote is an interac tion des igner, with a foc us on mobile and wireles s experienc es . H e lives in H els inki, Finland and works on N okia's I ns ight and I nnovation team. H e writes about buildings and food at http://antimega.c om, and c an be emailed at c @ deaddodo.c om. A drian H olovaty is a web developer/journalis t in C hic ago. H e s pends evenings hac king on open s ourc e c ode and s ide projec ts that make information ac c es s ible to the public . H is C hic agoc rime.org was one of the original G oogle M aps hac ks . H e's als o lead developer of D jango, an open s ourc e P ython web framework (D jangoprojec t.c om). By day, A drian works as editor of editorial innovations for Was hingtonpos t.c om. A ns elm H ook is a reformed games developer and s oc ial c artographer. H e's c urrently leading the http://platial.c om engineering team. Will J ames is a des igner and photographer living in N ew York C ity. H e c reated the N Y C s ubway map hac k as a c heap s tunt to promote his pet projec t http://onN Y Turf.c om. I t's working. Ric hard Kagerer is a s mall bus ines s owner in O ttawa, O ntario. H is c ompany, L eapbeyond Solutions , provides O utlook- bas ed s oftware and c utting- edge c ons ulting s ervic es to s mall and mid- s ize c ompanies . I n his s pare time, he likes to water s ki and s targaze. Tom L imonc elli has over 1 5 years of s ys tem adminis tration experienc e and has been teac hing works hops on time management at c onferenc es s inc e 2 0 0 3 . Tom has authored Time Management for Sys tem Adminis trators (O 'Reilly) and The Practice of Sys tem and Network Adminis tration (A ddis on Wes ley). O uts ide of work, Tom has won awards for his ac tivis m in gay/bi/les bian rights and now helps progres s ive c aus es us e tec hnology to further their goals . Robert L ipe, tired of being los t mos t of the time, bought his firs t G P S in 2 0 0 1 . T hough it was originally jus tified for his bus ines s travels as a s oftware engineer, geoc ac hing quic kly c ons umed itand him. Frus trated with the available tools to talk to the G P S and the diffic ulty of moving data between programs , he wrote G P SBabel and made it available to the public at http://www.gps babel.org. G P SBabel is now us ed behind the c urtains in programs s uc h as G oogle E arth and G SA K, the G eoc ac hing Swis s A rmy Knife. H e als o wrote and maintains a c ollec tion of tec hnic al G P S artic les on the web at http://www.mtgc .org/robertlipe. Robert and his family live outs ide N as hville, Tennes s ee. H e c ontinues to develop s oftware for G P S- related tec hnologies for fun and for hire. Tom L ongs on is a web developer with an interes t in c artography and wearable c omputing, whic h he often writes about on igargoyle (http://igargoyle.c om). H e gained an interes t in s oftware engineering from his father, who was a pioneer in digital arts and us ed programming to produc e unique 3 D c ons truc tions and C G I . Tom ultimately wants to develop s oftware that will c hange the way people think and interac t with eac h other, for better or wors e, and muc king with maps s eems like one of thos e things that will do s o. M ikel M aron is an independent s oftware developer and ec ologis t. H e has built s everal geographic - oriented projec ts around the worldKit mapping pac kage, inc luding World as a Blog. P revious ly, he led development of M y Yahoo! in the pre- RSS days . M ikel was awarded a M as ters degree from the U nivers ity of Sus s ex for building a s imulation of the evolution of c omplexity in food webs . O riginally from C alifornia, M ikel is pres ently bas ed mos tly in Brighton, U .K., where he lives with his wife A nna. L inks to various things c an be found at http://brainoff.c om. Tom M angan is a news paper c opy editor and page des igner who blogs at http://tommangan.net. H e is an avid hiker and photographer. H e als o maintains the "Banned for L ife" of expres s ions "s o hac kneyed and ins ufferable that they s hould be forever banned from the nation's news reports ." Ron P arker is a s oftware engineer from Fort Wayne, I ndiana who s pends his days writing s oftware for the blind and vis ually impaired and his evenings hac king on G P SBabel and other free s oftware. H e has two dogs , three c ats , and four c omputers . A nthony P etito c reated the http://www.s tormreportmap.c om s ite to s upport his interes t in weather. H e is available for G oogle M aps c ons ulting. D ave Sc horr is a weather fan who runs http://www.weatherbonk.c om. C hris Smoak runs the http://bus mons ter.c om s ite that trac ks bus es on G oogle M aps . E dwin Soto is an entertainment c olumnis t with http://www.gearlive.c om. M ark Torranc e is C hief E xec utive O ffic er and P rinc ipal C ons ultant at V inq. H e founded V inq in 2 0 0 3 to offer s ervic es inc luding des ign, implementation, and s upport of s ophis tic ated databas e- bac ked web applic ations . I n this role, Torranc e has grown an effec tive team of c ons ultants and managers , grown the bus ines s in exc es s of 1 0 0 % eac h year, and won new projec t work for the firm. Torranc e was als o the lead des igner and implementor of KnowledgeP lex 2 .0 , the firs t vers ion of this web platform developed for Fannie M ae Foundation. KnowledgeP lex s erves as both a c ontent management framework for its own affordable hous ing c ontent and as a platform for c obranding and reus e on partner s ites . M ark brings c ons ulting expertis e in the areas of open s ourc e s oftware, rapid applic ation development, des ign for us ability, graphic des ign and aes thetic s of web des ign, and taxonomy/ontology development. H ans van der M aarel is a s elf- employed G I S/c artographic engineer from T he N etherlands . M aps have been a great pas s ion of his s inc e a young age, and he's very glad he got the opportunity to do c ool things with them bec aus e he c ons iders it a great field of work that he enjoys every day. A part from maps , he likes travelling and lis tening to roc k mus ic . Preface A few years ago, us ing maps on the Web was hard. T he maps were ugly, s low to load, and burdened with a c lunky us er interfac eand if you think us ing maps on the Web was hard, imagine trying to make us eful and interes ting maps on the Web! Today, however, all that has c hanged. A good meas ure of the c redit for this quantum leap in digital c artography on the I nternet is due to G oogle and their G oogle M aps s ervic e. H ow did this c ome about? Putting the World in the World Wide Web I t has been s aid that "the network is the c omputer," and, for mos t of us , the "network" means the World Wide Web. From its humble origins as a repos itory of hypertext doc uments , the Web has bec ome a s ort of dis tributed operating s ys tem, one that allows c lever programmers (and more than a few random dilettantes ) from far- flung plac es to build new applic ations by mixing and matc hing data and s ervic es in ways that the original des igners of thos e s ervic es never c ons idered. I n rec ent years , "traditional" c ommerc ial web s ites , s uc h as A mazon, eBay, and G oogle, have inc reas ingly bec ome platforms that s upport c omplex us er ec os ys tems . U s ing openly publis hed A P I s , you c an look up an item on A mazon, get a pric e his tory from eBay, and find reviews on G oogleall at onc e, and all without A mazon, eBay, or G oogle ever talking with eac h other. U ntil now, a c ruc ial c omponent has been lac kingloc ation. What's important about loc ation, you may as k? Well, for s tarters , it's everywhere! E verything has a loc ation, and until now there were few reas onable options for mixing in loc ation. T here were expens ive and c omplic ated proprietary s ys tems , as well as free and powerfulbut s till c omplic atedopen s ourc e options , but they all required you to be part of the c artographer's elite. You had to pay with time, attention, aggravation, and even money! But today, G oogle M aps has opened mapping to everyone. A h! L oc ation! Open APIs + Open Data Formats = Web 2.0 Heaven L et's take P aul Rademac her's H ous ingM aps s ite at http://hous ingmaps .c om/ as one example. H ous ingM aps takes hous ing rental and for- s ale lis tings from C raigs lis t and plots them on a G oogle M ap, making it eas ier to find hous ing in the area that you're interes ted in. H ous ingM aps demons trates what c an happen when you give developers a tools etand, mind you, developers don't even need a c lean, well- doc umented tools et. T he s ite was originally developed by hac king on G oogle's (initially) s omewhat- obfus c ated maps interfac e. T he key is that neither C raigs lis t nor G oogle were involved in this endeavor, and that the res ult was s omething greater than the parts . I n mus ic this is c alled a mas hup, and the term has c ros s ed over and is now us ed in the world of Web 2 .0 . N owhere has this trend been more nec es s ary than digital c artography, of c ours e, for all the aforementioned reas ons . T hree things s et G oogle M aps apart from what c ame before: a c lean and res pons ive us er interfac e; fas tloading, pre- generated map images ; and a c lient- s ide A P I that makes it pos s ible to put a G oogle M ap on any web page. O f thes e three things , it might not be exaggerating to s ay that the openly publis hed A P I behind G oogle M aps is far and away the mos t revolutionary of them all. Who Will Aggregate the Aggregators? A new approac h to building web applic ations us ing As ynchronous JavaScript + XML (A J A X) has made this muc h eas ier. T he A J A X approac h employed by G oogle M aps and many other s ites means that the web page is running c ode that dynamic ally fetc hes data as needed from a s erver, and that this data is us ually in XM L . "Yeah? So what? " you might s ay. Well, the "s o what" is that thes e data s ourc es are probably open and available for you to s c rape. Sometimes they are publis hed, and other times they are hidden in a page, but they are there. A lot of new tec h is es tablis hed when developers have s omething that they c an hac k on. T he Web has s hown that the definition of developer is pretty wide! T he original Web took off in large part bec aus e of the menu item V iew Sourc e. Suddenly the barrier to entry was nearly mic ros c opic . I t was a s hoc k when my own mother as ked me for advic e on web- authoring s oftware, but that is what happens when you give people ac c es s to the tools that they c an us e to tell c ompelling s tories . G oogle M aps , A J A X- bas ed apps , and Web 2 .0 remixing in general are s imilarly benefiting from the "V iew Sourc e" mentality: others c an look at your page, learn from your c ode, figure out where your data lives , and then remix it to make s omething greater. T he c ons equenc e is that P aul Rademac her c an s c rape data publis hed in an open format by C raigs lis t and then put it on a map us ing an A P I openly publis hed by G oogle. But what's to keep you from s c raping P aul's s ite and a dozen others and putting that data on a map? To paraphras e J uvenal, who c an live in our modern age and not write aggregators ? Not Just Where 2.0, But Also Why 2.0 Some people s ay "why s hould we give all our hard work to our c ompetitors ? " A nd you know, I 'm not s ure I have an ans wer for them. But I 've notic ed that mos t of the people and c ompanies that as k that ques tion are, well, boring or lame, while the c ooles t people and c ompanies and you probably know who I 'm talking abouttend to be thos e that don't as k that ques tion. T hough s ometimes good people and good ideas are s tuc k in environments where s ec rec y is key, more often it's as Rob Flic kenger onc e s aid about the then- new c opy- protec ted C D from C eline D ion that would not play on a c omputer: "G ood! T hey are mos t of the way there. N ow if they c an only make a C D of C eline D ion that c an't play in any C D player…." L et's look a little bit deeper into this , though: maybe what makes the "open" c amp s eem interes ting is that opennes s c reates a s pac e for interac tion, and many interac tions allow c omplex ec ologies to form. J us t as one example, we s hould point out that, thanks to G oogle's approac h of offering open ac c es s to their mapping s ervic e, there is already at leas t one s oftware development outfit on the Web that advertis es G oogle M aps integration as its primary offering. So why s hare your c ode? Why s hare your data? U ltimately, if there's one les s on that's emerging from the wild world of Web 2 .0 , it's that s haring and opennes s make the world a ric her and more interes ting plac e to live. D oing s o might not make you as muc h moneybut it might make you moreand the world will be more fun if you s hare. O ur friend M arc P owell s ays that c ompanies are a lot like kindergartners , and s ometimes you jus t have to s mile and s ay "T hat is nic e, Billy, and would you like to s hare the c rayons now? " Why Google Maps Hacks? T he term hacking has a bad reputation in the pres s , where it is us ed to refer to s omeone who breaks into s ys tems or wreaks havoc with c omputers as their weapon. A mong people who write c ode, though, the term hack refers to a "quic k- and- dirty" s olution to a problem, or a c lever way to get s omething done. A nd the term hacker is taken very muc h as a c ompliment, referring to s omeone as being creative, having the tec hnic al c hops to get things done. T he H ac ks s eries is an attempt to rec laim the word, doc ument the good ways people are hac king, and pas s the hac ker ethic of c reative partic ipation on to the uninitiated. Seeing how others approac h s ys tems and problems is often the quic kes t way to learn about a new tec hnology. M aps are a s trange c ombination of the extremely s imple and the extremely c omplex. M os t people are familiar with paper maps , but are only s tarting to explore the pos s ibilities of elec tronic maps . With the advent of G oogle M aps , inc redible opportunities have opened up that go well beyond the us ual expec tations of paper maps . Google Maps Hacks will s how you thes e opportunities and how to take advantage of them. How to Use This Book You c an read this book from c over to c over if you like, but for the mos t part, eac h hac k s tands on its own, s o feel free to brows e and jump to the different s ec tions that interes t you mos t. I f there's a prerequis ite you need to know about, a c ros s - referenc e will guide you to the right hac k. So, feel free to brows e, flipping around to whatever s ec tions interes t you mos t. How This Book Is Organized T he book is divided into s even c hapters , organized by s ubjec t: C hapter 1 , You Are Here: I ntroducing Google Maps A n introduc tion to http://maps .google.c om, how to look up loc ations , get driving direc tions , look at s atellite pic tures , s hare links to maps in emails and on web pages , generate links to maps from a s preads heet, and us e del.ic io.us (http://del.ic io.us ) to keep up with developments . C hapter 2 , I ntroducing the Google Maps API G oogle M aps makes it eas y to put a map on your own web page. L earn how to put a map on your page, c apture us er c lic ks , c reate a s lides how c onnec ted with a map, c reate c us tom ic ons , and meas ure dis tanc es . C hapter 3 , Mas hing Up Google Maps A re you interes ted in s omething? C hanc es are that s omeone has put s ome as pec t of it on a G oogle M ap. L earn about a variety of mas hups , from mapping the news , to s eeing where c riminals "work," to weather maps , to ans wering the ques tion: where is the I nternational Spac e Station right now? You c an als o examine the blas t radius of a nuc lear explos ion, find a plac e to live, or s ee what is roughly the s ize of Texas . C hapter 4 , On the Road with Google Maps M aps and travel go together like gruel and c hipped teeth. Find the c heapes t gas near to you, load driving direc tions into your G P S to take with you, look at your G P S trac klogs , explore hiking trails , figure out why your c ell phone does n't work at home, and even beat a traffic tic ket. C hapter 5 , Google Maps in Words and Pictures P ic tures and maps are a natural fit. O ne of the great things about photos is that they are always taken s omewhere. L earn how to geoc ode your photos on Flic kr, s et up a blog that knows about plac e, geoc ode literature, and examine the c hoic es that go into whic h s atellite images are inc luded. C hapter 6 , API Tips and Tricks You now know how to put a map on your own page; in the c hapter, learn how to tweak and extend that map. I nc lude a map within your map, overlay photographs and labels where you want them, and c reate a georeferenc er to pin your own s c anned or digital maps onto a G oogle M ap. C hapter 7 , Extreme Google Maps Hacks P us h the boundaries ! U s e a c lus tering algorithm s o that your own points fit properly on a map, c reate your own map tiles , c onnec t to a databas e, us e web s tandards to dis play other data (s uc h as L ands at imagery) on your maps , and even figure out if your kids are likely to barf. Conventions Used in This Book T he following is a lis t of the typographic al c onventions us ed in this book: I talics U s ed to indic ate U RL s , filenames , filename extens ions , and direc tory/folder names . For example, a path in the files ys tem appears as /Developer/Applications . Constant width U s ed to s how c ode examples , the c ontents of files , c ons ole output, as well as the names of variables , c ommands , and other c ode exc erpts . Constant width bold U s ed to highlight portions of c ode, typic ally new additions to old c ode. Constant width italic U s ed in c ode examples and tables to s how s ample text to be replac ed with your own values . G ray type U s ed to indic ate a c ros s - referenc e within the text. You s hould pay s pec ial attention to notes s et apart from the text with the following ic ons : T his is a tip, s ugges tion, or general note. I t c ontains us eful s upplementary information about the topic at hand. T his is a warning or note of c aution, often indic ating that s omething might break if you're not c areful, pos s ibly quite badly. T he thermometer ic ons , found next to eac h hac k, indic ate the relative c omplexity of the hac k: beginner moderate expert Whenever pos s ible, the hac ks in this book are not platforms pecific, whic h means you c an us e them on L inux, M ac intos h, and Windows mac hines . H owever, s ome things are pos s ible only on a partic ular platform. Using Code Examples T his book is here to help you get your job done. I n general, you may us e the c ode in this book in your programs and doc umentation. You do not need to c ontac t us for permis s ion unles s you're reproduc ing a s ignific ant portion of the c ode. For example, writing a program that us es s everal c hunks of c ode from this book does not require permis s ion. Selling or dis tributing a C D - RO M of examples from O 'Reilly books does require permis s ion. A ns wering a ques tion by c iting this book and quoting example c ode does not require permis s ion. I nc orporating a s ignific ant amount of example c ode from this book into your produc t's doc umentation does require permis s ion. We apprec iate, but do not require, attribution. A n attribution us ually inc ludes the title, author, publis her, and I SBN . For example: "Google Maps Hacks by Ric h G ibs on and Sc huyler E rle. C opyright © 2 0 0 6 O 'Reilly M edia, I nc ., 0 - 5 9 6 - 1 0 1 6 1 - 9 ." I f you feel your us e of c ode examples falls outs ide fair us e or the permis s ion given above, feel free to c ontac t us at permis s ions @ oreilly.c om. How to Contact Us We have tes ted and verified the information in this book to the bes t of our ability, but you may find that features have c hanged (or even that we have made mis takes ! ). A s a reader of this book, you c an help us to improve future editions by s ending us your feedbac k. P leas e let us know about any errors , inac c urac ies , bugs , mis leading or c onfus ing s tatements , and typos that you find anywhere in this book. P leas e als o let us know what we c an do to make this book more us eful to you. We take your c omments s erious ly and will try to inc orporate reas onable s ugges tions into future editions . You c an write to us at: O 'Reilly M edia, I nc . 1 0 0 5 G ravens tein H ighway N orth Sebas topol, C A 9 5 4 7 2 (8 0 0 ) 9 9 8 - 9 9 3 8 (in the U .S. or C anada) (7 0 7 ) 8 2 9 - 0 5 1 5 (international/loc al) (7 0 7 ) 8 2 9 - 0 1 0 4 (fax) To as k tec hnic al ques tions or to c omment on the book, s end email to: bookques tions @ oreilly.c om T he web s ite for Google Maps Hacks lis ts examples , errata, and plans for future editions . You c an find this page at: http://www.oreilly.c om/c atalog/googlemaps hks / T he authors maintain the M apping H ac ks web s ite, whic h is related to the lates t in digital c artography on the Web. O n their s ite, you c an find more information about the topic s explored in this book. T he M apping H ac ks s ite c an be found at: http://www.mappinghac ks .c om/ For more information about this book and others , s ee the O 'Reilly web s ite: http://www.oreilly.c om Got a Hack? To explore H ac ks books online or to c ontribute a hac k for future titles , vis it: http://hac ks .oreilly.c om Safari Enabled When you s ee a Safari® E nabled ic on on the c over of your favorite tec hnology book, that means the book is available online through the O 'Reilly N etwork Safari Books helf. Safari offers a s olution that's better than e- Books . I t's a virtual library that lets you eas ily s earc h thous ands of top tec h books , c ut and pas te c ode s amples , download c hapters , and find quic k ans wers when you need the mos t ac c urate, c urrent information. Try it for free at http://s afari.oreilly.c om. Chapter 1. You Are Here: Introducing Google Maps 1.1. Hacks 19: Introduction I n February of 2 0 0 5 , G oogle quietly announc ed the debut of a new s ervic e, G oogle M aps , that c hanged the fac e of mapping and c artography on the Web for an overwhelming number of people. G one were the tiny, s low- loading, and s ometimes ugly digital maps that people were pretty muc h ac c us tomed to us ing on the Web, maps that fell below the "fold" of a web page, and were often impos s ible to navigate. I ns tead, us ing the lates t in web brows er s c ripting tec hnology, G oogle M aps offers a fas t- loading, tiled map dis play, a s imple yet deep us er interfac e, as ync hronous dis play updates in plac e of the tires ome c lic k- and- reload routine, and, ultimately, even a ric h s c ripting A P I . A lthough many of thes e features had been s een before in one plac e or another, no one had s een them all integrated with the attention to detail that we've c ome to expec t from G oogle. L et's take our firs t look at how G oogle M aps c hanged how people us e maps on the Web forever. Hack 1. Get Around http://maps.google.com Sometimes you need a map to the map. G oogle applied its trademark, c arefully des igned s implic ity, to provide us with its (firs t) view of plac e. G o to http://maps .google.c om/, and you'll get the view s hown in Figure 1 - 1 . I f you want maps of the U nited Kingdom, try http://maps .google.c o.uk/, and you'll get the view in Figure 1 - 2 . A s imilar map exis ts for J apan at http://maps .google.c o.jp/. T his s hows us what appears as a s tandard G oogle s earc h box (c alled the L oc ation Searc h box), an overview or orientation map of the c ountry in ques tion, and a res ults area with ins truc tions and s ample s earc hes . Figure 1-1. http://maps.google.com/ Figure 1-2. http://maps.google.co.uk/ P leas e remember that this book was written us ing beta s oftware, and the G oogle engineers are c ontinually tinkering with the s ite in order to provide the mos t c ompelling pos s ible s ys tem. T his means that things will c hange! 1.2.1. What's Different About Google Maps? G oogle M aps is a web mapping s ervic e that s olves the s ame old problem of online mapping. So why, ten years or more into the web revolution, is G oogle M aps s uc h a big deal? Some of the exc itement c omes from the G oogle name and its philos ophy. G oogle s tates on its c orporate philos ophy page at http://www.google.c om/c orporate/tenthings .html that "you c an make money without doing evil." H owever, more of the interes t in G oogle M aps may s tem from other ideas s tated on the philos ophy pagefor example, "T he interfac e is c lear and s imple" and "P ages load ins tantly." C lean pages and fas t performanc e? A c ommitment to avoid doing evil? Whic h drives traffic and mind s hare? M aybe at this moment on the Web you c an have it all. I n addition to thes e features , G oogle M aps als o offers a number of innovations in web us er interfac es . Single s earch box T he firs t thing that draws attention is that G oogle us es a s ingle s earc h box for loc ation s earc hes . D o you want to look up an addres s ? J us t type it in the box. N o more tabbing between different fields for s treet addres s , c ity, s tate, and ZI P C ode! (I n I nternet E xplorer, you c an even pas te multi- line addres s es into this box, believe it or not.) Draggable maps T he s tandard in web mapping is the us ual web interfac e, in whic h you c lic k on a button to pan the map and s ee more terrain. What if you wanted to jus t c lic k and drag to navigate the map? Well, now you c an! I ntegrated local s earch You c an us e that s ingle s earc h box to look for the things you want, s uc h as "hotels near Sebas topol," or, for more c hoic es , "hotels near SFO " (SFO is the c ode for San Franc is c o I nternational A irport). I f you jus t want to find all the hotels in a given area, zoom into that area, then s earc h for "hotels ," and G oogle M aps will c ons train its s earc h to the area s hown on the map. Satellite imagery With a s ingle c lic k you c an flip between viewing a map and viewing s atellite or aerial photography [Hack #4]. H ow c ool is that? Keyboard s hort cuts You don't need to c lic k and drag your mous e, or s trive to hit the little Zoom I n and Zoom O ut ic ons : you c an us e the arrow keys to move around in your map [Hack #3]. 1.2.2. Getting Around G oogle M aps s tarts with the overview map s hown in Figure 1 - 1 . You c an move around that map by c lic king and dragging your mous e on the map, by double- c lic king your mous e on the map, or by us ing the arrow keys . H olding the mous e button down and dragging will c aus e the whole map to move, as if the web brows er is providing a s mall window onto a muc h larger map. I f you double- c lic k on a s pot, the map will s moothly pan until the point you c lic ked on is c entered. U s ing the arrow keys has the s ame effec t as c lic king and dragging with the mous e. We explore the us er interfac e in more detail in "N avigate the World in Your Web Brows er" [Hack #3]. 1.2.3. Entering a Location T here are many ways to enter loc ations [Hack #2], but let's s tart off eas y. T he c onventional way of entering a loc ation is a s treet addres s . We've c ome to ac c ept addres s lookups in online mapping s ervic es as c ommonplac e, but there is a great deal of behind- the- s c enes work. I n order to dis play a map of a s treet addres s , the s ys tem mus t firs t find a latitude and longitude that c orres ponds to this addres s . T he proc es s of linking s omething (e.g., a s treet addres s ) with a latitude and longitude is c alled geocoding. When you enter a query into the s earc h box, G oogle takes your input and does its bes t to turn it into a loc ation that c an be mapped. So let's s tart c los e to home and enter the s treet addres s of O 'Reilly M edia headquarters into the s earc h box: 1005 Gravenstein Highway North, Sebastopol, CA 95472 You c ould als o enter the c ompany name and get the s ame res ult: O'Reilly Media, Sebastopol, CA 95472 C lic k Searc h and you'll get the map s hown in Figure 1 - 3 , whic h s hows the addres s (as bes t as G oogle c an determine) and hyperlinks to get direc tions to or from this s pot. T he s atellite view in Figure 1 - 4 (zoomed in from the area s hown in Figure 1 - 3 ) c learly s hows that the O 'Reilly E mpire is c entered in a parking lot median s trip…. You c an als o enter a s treet inters ec tion; for example: Hollywood & Vine St, Hollywood, CA 90068 T he ac t of looking up a loc ation has s et your s earc h area, or the extents of your s earc h area, and you c an now us e the s earc h box to get more information. For example, if you firs t zoom in to San Franc is c o, you c an then s earc h for "great s us hi" and return res ults limited to the San Franc is c o area. Figure 1-3. A Google map of O'Reilly Media's headquarters Figure 1-4. O'Reilly Media, apparently located in a median strip of a parking lot T he G oogle M aps tour s ugges ts that a s earc h on "G reat Sus hi in N ew York" is us eful. I t turns out that "great s us hi in San Franc is c o" als o brings up a lis t of res taurants , but for s ome reas on, "great s us hi in Sebas topol" jus t does n't work. To be fair, "great s us hi in Sebas topol, C A " does bring up our two s us hi plac es . But it als o brings up the L arks pur E lementary Sc hool D is tric t, 3 7 miles from Sebas topol. Varying the adjec tive us eds ay from "great" to "medioc re"brings up a new grouping of res taurants . T hes e are not the s ame plac es that s how up when you do a G oogle s earc h on "medioc re s us hi in San Franc is c o," s o I 'm not s ure what the qualific ations are. "C heap but filling s us hi in San Franc is c o" might be a more palatable s earc h! Finding meaningful res ults for loc al s earc h is s till an uns olved problem. Fortunately, G oogle is good at s earc hand getting better all the time. Hack 2. Find Yourself (and Others) on Google Maps Google Maps supports many ways to specif y location. U s ing addres s es to find a plac e makes a lot of s ens e for plac es that have an addres s , but what do you do when you don't have an addres s ? Fortunately for you, the G oogle M aps team has s upplied a number of additional ways to find yours elf. I s us pec t that the goal is to c reate a s ys tem in whic h, if you c an imagine a s omewhat s tandard way of repres enting a loc ation, then G oogle M aps will s upport it. T he func tionality is not quite there yet, but it does s upport a lot of ways of finding plac es . A s with all of the hac ks in this book, and as a general philos ophy of life, experimentation is your friend! T he number one rule for finding plac es us ing G oogle M aps is that if there is a way of s pec ifying loc ation that makes s ens e to you, go ahead and try it! A s we s aw in "G et A round http://maps .google.c om" [Hack #1], s tandard addres s es work, but s o does entering a c ity and s tate, or a ZI P C ode alone. Street inters ec tions als o work, as long as you add a c ity and s tate. You c an als o enter c oordinates as latitude and longitude, like 38, -122, or 38 N, 122 W. M os t modern people don't relate to latitude and longitude direc tly, but it is a c ompac t and prec is e way to mark a loc ation. G oogle M aps is good at s earc hing by bus ines s name. You c an s earc h by bus ines s name, c ity, and s tatefor example, "O 'Reilly M edia, Sebas topol, C A "with good res ults . E ntering a bus ines s name and a c ity, or a bus ines s name and a s tate, brings up a lis t of pos s ible matc hes . T he bes t G oogle M aps feature ever is the proximity s earc h, at leas t for one of my friends , who is a vegetarian and travels a lot. Before G oogle M aps , he s pent a lot of time on other map s ervic es planning for trips . A c ommon query was for the c los es t Whole Foods M arket in whatever c ity he was vis iting. N ow he c an jus t type his query into the s ingle s earc h box: "whole foods market near Bos ton, M A ." A s long as he remembers to c hange Bos ton, MA to his c urrent c ity, he is s et. Table 1 - 1 s hows examples of s earc hes that do and don't work. Table 1-1. The limits of Google Maps' understanding Example 1005 G ravens tein H ighway N , Sebas topol, C A 95472 Works? Yes 7 9 th St and Broadway, N Y 7 9 th St and Yes Broadway, 10024 Description Full s treet addres s works great. I nters ec tion and c ity, or inters ec tion and ZI P C ode. Santa Ros a, C A Santa Ros a, N M Yes C ity and s tate works . San Franc is c o M os c ow Yes T he bare c ity name works abs urdly often. I f the s ame c ity appears in more than one s tate it appears to pic k the larges t. I nternational c ities were added rec ently, but data quality varies . C A or C alifornia No State or s tate abbreviation alone does n't work. 94305 Yes ZI P C ode works . P os tal c odes for other s upported c ountries , s uc h as C anada and the U .K. work as well. LA X Yes A irport c odes work. P addington Yes I n the U K and J apan, s ubway s tations work as loc ations . 3 7 , -1 2 2 Yes L atitude and longitude expres s ed as dec imal degrees with - to expres s Wes t longitude or South latitude. SFO 37 N, 122 W Yes T he s ame, but us e N and S and E and W. N 38 24' 0 8 .8 " W 1 2 2 4 9 ' 4 4 .2 " No L atitude and longitude as degrees minutes - s ec onds does n't s eem to work, but perhaps after partaking of the magic s yntax elixir…. Range and towns hip No G oogle M aps does n't s eem to do range and towns hip. T his would be a great feature for genealogy buffs that get rec ords of their forbears ' property trans ac tions . [loc ation] to [loc ation] Yes A ny of the above loc ations that work c an be mixed and matc hed with the word to in between them to get driving direc tions . [thing] near [loc ation] Yes You c an us e any of the above loc ations to s earc h for nearby bus ines s es and points of interes t. 1.3.1. Odd and Surprising Ways to Find Things N ot everything is doc umented! L ike G oogle's s earc h, there are a lot of things that jus t work that are not doc umented (or at leas t they are not doc umented where you are likely to s ee them). For example, as of A pril 3 0 th, 2 0 0 5 , I c ould find no mention that entering a latitude and longitude in the s earc h box would have any effec t, and yet it works ! T he moral is that when you have a wild idea about a way to s earc h for s omething, try it firs t, and then if it does n't work, enjoy that temporary feeling of s atis fac tion that c omes from being ahead of the c urve (well, either ahead of the c urve, or plumb c razy, but s inc e there is no reliable way to determine whic h is whic h, you might as well enjoy it). 1.3.2. When Locations Fail: The Importance of Context U nles s you s pec ify a loc ation in your s earc he.g., "edible food near King's C ros s "G oogle M aps as s umes that the plac e that you are s earc hing for falls within the area, or extent, that is c urrently s hown in the map. A s a res ult, a s earc h that works on the full extent will s ometimes fail if you have a loc al c ontext s et. You c an res et that c ontext by adding "near [s ome loc ation]" to your s earc h, or by c lic king on the G oogle M aps logo in the upper left of the page. Hack 3. Navigate the World in Your Web Browser There is no doubt about it: Google has signif icantly raised the bar f or user interf aces to maps on the Web. Here's why. When G oogle M aps was launc hed in February 2 0 0 5 , the public res pons e was ins tant and almos t overwhelmingly pos itive. A lthough the remarkable s peed with whic h any map appeared, tile by tile, had a great deal to do with people's apprec iation of G oogle M aps , mos t of the prais e and rec ognition was s aved for the brows er interfac e its elf. T he G oogle M aps us er interfac e is c lean, s imple, s traightforward, quic k loading, and eas y to us e. I n other words , it offers yet another c las s ic G oogle us er experienc e. 1.4.1. Just a Click Away… T he main thing about the G oogle M aps us er interfac e that really wows everyone the firs t time they s ee it is the drag panning. G o to any loc ation in G oogle M aps , pos ition the mous e pointer anywhere on the map, c lic k and hold your left mous e button, and then move the mous e its elf. L o and beholdthe map moves with it, and the page in your brows er does n't even reload! Releas ing the mous e button, of c ours e, c aus es the map to s top panning. You'll notic e that, in the bac kground, your brows er has already loaded many of the tiles outs ide your original view, s o that you don't have to wait for them to load as you're panning aroundthat is , unles s you're on a s low I nternet c onnec tion, or you try to pan very quic kly from one edge of the map to the other. I f dragging the map feels a bit wild or diffic ult to c ontrol, the G oogle M aps interfac e als o allows you to double- c lic k your left mous e button anywhere on the map to rec enter it at that loc ation. D ouble- c lic king to rec enter gives you a more prec is e, but s omewhat les s dynamic way to pan around the map. T he ability to c lic k and drag the map around in the brows er window, while not, s tric tly s peaking, new, has never been s een before in a major mapping s ervic e on the Web. G one are the days when brows ing a map on the Web involved a tedious wait for the entire web page to reload every time you tried to rec enter or zoom the map! H ooray! 1.4.2. You Control the Horizontal and the Vertical O ver on the left s ide of the map, you s hould s ee a number of c ontrols in gray and blac k, as s hown in Figure 1 - 5 . I f panning by dragging or double- c lic king does n't s uit you, you c an us e the four arrow buttons to s c roll the map north, s outh, eas t, and wes t. T he s omewhat les s obvious ly labeled button in the c enter of the other four, whic h depic ts four arrows pointing inwards , returns you to the original view of the las t thing you s earc hed for. T his button lets you pan around the map, zoom in and out to your heart's c ontent, and then c lic k the return button to go right bac k to the plac e you were originally looking at. Figure 1-5. The Google Maps navigation controls Below the pan c ontrols lie the zoom c ontrols . G oogle M aps features 1 8 zoom levels , from a view that s hows multiple c opies of the E arth's s urfac e right down to the individual c ity bloc k. T he button marked with the plus s ign (+) zooms in one level, while the button at the bottom marked with the minus s ign (- ) zooms out. Between them runs a long vertic al ruler, marked with a tic k for eac h zoom level, with a "handle" indic ating the c urrent zoom. You c an c lic k anywhere along this ruler to zoom direc tly to a given map s c ale, or c lic k and drag the zoom handle up and down the ruler to zoom in and out dynamic ally. A s you zoom in and out, the s c ale bar at the bottom left c hanges ac c ordingly. I n the s maller vers ions of the G oogle M ap interfac e, the vertic al zoom c ontrol ruler is omitted, leaving the zoom- in and zoom- out buttons s tac ked immediately below the pan c ontrols . L as t but not leas t, in the upper right- hand c orner of the map, you'll find the map dis play c ontrols , as s hown in Figure 1 - 6 . A s of this writing, G oogle M aps has three modes : Map, Satellite, and a new Hybrid mode that dis plays s treets and labels s emitrans parently over a s atellite or aerial image. For N ew O rleans , there is als o a "Katrina" view, whic h is aerial imagery of N ew O rleans taken A ugus t 3 1 , 2 0 0 5 . T he us er interfac e features a button for eac h mode, with the button for the c urrent mode highlighted in bold. C lic king any one of thes e three buttons c hanges modes , allowing you to identify features or inters ec tions in one view, and then immediately s witc h to another to get more information about what's there. Figure 1-6. The Google Maps modes for New Orleans You'll notic e that c lic king on the map its elf with the left mous e button does n't ac tually do anything in the plain vanilla G oogle M aps interfac e. I ns tead, the left- c lic k is res erved in order to allow you to perform c us tom ac tions at any point on the map. We'll s ee a number of thes e c us tom us es for left- c lic king on the map later in the book. 1.4.3. Economies of Scale O n the lower left s ide of the s tandard G oogle M aps view, you'll s ee a s c ale bar, whic h indic ates dis tanc es horizontally ac ros s the c enter of the map in both miles and kilometers , as s hown in Figure 1 - 7 . N ot only c an this be us eful for es timating dis tanc es "as the c row flies ," but it als o gives a s ens e of how the cartographic proj ection us ed in G oogle M aps dis torts and exaggerates the E arth's s urfac e as you head towards the north and s outh poles . (T his is why G reenland looks bigger than A us tralia on G oogle M aps , when in fac t it is muc h s maller.) Figure 1-7. The Google Maps scale bar O ne c ute way to s ee this in ac tion is to pan up to the is lands in northern C anada, zoom in a bit, and then c lic k the map and s lowly drag it upwards , thereby panning s outh. A s you move the map, you c an watc h s ee the s c ale bar get s maller and s maller, and then flip over to a larger inc rement, before c ontinuing to s hrink. N ot only is this a good example of the dynamic nature of the G oogle M aps interfac e, but it als o illus trates one of the downs ides of us ing the familiar Mercator proj ection, as G oogle M aps does . T he reas on G oogle M aps us es the M erc ator projec tion ins tead of one that might provide les s vis ual dis tortion is that, as with other rec tangular projec tions , it treats all lines of latitude as being perpendic ular to all lines of longitude. T his property makes doing any kind of c alc ulation to plac e things on the map s o muc h eas ier that it outweighs the aes thetic detriments of having dis torted northern and s outhern extremes on the map. A dditionally, over s maller areas , the M erc ator projec tion pres erves angles ac ros s loc al areas on the map, making it s uitable for guiding navigation. (I ndeed, this is one major reas on the M erc ator projec tion c ontinues to be us ed after 5 0 0 years , in s pite of its tendenc y to dis tort the areas around the poles .) 1.4.4. Take the Shortcut But, wait, there's more! With G oogle's typic al thoroughnes s , the G oogle M aps us er interfac e makes good us e of keyboard s hortcuts in the web brows er as well. Keyboard s hortc uts allow you to ac c omplis h the s ame tas ks that mos t people us e their mous e for without ever taking your hands off your keyboard's home row. (A nd if you're a c ommand- line joc key like me, you gotta love 'em.) T he mos t immediately us eful keyboard s hortc uts in G oogle M aps are, of c ours e, the arrow keys , whic h allow you to pan the map in muc h the s ame way as the aforementioned pan buttons in the upper- left c orner of the map, with one differenc e: if you hold down any arrow key, the map c ontinues to panand fairly s moothly at that, if your c omputer and 'N et c onnec tion are fas t enoughuntil you let up on the key. With a little prac tic e, you c an s c oot around a neighborhood in G oogle M aps like a pro, without ever touc hing your mous e. I f you want to pan around fas ter at one go, you c an us e the diagonal arrow keys : P gU p and P gD n pan three- quarters of the way ac ros s the map north and s outh res pec tively, and H ome and E nd quic kly pan wes t and eas t by the s ame amount. Finally, the plus (+) and minus (- ) keys zoom in and out by one level, res pec tively. O n s ome A pple keyboards , s uc h as the one s upplied with iBooks , Fn- / generates a plus s ign, Fn- ; is minus , and Fn- arrow keys provides the P gU p, P gD n, H ome, and E nd func tions . I n M ozilla Firefox, you may find that if you jus t typed s omething into the s earc h box above the map, your brows er's foc us is s till be on the text box, whic h means that key pres s es will s how up there, rather than going direc tly to the map. I f this happens , jus t hit the Tab key (or left- c lic k onc e anywhere on the map its elf) to move the brows er's foc us away from the s earc h box. T hen the keyboard s hortc uts s hould work as advertis ed. 1.4.5. Taste the Secret Sauce I t is a c urious fac t that, as of this writing, although all the pan and zoom c ontrols have as s oc iated keyboard s hortc uts , there do not s eem to be keyboard s hortc uts for s witc hing modes . O ne almos t wonders if this is n't an inadvertent overs ight on G oogle's part. Fortunately, as the patient and attentive reader will dis c over, s inc e G oogle's c ode is running on your web brows er, you the hac ker c an fix any s uc h overs ights yours elf by dipping into G oogle's s ec ret s auc e. T he s ec ret s auc e by whic h G oogle offers s o muc h ric h func tionality with s uc h a s eemingly s imple interfac e is referred to by s ome people as A J A X, whic h (s ometimes ) s tands for "A s ync hronous J avaSc ript A nd XM L ." By us ing c lient- s ide J avaSc ript to detec t us er ac tions and ac t on them in the bac kground, G oogle M aps offers a very pleas ingly us able interfac e to a map of the world, all without the interminable wait for the entire page to reload any time s omething happens . A s we'll s ee later in the book, the deep integration with the brows er interfac e at the J avaSc ript level is als o the s ourc e for muc h of the extreme hac kability of G oogle M aps ! Hack 4. Get the Bird's-Eye View Maps are good, but a picture is worth… M aps s how what the mapmaker c hoos es to s how. G oogle M aps , like mos t of the online map s ervic es , s hows maps that are des igned primarily for getting around in a c ar. I n A meric a, we pretend we've (d)evolved into homo automobilious , but des pite our bes t efforts there is more to the world than s c enery and billboards flying pas t the bug- s meared winds hield. O ne neat feature of G oogle M aps is the ability to flip between viewing a map and viewing s atellite imagery. I n Figure 1 - 8 we s ee a map of the U pper Wes t Side of M anhattan, with an odd little s hape s tic king into the H uds on River on the left s ide. By c lic king on the Satellite link on the upper- right s ide of the window, you get s atellite and aerial imagery. Figure 1-8. Upper West Side Manhattan T he aerial view in Figure 1 - 9 provides a lot more c ontext! You c an s ee the buildings and Rivers ide D rive. You c an even make out individual boats at the 7 9 th Street Boat Bas in. You c an us e the s ame navigation tric ks to pan around in s atellite and aerial imagery as you c an on the map layer [Hack #3]. Figure 1-9. Aerial view of the Upper West Side and the 79th Street Boat Basin T he s atellite imagery's level of detail varies by where you're looking; s ome plac es have muc h more detail than others . 1.5.1. Is It Really There? You c an us e the aerial imagery as a s anity c hec k. For example, let's s ay you are in the N orth Bay area and are interes ted in dairy produc ts . You c ould s earc h for cheese near Petaluma, CA and get a map like Figure 1 - 1 0 . Figure 1-10. Looking for cheese in all the wrong places To vis it Rouge et N oir C hees e Fac tory (http://www.marinfrenc hc hees e.c om/), you c ould c lic k on the link on the right s ide in the lis t of res ults , zoom in a bit, and flip to s atellite view to get the view in Figure 1 - 1 1 . Where's the c hees e? I t does n't look like it is there. C ould it be in that c irc ular c ompound on the right- hand s ide? M aybe, exc ept I happen to know that this is n't the c as e. I t s eems that there's a dis c onnec t between databas es at G oogle. T he bus ines s lis ting for Rouge et N oir puts it at 7 5 0 0 Red H ill Road, P etaluma, C A 9 4 9 5 2 , but the map pointer is 4 .5 miles northeas t. O f c ours e, this is beta s oftware! E ntering the addres s , rather than the bus ines s name, into the s earc h box rewrites the addres s as 7500 Point ReyesPetaluma Rd and c omes c los er to loc ating the C hees e Fac tory, as s hown in Figure 1 - 1 2 . T he pointer is s till a bit off, but that c an be attributed to the diffic ulty in geoc oding loc ations from s treet addres s es on roads with long patc hes between inters ec tions . Figure 1-11. Cheeseless in Marin You may s ometimes find that the s atellite imagery is s lightly out of date with res pec t to the roads and other things s hown on the map. Figure 1-12. Thar be cheese! 1.5.2. Hybrid Vigor N ow, as if that weren't enough, G oogle has added a Hybrid mode to G oogle M aps . T he H ybrid mode takes a vers ion of the original s treet map tiles with trans parent bac kgrounds , and then lays them over the s atellite tiles . T he res ult is pretty fantas tic , as you c an s ee from Figure 1 - 1 3 , making it muc h eas ier to identify what's being s hown in the s atellite image. Figure 1-13. Manhattan's Upper West Side, in Hybrid mode T he ability to flip between maps and s atellite imagery is amazingly c ool, and is jus t a hint of what (I as s ume) is c oming. T here is plenty of room next to the M ap, Satellite, and H ybrid hyperlinks for other views or, as we s ay in G eographic I nformation Sys tems , other data layers . O ne prominent example was the Katrina button that s howed up in the map dis play of the G ulf C oas t of the U nited States in the aftermath of H urric ane Katrina in A ugus t 2 0 0 5 . C lic king this button dis played up- todate s atellite imagery, allowing you to c ompare before- and- after views of the hurric ane's tragic ally des truc tive wake. What c ould G oogle add? H ow about a link to terrain or elevation data? O r a c urrent weather overlay? T hanks , G oogle, may I have another? Hack 5. Driven to a Better User Interface Driving directions and the single search box. H ow muc h work does it take to get driving direc tions ? With M apQ ues t, you need to c lic k on a link to the D irec tions page, enter your s tarting s treet addres s , hit Tab (or even wors e, take your hands off the keyboard, put them on the mous e, and c lic k on the next field), enter your c ity, hit Tab, enter your s tate, hit Tab, enter your ZI P C ode, hit Tab, and then repeat that E nterTab ballet for your des tination. I n G oogle M aps , you enter your s tarting s treet addres s , c ity, s tate, and (optional) ZI P C ode, then to, and then the s treet addres s , c ity, s tate, and (optional) ZI P C ode of your des tinationinto the s ingle s earc h box. Would you trade a c lic k and s even tabs or c lic ks for a s ingle to? I s ure would! I n addition, G oogle M aps provides lots of alternatives for as king direc tions . T he us ual way is to enter the beginning and ending des tinations into the s earc h box [Hack #2]. To get direc tions from O 'Reilly M edia to the San Franc is c o airport, you c an enter the s tarting addres s and the airport c ode: 1005 Gravenstein Hwy N, Sebastopol, CA 95472 to SFO You c an even get direc tions from one airport to another. For example, for direc tions from San Franc is c o I nternational to O akland I nternational try SFO to OAK. T his pulls up the driving direc tions s hown in Figure 1 - 1 4 . Figure 1-14. Driving directions from the San Francisco to the Oakland airports When I get driving direc tions , I 'm us ually familiar with either the s tarting or ending loc ation, but not both. G oogle provides a neat map- within- a- map effec t to help navigate that las t little bit. I f you c lic k on the Start A ddres s or E nd A ddres s links in the top of the res ults area on the right of the s c reen, a mini- map appears in the info window of the s tarting or ending addres s (Figure 1 1 5 ). Figure 1-15. A detailed map of the destination You c an als o c lic k on the individual s teps in the driving direc tions to get a mini- map for that navigational maneuver. T he mini- map that appears is a c omplete map, with its own zoom (but not pan) c ontrols , s o you c an pos ition the map, zoom in, and print the map and direc tions . To add another level of c ool, flip the mini- map to s atellite view, as s hown in Figure 1 - 1 6 . Figure 1-16. The detailed satellite view of the destination We have a friend who lives donde el Diablo s e perdido s u poncho ("where the devil los t his ponc ho"), and having this imagery makes it a lot eas ier to unders tand what is happening as you travers e miles of s ingle- lane former s tage c oac h roads to pay a vis it. 1.6.1. Using the Info Windows When you s earc h for an addres s or c lic k on a loc al link, G oogle M aps produc es the (hopefully) now- familiar info window, as s hown in Figure 1 - 1 7 . Figure 1-17. You can search in the info window You c an c lic k on the info window links to get direc tions to or from that addres s . When you c lic k on one of thos e links , you get a mini s earc h box into whic h you c an type a loc ation, as s hown in Figure 1 - 1 8 . 1.6.2. Other Ways to Search A s mentioned above, you c an us e any of the methods of entering a loc ation mentioned in "Find Yours elf (and O thers ) on G oogle M aps " [Hack #2] and probably s everal more that we haven't found! So you c an get the direc tion from an airport to a c ity (LAX to Hollywood, CA) or between two ZI P C odes (94305 to 95472), or any c ombination of the two. You c an even get direc tions to a latitude and longitude. T his c an be fun if you are interes ted in the D egree C onfluenc e P rojec t (http://www.c onfluenc e.org/), whic h is attempting to c ollec t pic tures and s tories from eac h of the latitude and longitude integer degree inters ec tions in the world. So you c ould s earc h for LAX to 34, -118 and get Figure 1 - 1 9 , s howing the c los es t degree c onfluenc e to L os A ngeles . Figure 1-18. The search box in the info window Figure 1-19. LAX to the nearest Degree Confluence34 N, 118 W Hack 6. Share Google Maps Found something good? Email a link, bookmark it, or post it on your web site. A re you having a party and needing to let people know where it will be held? D id you find a c ool s pot that you want to s how your friends ? G oogle M aps c an c reate an email with a link that will s how your friends (mos tly) the s ame view you s eeor generate a link to pos t on your own web s ite. Without maps , many of us are reduc ed to near- inc omprehens ible grunts if forc ed to provide direc tions to our homes . E ven if we've lived in the s ame plac e for years , our direc tion- giving proc es s too often inc ludes putting a hand over the phone hands et and as king whoever is around, "What is the name of that s treet? " T he problem does n't end there. E ven if we are good at providing direc tions , our would- be vis itor mus t keep trac k of fragments of data s uc h as "the red mailbox" and "right after the hilland if you hit the c orner, you've gone too far." With online map s ervic es , though, mos t of the time it is enough jus t to have a s treet addres s , and with mos t, emailing or pos ting a link to a map helps a vis itor find the loc ation quic kly. Figure 1 - 2 0 s hows driving direc tions from W 88th St and Broadway, NY, NY to W 92nd St and Central Park West, NY, NY. I t als o inc ludes a des tination mini- map. Figure 1-20. Getting around New York in Google Maps C lic k the E mail link jus t under the line that inc ludes the M ap and Satellite links , and G oogle opens your email c lient and ins erts this link to this map, along with a s et of driving direc tions , in the body of the email: http://maps.google.com/maps?q=W+88th+St+and+Broadway,+ny,+ to+W+92nd+St+and+Central+Park+West,+ny,+ny&ll=40.789110, =0.007782,0.013467&hl=en A ll you need to do is fill in the email addres s of your friend and s end it off. 1.7.1. Bookmark a Google Map or Post It on Your Web Page G oogle M aps makes deep us e of J avaSc ript to dynamic ally redraw the map without (apparent) reques ts to the s erver. T his means that the loc ation bar in your brows er does not get updated. T his only bec omes an is s ue when you dec ide to bookmark a map to us e later. When you bookmark G oogle M aps , you find that you've bookmarked the overview map of the whole U nited States almos t c ertainly not what you intended! Fortunately G oogle has provided a way out. N ext to the E mail link, under the M ap and Satellite links , is a link to "L ink to this page," as s hown in Figure 1 -2 1 . Figure 1-21. Print, email, or link to this map C lic king "L ink to this page" updates the addres s bar in your brows er. N ow you c an bookmark the page in your brows er or s hare the link on del.ic io.us [Hack #9]or c opy the link from the addres s bar and pas te it into your own web page. alternatively, you c an right- c lic k on "L ink to this page" and s elec t C opy L ink L oc ation (in Firefox) or C opy Shortc ut (in I nternet E xplorer) to c opy the link direc tly to the c lipboard. To pos t a link on your web page: 1. Find a map that you like. 2. Right- c lic k on "L ink to this page" and s elec t the C opy option. 3. P as te the link into your web page within an appropriate anc hor tag. For example, here is a link to a map of Salina, Kans as : http://maps .google.c om/maps ? q=Salina,+KS&s pn=0 .1 2 4 5 1 2 ,0 .2 1 5 4 6 7 &hl=en. You c ould inc lude it in your web page with this H T M L : <a href="http://maps.google.com/maps?q=Salina,+KS&spn =0.124512,0.215467&hl=en">Salina, Kansas</a> 1.7.2. Shorten That Link! Sometimes , if you jus t want to pas te a U RL of a G oogle M ap into an email, you may find that the U RL s are jus t long enough to break in the middle and wrap to the next line in your email c lient, whic h may make it more diffic ult for the rec ipients of your email to us e. M etamark offers a s olution to this problem at http://xrl.us /. T here you'll findno kiddinga link- s hortening s ervic e, whic h takes unwieldy U RL s like thos e produc ed by G oogle M aps and generates a permanent redirec t from a muc h s horter U RL to the muc h longer one you're having trouble with. H ere, for example, is M etamark's s hortened vers ion of the C entral P ark driving direc tions that were s hown in Figure 1 - 2 0 : http://xrl.us /hu9 c When others vis it the s hortened U RL , their brows ers will immediately be redirec ted to the longer U RL you s tarted with. You c an als o c hoos e to us e a mnemonic "nic kname" in plac e of the s tring of random letters after xrl.us in the s hortened U RL , as well as apply a pas s word to keep your U RL under wraps . 1.7.3. Limits on Email and Links T he link generated by E mail and "L ink to this page" produc es almos t the s ame view when c lic ked as you have when you c reate the links . Sometimes the map is not c entered in the s ame plac e as when you c lic ked on the link, as brows er window s izes vary, and G oogle M aps does its bes t to s how the area reques ted. O c c as ionally, this may even res ult in a different zoom level being dis played, in order to make the reques ted area fit in the available brows er window s pac e. A ls o, it is quite pos s ible, s inc e G oogle L oc al s earc hes appear to be regenerated on demand, that s omeone us ing your link c ould s ee a s lightly different lis t of bus ines s es than you did when you c reated the link. C urrently, the link does not s ave embedded mini- maps , s o if you've c reated driving direc tions and opened up a mini- map at the s tart or end addres s , it will not be inc luded in the email or link that you generate. M aps help us gather together, and being able to c ommunic ate with more prec is ion than "drive pas t the third gate, then turn right" means more people will s how up where they want to be, rather than los t by a frog pond (though s earc hing for "los t by a frog pond" brings up an abs urd number of links ). Hack 7. Inside Google Maps URLs Gain control of your links to Google Maps by understanding the URLs. "Share G oogle M aps " [Hack #6] s howed how to have G oogle M aps generate a link (i.e., U niform Res ourc e L oc ator or U RL ) that c reates a view of the c urrent map. A little exploration of G oogle M aps U RL s c an provide a lot of power! We have no partic ular ins ide information, s o muc h of what follows es pec ially what I think the abbreviated names s tand foris jus t s emi- knowledgeable gues s es . L et's s tart with a bas ic U RL . T his is what you get if you s earc h for Key West, Fl and then c lic k on "L ink to this page." http://maps .google.c om/maps ? q=Key+Wes t,+Fl&hl=en T he http://maps .google.c om part s hould be familiar. T his is the bas ic G oogle M aps addres s . N ext, /maps is a program running on G oogle's s ervers that generates maps . Web programs c an ac c ept parameters . T he s yntax for parameters is to s tart with a ques tion mark and then put the name of a parameter, an equal s ign, and the value of the parameter. I f you need a s ec ond (or third, or more) parameter, you put an ampers and between the firs t value and the s ec ond parameter's name. So ? q=Key+West,+Fl&hl=en means there is a parameter named q with the value Key+West,+Fl and a parameter named hl with the value en. N ote that the s pac es in "Key Wes t, Fl" have been replac ed with plus s igns . T his is bec aus e s pac es aren't allowed in U RL s and mus t be es c aped. T he parameter hl is the language for the res ults , and q is the query, or loc ation that you are s earc hing for. I f you s peak Frenc h, replac e the en with fr, and s o on. I f you leave off the hl parameter, G oogle M aps will try to dis play things in whatever language the us er's web brows er prefers . T he q or query parameter c an be any of the things that are dis c us s ed in "Find Yours elf (and O thers ) on G oogle M aps " [Hack #2]. For example, here is the U RL to a map for latitude 3 8 degrees north, longitude 1 2 2 degrees wes t: http://maps .google.c om/maps ? q=3 8 ,- 1 2 2 &hl=en? G oogle M aps follows the c onvention obs erved by mos t web mapping s oftware and G eographic I nformation Sys tems , and us es negative values to denote latitude s outh of the E quator and longitude wes t of the P rime M eridian. H ere, for example, is ZI P C ode 9 4 3 0 5 : http://maps.google.com/maps?q=94305&hl=en T he query s tring for driving direc tions matc hes what you would enter into the s earc h box, whic h is jus t as you'd expec t. H ere is San Franc is c o I nternational (SFO ) to L os A ngeles I nternational (L A X): http://maps.google.com/maps?q=SFO+to+LAX&spn=3.984375,6.89 T he spn parameter s hows how muc h territory the map s pans . I t appears to be the number of degrees of longitude and latitude (in that order) that are s hown on the map. T he firs t value appears to be the number of degrees of longitude that are s hown to the left and right of the c enter of the map. T he s ec ond value is the s ame for the number of degrees of latitude that are s hown above and below the c enter point. For example, if the values are 1,1, then about 2 degrees of longitude (about 9 0 miles from eas t to wes t), and about 2 degrees of latitude (around 1 3 8 miles from north to s outh) are s hown on the map. When you s earc h for driving direc tions , the s pan of the map is automatic ally s et s o that both the s tarting and ending points are s hown. T he s pan s ets the zoom level. T he fully zoomed- out map has a s pan of 6 3 .7 5 0 0 0 0 , 1 1 0 .3 1 9 1 9 1 , while the fully zoomed- in map is 0 .0 0 3 8 9 1 , 0 .0 0 6 7 3 3 (at leas t for one s ample mapit is likely that this varies with latitude). A t this point it does n't appear that you c an manually enter an even s maller s pan. T he s ys tem s eems to have a minimum, beyond whic h it will not go. A t the equator, one degree of latitude or longitude is equal to about 6 9 miles , or 1 1 1 kilometers . A s you go north or s outh of the equator, the degrees of latitude remain the s ame, but one degree of longitude s hortens to approximately the c os ine of the latitude multiplied by 6 9 miles . So, at 4 0 degrees north latitude, a degree of longitude is about 4 6 miles . 1.8.1. More Parameters! Table 1 - 2 lis ts the parameters we've been able to figure out. H ere, for one example, is a s earc h for "pizza" when the s pan of the map has already been limited to a loc al area: http://maps.google.com/maps?q=pizza&sll=38.402193,-122.829 =0.031128,0.053867&hl=en T he parameter sspn appears to be the s earc h s pan, and sll is the s earc h's latitude, longitude c enter points o this query is looking for pizza within .031128 degrees of longitude and .053867 degrees of latitude from latitude and longitude 38.402193, -122.829009. For linguis tic reas ons , we tend to think latitude and then longitude (i.e., lat/long), but when we draw graphs we think x,y. L atitude maps to the y axis , s o to be c ons is tent we'd talk about either y,x graphs or latitude, longitude c oordinates . G oogle appears to have adopted both c onventions in expres s ing geographic c oordinates in this U RL . P eople are not c ons is tent, and G oogle c an happily have a U RL that s pec ifies the c enter point as latitude, longitude but the s pan in x,y. To s ee the s atellite view, add the parameter and value t=k. M aybe that means type is k? What c ould k mean? (keyhole, perhaps ? ) A s of A ugus t 2 0 0 5 , the letter k and the number 1 both c aus e a s atellite map to appear, and the letter h c aus es hybrid maps to appear. From experimentation (i.e., trying all the other letters ), no other s pec ial tric ks live in the t parameter. P erhaps the other letters and digits will be us ed for c oming features . T his U RL repres ents a s atellite view and driving direc tions from SFO to L A X: http://maps.google.com/maps?q=SFO+to+LAX&spn=5.603027,7.48 O r, to get jus t the driving direc tions : http://maps.google.com/maps?q=SFO+to+LAX&spn=3.984375,6.89 Table 1-2. Google Maps URL parameters Parameter Example 94305 q 3 8 ,- 1 2 2 Description Q uery s tring. T his is what goes into the s ingle s earc h box. en hl L anguage. fr h t k I magery type. Show s atellite imagery if s et to k or 1 and hybrid maps if s et to h. 1 ll - 1 2 2 .7 3 8 .4 L ongitude and latitude of the c enter point of a generated map. z 3 Zoom level. Ranges from 3 to 1 8 . spn 5 .6 0 3 0 2 7 7 .4 8 1 6 8 9 N umber of degrees of longitude and latitude ac ros s the entire map. sspn 0 .0 3 1 1 2 8 0 .0 5 3 8 6 7 Searc h s pan. D efine area to s earc h for loc al s earc h. Same format as the spn parameter. sll 3 8 .4 0 3 1 9 3 Searc h latitude and longitude. T he - 1 2 2 .8 2 7 0 9 c enter point for a loc al s earc h. 1.8.2. Finding More Parameters? A nother c ute thing you c an do with G oogle M aps queries is to add a c us tom title to the loc ation by putting the title in parenthes es after the s earc h loc ation. For example, the following U RL s hows the loc ation of G oogle's headquarters , titled with the word "G oogle": http://maps.google.com/maps?q= 1600+Amphitheatre+Parkway,+Mountain+View,+CA+94043+(Goo G oogle M aps is filled with hidden (to us ) options . T he way to find out what it c an do is to experiment! Try different things and to s ee what it all means , c lic k on "L ink to this page" often! You never know what might workthat is the es s enc e of hac king! 1.8.3. See Also "G enerate L inks to G oogle M aps in a Spreads heet" [Hack #8]. Hack 8. Generate Links to Google Maps in a Spreadsheet Get a handle on your own data with Google Maps. What if you c ould c reate a private (or public ) web page with links to G oogle M aps for eac h of the people in your c ompany? O r all the members of your s oc ial c lub or c hurc h? You would be able to c lic k on the names of people in your group and pop up a map of their loc ation. Well, you c an! I n "I ns ide G oogle M aps U RL s " [Hack #7], we examined the s truc ture of G oogle M aps U RL s . N ow we will us e that information to c reate links to G oogle M aps that s how your own c ontac ts . We'll as s ume that you've got your c ontac ts in a s preads heet program, s uc h as M ic ros oft E xc el, G numeric , or O penO ffic e C alc . Figure 1 - 2 2 s hows a s ample data s et with a name, s treet addres s , c ity, s tate, and ZI P C ode s et up in c olumns . T his s preads heet is available as http://mappinghac ks .c om/google/s ample_data.xls . Figure 1-22. Name, address, city, state, and ZIP Code in spreadsheet columns We c an go from this format to a full H T M L link in E xc el. T he H T M L link for eac h element will look like this : <li><a href="http://maps.google.com/maps?q=1005+Gravenstei +N.,Sebastopol,CA,95472+(O'Reilly)&hl=en"> O'Reilly & Associates</a></li> T he li tag will put eac h line in an H T M L bulleted lis t. You will be able to c lic k on the name and pop up a map c entered on the addres s that goes with that pers on or c ompany. T he firs t s tep is to us e the c onc atenation func tion to put the name, addres s , c ity, s tate, and ZI P C ode together in a new c olumn. You c an do this by us ing either the c onc atenation func tion or the s hortc ut & that does the s ame thing: =CONCATENATE(B4,",",C4,",",D4,",",E4,"(",A4,")") or: =B4 & "," & C4 & "," & D4 & "," & E4 & "(" & A4 & ")" T his c reates an addres s that looks like this : 1005 Gravenstein Hwy N.,Sebastopol,CA,95472 (O'Reilly) You'll note that we us e the c us tom loc ation title tric k [Hack #7] to as s oc iate the loc ations on the map with the names from our s preads heet. N ext, we'll replac e the s pac es with plus s igns and ampers ands with %26 (s o they don't mes s up the format of the U RL ), and then add the q= part of the query. E xc el provides the Substitute() func tion. You give it a s tring, then the value you want to get rid of, and a new value to replac e the old value. I n this c ommand I c onc atenate the q= part of the parameter with the res ult of replac ing the s pac es in the c ombined addres s with plus s igns . =CONCATENATE("q=", SUBSTITUTE(SUBSTITUTE(F4," ","+"), "&", T he res ult looks like this : q=1005+Gravenstein+Hwy+N.,Sebastopol,CA,95472+(O'Reilly) N ext c onc atenate the other parts of the G oogle U RL : =$G$1 & G4 $G$1 is an abs olute referenc e to a c ell c ontaining http://maps .google.c om/maps ? hl=en& and G4 is the c ell with our c leaned up query parameters . N ote how the order of the parameters does n't matter. We c an lis t the q= part firs t or hl=en firs t. T his gives us the full G oogle M aps U RL of: http://maps.google.com/maps?hl=en&q= 1005+Gravenstein+Hwy+N.,Sebastopol,CA,95472+(O'Reilly) We have to make jus t one little addition in order to get the full H T M L that we want: ="<li><A href="""&H4&"""" & ">" & A4 & "</a></li>" T his is s ort of ugly bec aus e we need to inc lude double quotes (") in the res ult, but the double quotes are us ed as the s tring delimiter. I n E xc el you c an ins ert a double quote into a s tring by entering three double quotes . T he res ult is : <li><a href="http://maps.google.com/maps?hl=en&q= 1005+Gravenstein+Hwy+N.,Sebastopol,CA,95472+(O'Re O'Reilly & Associates</a></li> N ow we want to get thos e links into our own H T M L page. M os t s preads heet programs provide other tools to manage hyperlinks , but the s imples t way is to jus t c opy the c olumn by s elec ting the whole thing with E dit into your H T M L file. C opy (or C trl- C ) and then pas ting it O pen that loc al file in your brows er. You c an us e the power of the brows er without expos ing this page onto the I nternet. I f you are extremely paranoid, you need to aware that you are of c ours e expos ing your addres s es to G oogle, whic h c ould in theory trac k addres s s earc hes by your I P addres s and do s omething nas ty with that information. G iven G oogle's written c ommitment to avoid being evil, that s houldn't be a real ris k. You c an open a loc al H T M L file by s elec ting File O pen in I nternet E xplorer, or File O pen File in Firefox. T he res ult is a page of links like thos e in Figure 1 - 2 3 . Figure 1-23. A page of links to Google Maps created in Excel 1.9.1. See Also "I ns ide G oogle M aps U RL s " [Hack #7]. Hack 9. Use del.icio.us to Keep Up with Google Maps Other people want to help you keep up with Google Maps (and anything else)! What would you s ay to a world- wide c ommunity of people who s pend a great deal of effort to maintain a c haotic but powerful s et of links to mos t of the mos t interes ting material that is available on the Web? H ow about "thank you" and welc ome to http://del.ic io.us /? Q uoting from http://del.ic io.us /doc /about, J os hua Sc hac ter c reated del.ic io.us as a: …s oc ial bookmarks manager. I t allows you to eas ily add s ites you like to your pers onal c ollec tion of links , to c ategorize thos e s ites with keywords , and to s hare your c ollec tion not only between your own brows ers and mac hines , but als o with others . O ne key to the s ervic e is that your c ollec tion of links is intrins ic ally s hared with others . So you c an us e del.ic io.us to manage your own bookmarks , or you c an jus t brows e other people's links . O nc e you c reate an ac c ount by going to http://del.ic io.us /regis ter and pic king a us ername and pas s word, you c an us e the s ervic e to bookmark your own links . A major part of the power of del.ic io.us c omes from the ability to tag your links . A tag is jus t a bit of text that you feel c ategorizes the link. Figure 1 - 2 4 s hows a page of links that I tagged with the gmaps tag. Figure 1-24. del.icio.us posts about Google Maps Sinc e all bookmarks on del.ic o.us are s hared, you c an look at other s ites that people have tagged with the s ame tags . So if you wanted to s ee all of the s ites tagged with gmaps , you c an c lic k on "gmaps from all us ers " or go direc tly to this url: http://del.ic io.us /tag/gmaps . O r to s ee the s ites tagged with gmap, try http://del.ic io.us /tag/gmap. O ther people us e googlemaps and google_maps , s o you c an get to thos e with http://del.ic io.us /tag/googlemaps and http://del.ic io.us /tag/google_maps . O nc e you've looked at other people's links , you will want to c reate your own. J os hua provided s ome nifty little bookmarklets that you c an drag onto your bookmark toolbar. When you find a page you want to remember, you jus t c lic k on this bookmarklet in your own toolbar. T his will bring up a form like that s hown in Figure 1 - 2 5 . (T here are a few different bookmarklets , s o yours might look s lightly different.) Figure 1-25. Bookmarking a page in del.icio.us When you c lic k on the "pos t to del.ic io.us " bookmarklet, it c opies the U RL and title from the c urrent page and then pre- fills the "pos t to del.ic io.us " form. You then c an add an extended des c ription and tags . I f you wis h, you c an totally ignore the res t of the world and us e tags that are only meaningful to you. O r, you c an s trive to us e a s et of c ommon and authoritative tags in all of your links . Well, you c ould us e that s et of c ommon and authoritative tags , exc ept that no s uc h thing exis ts , nor, really, is it c apable of exis ting. T he problem of c las s ifying web pages is s o diffic ult that it has driven otherwis e brilliant people to near lunac y. A nd s ome of thos e folks were even P erl programmers ! So ins tead of a s et of authoritative taxonomies , del.ic io.us allows you to roll your own. I n the c as e of the link s hown in Figure 1 - 2 4 , I dec ided that the tag gmaps (for G oogle M aps ), fit, s inc e the artic le is about c onnec ting a G P S to a mobile phone and then loading maps from G oogle M aps onto the phone. O f c ours e, gps als o fits , s inc e there is a G P S in the s ys tem, and mobile phones are mobile, s o I threw both of thos e in as well. M ultiple tags are s upported, and enc ouraged; they jus t need to be s eparated by s pac es . Why did I us e gmaps ins tead of gmap? T his brings up a weaknes s of thes e informal taxonomies ; s ometimes they are too informal, and redundanc y c reeps in. D id I s ay creeps ? N o, redundanc y does n't c reep in, it is thrus t in! H eaved in, piled in s o that the res ulting taxonomy c reaks from the weight of repetition. A nd it turns out that this overwhelming c ruft of repetition jus t does n't matter. T he ability for everyone to c reate meaningful c ategories that work for them, while allowing everyone to s hare in this c ollec tive taxonomic al work, has c reated a s ys tem of inc redible power. Tag- bas ed c las s ific ation s ys tems are jumping into exis tenc e all over the Web. So muc h s o, that they have fos tered the term folks onomy to des c ribe thes e "folk"- driven taxonomies . Folks onomies have thrilling emergent properties , s uc h as automatic ally generating taxonomies , and providing the data to allow for automatic generation of link c lus ters . Folks onomies als o have weaknes s es , and few people are s ugges ting that profes s ional taxonomy be eliminated! del.ic io.us has lots of c ool features , and it is in a s tate of c ontinual improvement. O ne of the neat features is that you c an s ubs c ribe to tags and to us ers . So if you s ubs c ribe to the gmaps , gmap, googlemaps , and google_maps tags , interes ting links will jus t magic ally appear in your del.ic io.us inbox, and you will get c ontinual updates on what is happening with G oogle M aps . O ur friend (and Mapping Hacks c ontributor) M ike L iebhold maintains an extens ive s et of links to geo- related topic s : mapping, G I S, G P S, and s o on. H e c reated the del.ic io.us ac c ount s tarhill_blend as a repos itory for his abs urdly detailed s ubs c riptions to geo- related web s ites . Sometimes two- thirds of the pos ts will be about G oogle M aps , but he is looking at everything from location-bas ed-game to ps ychogeography. You c an follow this page at http://del.ic io.us /inbox/s tarhill_blend. A s befits a modern data aggregating applic ation, all the interes ting pages are als o available via RSS c ontent s yndic ation. I f you s pend a lot of time on the Web and you don't know about RSS, you c an do yours elf a favor and s ave a lot of time by learning about it. 1.10.1. See Also T he G oogle M aps M ania blog at http://googlemaps mania.blogs pot.c om/ maintains a good ongoing review of all things new and G oogle M aps . Developing Feeds with RSS and Atom by Ben H ammers ley (O 'Reilly). Chapter 2. Introducing the Google Maps API 2.1. Hacks 1016: Introduction T he G oogle M aps s ite at http://maps .google.c om is awes ome, with an eas y us er interfac e, one- box s earc hing, and integrated s atellite imagery. But it gets better! T he G oogle M aps team has made it pos s ible to inc lude G oogle M aps with almos t all of its great features onto your own web pages . T hey have done this by providing an open A pplic ation P rogram I nterfac e, or A P I . A n A P I defines a s tandard way for one program to c all c ode that lives within another applic ation or library. T he G oogle A P I defines a s et of J avaSc ript objec ts and methods that you us e to put maps on your own web pages . Before G oogle M aps , it was muc h harder to put s imple maps on your own pages . M apQ ues t had a program that let you c reate a link to a map. You c ould not embed the map on your own page, you c ould not put it into a frame, you c ouldn't even us e Target=_new to open a new brows er window. T here wereand areopen s ourc e s olutions to generate maps . For example, the U M N M aps erver (http://maps erver.gis .umn.edu) is very powerful, allowing you to do things that G oogle M aps c annot yet equal, but there is a rather s teep learning c liff. T here are als o indus try s tandards for web mapping promulgated by the O pen G eos patial C ons ortium (O G C ) at http://www.opengeos patial.org. T he O G C - defined Web M apping Servic e (WM S) and Web Feature Servic e (WFS) s tandards define a powerful web s ervic es interfac e to geos patial data. T here are now free and eas y- to- us e open s ourc e c lients for WM S and WFS data. For example, you c an us e the open s ourc e J avaSc ript library from http://openlayers .org/ to ac c es s public data s ourc es and put free maps on your page. T hes e are great options that either were not available or were not eas y to us e when the G oogle M aps A P I was releas ed. Some folks argue that G oogle did nothing new. T here was free data out there, and there were web- enabled G I S s ys tems . But c learly G oogle did s omething. C reating feature- c omplete interfac es to geographic data that are s o c omplex as to be inpenetrable by all but the highes t of high pries ts s eems to be nearly inevitable. P rogrammers s tart with a s imple model, and then the world, the data, and the weight of his tory intrude to "c omplexify" our models and break our metaphors . When Walt Kelly wrote "We have met the enemy and he is us ," he c ould have been des c ribing the c reators of mos t geos patial apps . Somehow G oogle avoided that trap. A s G P SBabel author Robert L ipe s ays , "We've s een an explos ion in applic ations us ing the A P I . I t's eas y enough that you don't really need to be either a geo- geek, a c artographer, or a progamming joc k to produc e s ome really us able res ults ." G oogle has provided a readable introduc tion to the A P I , available at http://www.google.c om/apis /maps /. T hey have c reated a "H ello World" of G oogle M aps that embeds a G oogle M ap on a web page: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Google Maps JavaScript API Example - simp <script src="http://maps.google.com/maps?file=ap type="text/javascript"></script> </head> <body> <div id="map" style="width: 300px; height: 300px">< <script type="text/javascript"> //<![CDATA[ if (GBrowserIsCompatible()) { var map = new GMap(document.getElementById("map") map.centerAndZoom(new GPoint(-122.141944, 37.4419 } //]]> </script> </body> </html> You need a bit of glue in the form of the above div element and the script src= line, but there are only two important lines of c ode required to c reate and dis play a map c entered on a s pec ific point. T he key c ode in this example c reates a new GMap objec t and then c enters the map on a s pec ific point: var map = new GMap(document.getElementById("map")); map.centerAndZoom(new GPoint(-122.141944, 37.441944), 4); I n programming terms , the firs t line c reates a new variable that c ontains a new GMap objec t. T he GMap objec t will be linked with the s ec tion of the page marked with <div id="map">. T he s ec ond line then c alls the centerAndZoom method of the GMap c las s . T he GMap c las s repres ents a s ingle map on your page (yes , you c an have multiple maps on the s ame page, eac h dis playing a unique view). T here are other c las s es that provide additional features , s uc h as GPoint to define a point and GPolyLine to define a line (there is not yet true polygon s upport), as well as a built- in XM L pars er and XSLT proc es s or. Take a look at the A P I doc umentation at http://www.google.c om/apis /maps /doc umentation. Hack 10. Add a Google Map to Your Web Site Here's how to get started using the Google Maps A PI. A t O 'Reilly's Where 2 .0 c onverenc e on J une 2 9 , 2 0 0 5 , G oogle announc ed an offic ial and doc umented A P I for G oogle M aps . T he A P I makes it pos s ible for anyone to add a G oogle M ap to a web page by c utting and pas ting a few lines of J avaSc ript from the G oogle M aps D eveloper's s ite. P eople reac ted to the new A P I in one or more ways . M y firs t ac t was to s c ratc h my own itc h by writing a bit of c ode to dis play my G P S waypoints on a G oogle M ap. Fortunately, better G P X- toG oogle M aps s olutions have been c reated, one of whic h is doc umented in "V iew Your G P S Trac klogs in G oogle M aps " [Hack #37]. A fter s c ratc hing that itc h, I looked to our G eoc oder.us s ite. Sc huyler had s pent a lot of time figuring out the C ens us Bureau's public T I G E R/L ine M ap Server A P I , and how to dis play the res ulting map with a neat little zoomable interfac e. T he res ults were s low and c lunky, but they worked. T he G oogle M aps A P I gets rid of the need for that level of head s c ratc hing! T he marc h of progres s in c omputers (pos s ibly in s oc iety at large) works by firs t figuring out ways to do new things , and then progres s ively making thos e tas ks eas ier, and leaving the old prac titioners to eat c at food and write programs for their O s borne luggable c omputer. I us ed G oogle M aps to bring the geoc oder.us s ite into the protec tive embrac e of the G oogle M aps A P I . G eoc oder.us , online at http://geoc oder.us /, is a free U .S. addres s geoc oder. You c an go to the web s ite and get the latitude and longitude for a U .S. s treet addres s . You c an als o us e a web s ervic e interfac e to get the latitude and longitude automatic ally for a group of addres s es [Hack #62]. You c an geoc ode us ing G oogle M aps by s c raping their s earc h res ults , but it's not a part of the offic ial A P I , and doing s o violates G oogle's terms and c onditions of s ervic e. By c ontras t, the G eoc oder.us s ite is bas ed on free data without limited terms of s ervic e for non- c ommerc ial us e. Figure 2 - 1 s hows the res ults of geoc oding the addres s of O 'Reilly M edia's headquarters with the original T I G E R/L ine map, with a pus hpin s howing the loc ation of the addres s that we jus t looked up. We'd like to replac e this s omewhat s low map generated by the C ens us Bureau with the muc h fas ter, more attrac tive, and more eas ily navigable maps offered by G oogle M aps . (T he original G eoc oder.us map view c an be s een at http://geoc oder.us /demo_tiger.c gi.) Figure 2-1. The Census Bureau map originally used by http://geocoder.us/ 2.2.1. Get a Developer Key T he firs t s tep in putting a G oogle M ap on your page is to generate a developer's key, whic h is an alphanumeric s tring that identifies your web s ite to G oogle, and helps them trac k us age of G oogle M aps . H aving to s ign up for a developer's key c an be s omething of an annoyanc e, but it's a s mall pric e to pay for being able to inc lude free (as in beer) maps on your web s ite with s uc h relative eas e. You'll need a dis tinc t developer's key for eac h direc tory on your s ite that inc ludes G oogle M aps . You don't need a key for eac h individual web page or s c ript. So if you have s everal pages that generate c alls to G oogle M aps from the s ame direc tory, you only need one key. Fortunately G oogle has made getting developer's keys as eas y as filling in a web form. T he G oogle M aps A P I page is at http://www.google.c om/apis /maps /. T his inc ludes links to doc umentation, examples , Terms of U s e, and the page to get your key. T here is a human vers ion of the Terms of U s e, then the full legales e vers ion. Figure 2 - 2 s hows the form with the U RL we want to us e for our maps . You mus t agree to the Terms of Servic e, then c lic k G enerate A P I Key. Figure 2-2. Enter a server and path to generate a developer's key I n our c as e, we wanted to enable G oogle M aps for a s ingle s c ript on our s erver. I f you want to enable G oogle M aps for a whole direc tory, you c an leave off the s c ript name and jus t s pec ify the hos t name and direc tory portion of the U RL . U nfortunately, the A P I key is n't good for direc tories ins ide the one you s pec ify, jus t the files and s c ripts in that direc tory. A lmos t ins tantly, a key will be generated, along with an example web page that G oogle refers to this as the "H ello World" of G oogle M aps . To put this on your web s ite, c opy the H T M L /J avaSc ript s ec tion in E xample 2 - 1 and pas te it into a new file on your own web s ite in the direc tory that you us ed when you c reated the developer's key. Example 2-1. Google Maps "Hello World" <!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"> <head> <script src="http://maps.google.com/maps?file=api&v=1& type="text/javascript"></script> </head> <body> <div id="map" style="width: 500px; height: 400px; border: 1p <script type="text/javascript"> //<![CDATA[ var map = new GMap(document.getElementById("map")); map.addControl(new GSmallMapControl()); map.centerAndZoom(new GPoint(-122.1419, 37.4419), 4) //]]> </script> </body> </html> D eveloper keys work only when they are us ed on a web page that lives in the s erver and direc tory that you s pec ified when you c reated the key. So you c an't c opy this lis ting and have it work until you c hange the developer's key to matc h your own. I n general, mos t of the c ode examples in this book will require you to s ubs titute your own valid developer key in order for them to work. 2.2.2. Hello, World! T he "H ello World" page s hown in E xample 2 - 1 is a s tandard H T M L page, with a bit of J avaSc ript. T he firs t interes ting part is the opening script element: <script src="http://maps.google.com/maps?file=api&v=1&key=[Your AP type="text/javascript"></script> T his imports the G oogle M aps J avaSc ript library into our page. A J avaSc ript c ompliant brows er will automatic ally fetc h the c ontents of the provided U RL . G oogle c an then c ompare the developer's key and the s erver name and path that is inc luded in the H T T P headers of your reques t with their rec ords , to s ee if they matc h. T he v=1 parameter in the above U RL is important, bec aus e it s pec ifies the G oogle M aps A P I vers ion that your s c ript expec ts . I f G oogle ever c hanges 'its A P I in s uc h a way that bac kwards c ompatibility is broken, the v parameter will allow your s c ript to c ontinue to func tion with the original A P I and give you s ome breathing room to update your c ode to the newer vers ion of the A P I . T he next three interes ting lines are: var map = new GMap(document.getElementById("map")); map.addControl(new GSmallMapControl()); map.centerAndZoom(new GPoint(-122.1419, 37.4419), 4); T hes e lines are pretty muc h s elf explanatory (for an objec toriented J avaSc ript programmer). But you don't need to unders tand muc h to put powerful maps on your own pages ! By default the s ize of the map is determined by the s ize of the H T M L element that c ontains the map. I n this example, we are us ing the div element to define a divis ion in the page, whic h provides an area that you c an c ontrol and format independently from other parts of the page. T he firs t line c reates a new GMap objec t and plac es it within the div named map. (T here's nothing magic about the name of the div element, by the waywe c ould c all it "T im," and s o long as the J avaSc ript mentioned the s ame name, it would s till work.) T he next line adds the s mall pan and zoom c ontrol to the map, and the third line c enters and zooms the map to longitude - 1 2 2 .1 4 1 9 , latitude 3 7 .4 4 1 9 at zoom level 4 . I n our example, the div element is 5 0 0 x 4 0 0 pixels high and has a 1 - pixel- wide gray border around the edge. You c an als o s pec ify the width and height in perc entages , s uc h as style="width: 50%; height: 40%". T he border its elf is totally optional, but it does s et the map off nic ely from the res t of the page. <div id="map" style="width: 500px; height: 400px; border: 1px solid #979 T he demo.cgi page at http://geoc oder.us / was already template driven, s o to add G oogle M aps func tionality I added the script= line to load the G oogle M aps library, and then inc luded thes e lines in my template: <div id="map" style="width: 500px; height: 300px; border: #979797"></div> <script type="text/javascript"> //<![CDATA[ var map = new GMap(document.getElementById("map")); map.addControl(new GSmallMapControl()); map.centerAndZoom(new GPoint([% long %], [% lat %]), 4); var point = new GPoint([% long %],[% lat %]); var marker = new GMarker(point); map.addOverlay(marker); //]]> </script> T he map will automatic ally s ize its elf to fit within the <div id="map"…> tag. I n our templating s ys tem (P erl's Template Toolkit, as it happens ), [% long %] will be replac ed with the c ontents of the variable long, or the longitude. T he only differenc es from the s ample c ode are that the s ample c ons tants for lat and long are replac ed with variables that will be s et in our program, and that a point marker is added for the loc ation of the addres s the us er looked up. 2.2.3. Getting Outside of Your Head T he "H ello World" example pres umes that the H T M L script element that imports the G oogle M aps A P I library into your web page is nes tled s afe within the H T M L doc ument's head element. C ertainly, this is the right plac e for it to go, but web brows ers are perfec tly c apable of handling script elements els ewhere in an H T M L doc ument. Furthermore, s ituations will oc c ur where you might want to inc lude the A P I library from els ewheres ay, for example, one where you have an H T M L templating s ys tem that provides a boilerplate header and footer for eac h page on your s ite. I n this c irc ums tanc e, you don't want the A P I library to be imported into every page on the s ite, bec aus e every page outs ide the direc tory as s oc iated with your developer's key will load up with a developer key error mes s age. Fortunately, you c an indeed import the A P I library almos t anywhere in your doc ument, s o long as it appears before the J avaSc ript c ode that needs to us e it. T he only thing you really need to know is that s ome brows ers I nternet E xplorer, in partic ularwill wait for a s c ript element to exec ute before rendering the res t of the page, to make s ure that the J avaSc ript its elf does n't modify the page layout. For s ome reas on, this behavior s ometimes has a bad interac tion with the G oogle M aps A P I when the s c ript element is us ed outs ide the heada J avaSc ript exec ution error is the mos t c ommon res ult. T he workaround is to add a defer="defer" attribute to the s c ript element, whic h will tell the brows er not to worry about it and get on with rendering the page. I n that c as e, our earlier s c ript element example looks like this : <script src="http://maps.google.com/maps?file=api&v=1&key =[Your API Key ]"type="text/javascript" defer="defer 2.2.4. Getting Right to the Point O nc e you've got a G oogle M ap on your page, adding points to it is eas y. You'll firs t c reate a new GPoint objec t, then c reate a marker ic on at that point, and finally add that marker to the map. We'll look more at adding points and lines to G oogle M aps in other hac ks . For now, enjoy Figure 2 - 3 , whic h s hows a pretty G oogle M ap replac ing our T I G E R map. But is that (always ) better? A re there reas ons not to us e G oogle M aps ? Yes ! G oogle M aps are great, and G oogle has a his tory and reputation of being the good guys , but it is a profit- making bus ines s and its goals might not be your goals . T he G oogle M aps terms of s ervic e are extremely generous , but when you us e G oogle M aps , you are relying on G oogle. T here are res tric tions on what you c an do with G oogle M aps ; for example, G oogle M aps c annot be us ed on a s ite that is inac c es s ible to the general public , s uc h as a paid premium c ontent s ite or a c orporate intranet. T here are limitations on volume, as well: if you expec t more than 5 0 ,0 0 0 hits in a day, G oogle expec ts to hear from you firs t. You c an't do c ertain things , s uc h as s c rape G oogle's images or remove its imprint from its imagery, and it has explic itly res erved the right to put ads on the maps at any time. You c an read more about the fine details at http://www.google.c om/apis /maps /faq.html, but you s hould als o review the terms of us e at http://www.google.c om/apis /maps /terms .html to be on the s afe s ide. Figure 2-3. http://geocoder.us/ with a Google Map T here are (at leas t c urrently) limits on the data available from G oogle. T here is far more aerial and s atellite data and map imagery available on the Web [Hack #12] from public Web M apping Servic e (WM S) s ervers than is available from G oogle. 2.2.5. See Also G oogle M aps are free- as - in- beer but not free- as - ins peec h. So if the power, beauty, and eas e of us e of G oogle M aps don't meet your needs , projec ts s uc h as G eos erver (http://geos erver.s f.net/), M aps erver (http://maps erver.gis .umn.edu/), and the Ka- M aps c lient interfac e to M aps erver (http://ka- maps .s f.net/) may fill the bill. T he downs ide, as is often the c as e with open s ourc e s oftware, is that you may have to do more of the work yours elf! O 'Reilly's Mapping Hacks and WebMapping I llus trated have muc h more to s ay about free and open s ourc e mapping s olutions . Hack 11. Where Did the User Click? Find the location of a click on a map and display it on your web page. G oogle M aps makes it eas y to put an interac tive map on your web page. A t http://www.naffis .c om/maphac ks /latandlon.html you c an c lic k on a map and have the c orres ponding latitude and longitude dis played in a G oogle M aps info box. I n Figure 2 - 4 you c an s ee the loc ation of the Was hington M onument. Figure 2-4. The Washington Monument at 38.88941 N, 77.03517 W T his s ite s olves the c ommon problem of figuring out the c oordinates of a loc ation from a map view and is an example of the s ort of quic k hac k that G oogle M aps has made pos s ible. T his page illus trates one way to get the latitude and longitude from a c lic k on a map and dis play res ults in an info box. So how c an you do it? A t http://mappinghac ks .c om/projec ts /gmaps /c lic k.html there is a s implified example of updating a form from the c oordinates of a c lic k on a map. T his is the H ello World map with three c hanges . A n H T M L form has been added to rec eive the latitude and longitude from the c lic k event: <form> Latitude: <input type="text" value="38.4094" id="click_lat onclick="this.blur()">&nbsp; Longitude: <input type="text" value="-122.8290" id="click_ onclick="this.blur()">&nbsp; </form> I n the s c ript, the latitude and longitude us ed to s et the initial map loc ation with centerAndZoom( ) now c omes from thes e form elements . T his c ode defaults to s tarting at 3 8 .4 0 9 4 N , 1 2 2 .8 2 9 0 W. C hange thos e values to c hange the initial foc us of the map. T he important c hange to the s c ript is the addition of a GEvent.addListener. T his c ode and the above form c an be pas ted into the body of your H T M L page. C hange the developer's key and you c an c apture c lic ks on a map: <script src= "http://maps.google.com/maps?file=api&v=1&key=replace type="text/javascript"> </script> <div id="map" style="width: 400px; height: 300px"></div> <script type="text/javascript"> //<![CDATA[ var map = new GMap(document.getElementById("map")); map.addControl(new GSmallMapControl()); // center and zoom to the lat/long in the form map.centerAndZoom(new GPoint( document.getElementById('click_long').v document.getElementById('click_lat').va GEvent.addListener(map, 'click', function(overlay, point) { if (point) { document.getElementById('click_lat').va document.getElementById('click_long').v } } ); //]]> </script> T his c ode adds a lis tener to the GMap objec t named map. I f you c lic k on the map, the c ode in the event handler will be run. T he c ode is given both an overlay (a marker) and a point. I f you c lic k on a marker, the overlay will be s et. I f you don't c lic k on a marker, then a GPoint objec t is given to the c ode. T hes e two lines are s tandard J avaSc ript. T hey as k the doc ument for the value of the elements click_lat and click_long. T he only elements with thos e names are the form elements . point.x and point.y are the longitude and latitude of the GPoint objec t that marks where you c lic ked. document.getElementById('click_lat').value = point.y; document.getElementById('click_long').value = point.x; T he end res ult is s hown in Figure 2 - 5 . Figure 2-5. The click is back T he next s teps are to add markers to the map from the c lic k, populate a map from an external data s ourc e, and update an external data s ourc e bas ed on the map. Hack 12. How Far Is That? Go Beyond Driving Directions Draw routes and calculate distances on your own Google Maps. H ow far is it? T hat's a bas ic ques tion we often as k of maps . G oogle M aps ' driving direc tions ans wer that ques tion, but driving direc tions are not (yet) ac c es s ible to the developer's A P I . M ore importantly, they s imply give driving dis tanc es as s uming the optimal route, where optimal is defined as getting there as quic kly as pos s ible in an automobile. T hey are not optimized for "s c enic drive" or "s afes t bic yc le route" or "quiet s troll" or "jog around the park." T here are at leas t two s ites that allow you to c reate routes and c alc ulate dis tanc es by c lic king on maps . T he G maps P edometer at http://www.s ueandpaul.c om/gmapP edometer/ s hown in Figure 2 - 6 es timates c umulative dis tanc eand even inc ludes a c alorie c ounter. U s e the s tandard map c ontrols to zoom into your area of interes t, and then c lic k Start Rec ording. When you double- c lic k a point on the map, it will rec enter to that s pot and add a marker there. T he s ec ond time you c lic k, the map will rec enter to your new point, the marker will be moved, and a line will be drawn from the las t point c lic ked to this one. E ac h time you do this , the Total D is tanc e and L as t L eg D is tanc e fields will be updated. Figure 2-6. Sue and Paul's Gmaps Pedometer H andling double c lic ks is a bit awkward and brows er dependent. Sue and P aul are doing brows er detec tion and then s etting the appropriate event handler bas ed on the brows er: if (navigator.appName == 'Microsoft Internet Explorer'){ document.ondblclick = handleDblClick; bIsIE = true; } else { window.ondblclick = handleDblClick; bIsIE = false; } D o you s ee the differenc e between the two ondblclick events ? I t is a differenc e in how they implement the D oc ument O bjec t M odel. I nternet E xplorer handles double- c lic ks at the doc ument level, henc e document.ondblclick and everyone els e (well, everyone els e ac c ording to this c ode) us es the window objec t, s o window.ondblclick. I n both c as es when there is a double- c lic k the variable bDoubleClickHappened is s et to true. T his will bec ome important in a bit. You c an't add a double- c lic k lis tener with the G oogle M aps A P I , s o the map does not direc tly c apture the double- c lic k event, but rather the moveend event, whic h ac c ording to the A P I doc umentation is "Triggered at the end of a dis c rete or c ontinuous map movement. T his event is triggered onc e at the end of a c ontinuous pan." T his means that when there is a double- c lic k event, Sue and P aul's handleDblClick func tion is c alled to s et the bDoubleClickHappened variable. N ext the G oogle M aps equivalent of handleDblClick is c alled. O nc e G oogle M aps has finis hed the move or pan, the moveend event is triggered, the func tion s et to lis ten for moveend events is c alled, and the anonymous func tion s et in this c ode is c alled: GEvent.addListener(map, "moveend", function() { if (bDoubleClickHappened){ addLeg(map.getCenterLatLng().x, map.getCenterLatLn drawPolyLine(gPointArray); } bDoubleClickHappened = false; }); I love this c ode! I t is an example of not always getting what you want, but finding a way to get what you need. We don't want to add a leg to our route on every move, jus t the ones that were initiated by a double- c lic k. When the double- c lic k handler was c alled, the bDoubleClickHappened variable was s et. T his c ode is c alled any time the map is moved, and if the map was doublec lic ked the addLeg and drawPolyLine func tions are c alled. Walk J og Run, s hown in Figure 2 - 7 , works in s imilar ways , but it c aptures s ingle c lic ks . I f you c lic k on the map it as ks if you want to s tart a new route. I f you s ay yes , it c aptures eac h c lic k, adds a marker, and draws a line c onnec ting all of the points you've c lic ked. Figure 2-7. Walk Jog Run I f this is the firs t c lic k, the route will be empty, s o startRoute() is c alled; otherwis e, this is the c ontinuation of a route, s o this point is added to the lis t. GEvent.addListener(map, 'click', function(overlay, point) if (overlay) { /* do nothing */ } else if (point) { if (route.length == 0) { startRoute(point); } else if (route[route.length-1].x != point.x route[route.length-1].y != point.y) route.push(point); currentRouteId = null; drawRoute(route); } } }); T he prototype for a c lic k event handler ac c epts an overlay and point parameter. T he overlay parameter is s et when the us er c lic ks on an overlay (that is , a line or marker). M os t of the time we handle c lic k events on markers by s etting a lis tener when the marker is c reated. T he drawRoute method is c alled when a new point is added and then goes through the lis t of points in the route, s etting up the text for the marker overlays and c alling this createMarker c ode to draw them, and then drawing the polyline of the route. function createMarker(point, mtext, icon) { var marker = new GMarker(point,icon); var html = "<b>Route Information</b><br />" + mtext; GEvent.addListener(marker, "click", function() { currentPoint = marker.point; map.centerAndZoom(currentPoint, map.getZoomLevel()); marker.openInfoWindowHtml(html); }); return marker; } T his illus trates the c reation of a marker with embedded text. I f you want your markers to open, add a lis tener for the c lic k event of the marker. T he s tandard c hoic e when c lic king a marker is the openInfoWindowHTML() method for the marker. T his pops up the s tandard H T M L- enabled info window, but you c an do anything when a marker is c alled. I n the wouldn't- it- be- c ool- if c ategory, wouldn't it be c ool if there were an I nternet- enabled game of Ris k us ing G oogle M aps as the interfac e? You would have a map of the world with markers that repres ent the Ris k c ountries . C lic king on the marker would bring up an H T M L form with your options in regards to that c ountryfrom jus t getting information, to launc hing an attac k. G iven the pac e of development on G oogle M aps , I s us pec t that googling for "G oogle M aps Ris k" will bring up three different implementations by s ome time Tues day (depending on whic h Tues day). Walk J og Run aims to be the http://del.ic io.us of maps for the running c ommunity. I t lets you s ave your own routes as well as s earc h and c omment on the s hared lis t of routes . You c an look at the information relevant to any of the intermediate points on the route. Walk J og Run s hows you an es timated time for the total route and for eac h s egment and allows you to delete any points from a route, unlike Sue and P aul's , whic h will only let you undo the las t point. L ines or P oints ? Both s ervic es let you add points by c lic king. G M aps P edometer s hows a marker for your s tart and mos t rec ent pos ition and hides the markers for the intermediate points . T he res ult is a c lean path overlaid on the map. Walk J og Run leaves the markers on the map, whic h lets you view s tatis tic s for eac h s egment of a c ompleted route. T hey eac h have advantages . Both G M aps P edometer and Walk J og Run aim to be full- featured s ites . A s a res ult, the c ode has a lot of detail that might make it hard to unders tand what is going on. O ur page at http://mappinghac ks .c om/projec ts /gmaps /lines .html has another example of adding markers and lines , and then c alc ulating dis tanc es in res pons e to c lic k events , as s hown in Figure 2 - 8 . Figure 2-8. Adding markers and lines When the us er c lic ks on the Start Rec ording button, the c ode s ets up a lis tener to proc es s c lic k events and the recording_flag is s et in the J avaSc ript. I f it is s et the c urrent pos ition is added to the arrays that hold our x and y pos itions (where, you'll rec all x equals longitude, and y equals latitude), and the drawRoute func tion is c alled. Finally, the c urrent latitude and longitude are s hown in the form elements click_lat and click_long. C apturing c lic ks is des c ribed in more detail in "Where D id the U s er C lic k? " [Hack #11]. GEvent.addListener(map, 'click', function(overlay, point) { if (point) { if (recording_flag > 0) { addPoint(point.y, point.x, keepPoint); x_array.push(point.x); y_array.push(point.y); drawRoute(); document.getElementById('click_lat').v document.getElementById('click_long'). } } } ); // end of GEvent.addListener T he drawRoute( ) func tion is a bit longer, but hopefully s traightforward. T he firs t tric k when updating markers is to c lear all the exis ting markers by c alling clearOverlays( ). N ext the c ode walks the array of longitudes , x_array. D is tanc es are c alc ulated for the s egment and the running dis tanc e of the route up to this point. T he segment_distance and total_distance form elements are updated to s how the dis tanc es . T he point is then c reated and a marker added. T he c reated point is added to the array points. O nc e all of the elements in the x and y arrays have been proc es s ed, the array of points is added as a new GPolyLine. function drawRoute() { map.clearOverlays(); var points = []; for (i = 0; i < x_array.length; i++) { if (i>0) { segment_distance_array[i] = calcDist(x_array[i x_array[i], y_array[1]); total_distance_array[i] = total_distance_array segment_distance_array[i]; document.getElementById('segment_distance').va segment_distance_array[i]; document.getElementById('total_distance').valu total_distance_array[i]; } else { // initialize the first element distances to 0 document.getElementById('segment_distance').va document.getElementById('total_distance').valu total_distance_array[0] = 0; segment_distance_array[0] = 0; } var point = new GPoint(x_array[i], y_array[i]); points.push(point); var marker = new GMarker(point); // define the text that appears in the marker var html = "location <b>" + y_array[i] + ', ' + x_ GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); }); map.addOverlay(marker); } map.addOverlay(new GPolyline(points)); } T his is not the only, or even bes t, way to do this ! T here is more than one way to do it! N ow, let's move on to c alc ulating dis tanc es . Walk J og Run and G M aps P edometer us e s imilar func tions to c alc ulate dis tanc e. I us ed the one from Walk J og Run in my demo bec aus e it s pec ific ally had a C reative C ommons A ttributionN onC ommerc ial- ShareA like lic ens e. /* calcDist() function is from Adam Howitt Copyright Adam Howitt 2005 Email: adamhowitt@gmail.com This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. http://creativecommons.org/licenses/by-nc-sa/2.5/ */ function calcDist(lon1,lat1,lon2,lat2) { var r = 3963.0; var multiplier = 1; // var multiplier = currentUnit == "miles" ? 1 : MILES return multiplier * r * Math.acos(Math.sin(lat1/57.295 Math.sin(lat2/57.2958) + Math.cos(lat1/57.2958 Math.cos(lat2/57.2958) * Math.cos(lon2/57.2958 lon1/57.2958)); }: N ote that the variable multiplier has been c ommented out. I n this c ode, I 'm dis playing the values only in miles . T he multiplier repres ents the c onvers ion fac tor from miles to whatever units you need. MILESASKM is Miles as Kilometers , the number of kilometers in one mile, or 1 .6 0 9 3 4 4 . T he multiplier is s et us ing the ternary operator. I f the c urrent unit equals miles then the multiplier is 1 (as 1 mile equals 1 mile); otherwis e, it is s et to the number of kilometers in a mile. You don't need to unders tand this formula, but if you want to learn more, s ee "H ow to c alc ulate dis tanc e in miles from latitude and longitude" at http://www.meridianworlddata.c om/D is tanc e- C alc ulation.as p. T he c ons tant 3 ,9 6 3 is c los e enough to the radius of the earth in s tatute miles . 5 7 .2 9 5 8 is the number of s tatute miles (5 ,2 8 0 feet, as oppos ed to nautic al miles ) in one degree of latitude anywhere, or one degree of longitude at the equator. A nautic al mile is defined as 1 minute of latitude (or 1 minute of longitude at the equator). With the multiplier c ode c ommented out, you c an c opy this func tion into your own c ode and c alc ulate dis tanc es between anything. G o dis tanc e c razy! Hack 13. Create a Route with a Click (or Two) You can even take Google Maps where the roads don't go. D riving direc tions don't always take you where you want to go, or they may take you the wrong way. You c an us e a little G oogle M aps hac k to build up your own lis t of points that c an be s aved in different formats that c an be loaded into a G P S or other tool that s upports the G P X s tandard. T he c lic k- to- route tool is at http://mappinghac ks .c om/projec ts /gmaps /c lic ktoroute.html. You c lic k on the map to c reate a c ontinuous trac k. A n example is s hown in Figure 2 - 9 . Figure 2-9. No roadsonly walkers, horses, and bikes here! O nc e you've c reated your route, c lic k on one of the E xport buttons . C lic king on C SV (C omma Separated Values ) generates a pure- text file with the latitude and longitude s eparated with c ommas . G P X Trac k makes a G P X Trac klog file. G P X Route generates a s et of points that c an be loaded into a G P S. H ere is a s ample of the route as a C SV file: 38.4047068183193, -122.84743666648865 38.4041771393969, -122.84764051437378 38.403941725296505, -122.84796237945557 A nd here is an example of a G P X Trac klog: <?xml version="1.0"?> <gpx> <trk><name>Google Maps Hacks is Good</name> <trkseg> <trkpt lat="38.41324840580697" lon="-122.84113883972168">< <trkpt lat="38.402688973080245" lon="-122.82877922058105"> <trkpt lat="38.4049085997449" lon="-122.84637451171875"></ </trkseg> </trk> </gpx> M any G P S units have a limit on the number of points that c an be us ed in a route. T his G P SBabel c ommand will s implify your lis t of points to 3 0 . gpsbabel -r -i gpx -f route.gpx \ -x simplify,count=30 -o gpx \ -F shorter_route.gpx See "L oad D riving D irec tions into Your G P S" [Hack #35] for more on reduc ing the number of points and loading a route file into your G P S. 2.5.1. The Code T his hac k is almos t identic al to "H ow Far I s T hat? G o Beyond D riving D irec tions " [Hack #12], with the addition of one func tion that generates the formatted lis t of points , and buttons to c all this func tion. T he buttons are ins erted with this H T M L c ode: <input type="button" value="Export CSV" onClick="exportPoi <input type="button" value="Export GPX Track" onClick="exportPoints('track'); "> <input type="button" value="Export GPX Route" onClick="exportPoints('route'); "> T he onClick event is s et to c all the exportPoints func tion with a parameter to s et the format of the exported points . T his example s hows the exportPoints func tion with the c ode for the G P X exports removed. T he G P X format is s imple XM L , and that c lutters up the example. function exportPoints(format) { var export_string; if (format=='csv') { //csv header export_string = export_string + "latitude, longitu } for (i = 0; i < x_array.length; i++) { var lon = x_array[i]; var lat = y_array[i]; if (format=='csv') { export_string = export_string + lat + ", " } } // write into document document.getElementById("output").value=export_string; } T he res ults of your s elec ted route will appear in a textarea below the map. You may need to s c roll down to s ee the lis t. You c an s elec t the whole text area and pas te it into your own doc ument. O nc e you have a lis t of points to map bac k on G oogle M aps [Hack #37], export the points to your G P S [Hack #35], and even c alc ulate driving direc tions between the points [Hack #36]. You c an als o us e this tec hnique to plan a trip or to explore more about a trip you took without a G P S (or a trip where the G P S didn't work bec aus e the darn s atellite s ignals wouldn't penetrate the s teel c anyons of the c ity). Hack 14. Create Custom Map Markers A dding custom markers to your Google Map can enhance its readability and appeal. A lmos t immediately after the G oogle M aps A P I announc ement, J eff Warren made a hac k that us ed c us tom ic ons to do a map depic ting Star Wars ATATs attac king G oogle's home town, P alo A lto, as s hown in Figure 2 - 1 0 . You c an launc h your own I mperial as s ault on G oogle's home bas e at http://www.ves taldes ign.c om/maps /s tarwars .html. T his hac k immediately demons trated the flexibility of G oogle's new A P I . I f you wanted to us e a hous e ic on ins tead of the generic marker, you c ould. L ikewis e, if you wanted to make a multiplayer game us ing G oogle M aps , the A P I was flexible enough to allow you to let us ers s ubmit their own ic ons . To c reate an ic on, you need two things : a foreground image for the ic on and a s hadow image in the P N G 2 4 - bit file format. I f you are only c hanging the c olor of the generic marker, you c an reus e the generic s hadow, but for this hac k we're going to make s omething c ompletely different. 2.6.1. Find the Right Foreground Image I ns tead of doing s omething generic and boring, I dec ided to take a heads hot of a friend of mine and turn it into a G oogle M aps marker ic on! I grabbed a s uitable s hot from a digital photo, loaded it into A dobe P hotos hop, and s tarted eras ing, as s hown in Figure 2 - 1 1 . A bout halfway through, I c ould tell this was going to make a great foreground image. Figure 2-10. You too can send Imperial ATATs to attack Google's headquarters I f you're not into c ommerc ial s oftware, the G N U I mage M anipulation P rogram, or G I M P, offers an open s ourc e alternative with the s ame bas ic features . You c an find the G I M P at http://www.gimp.org/. O nc e I finis hed eras ing around Karl's head, I s c aled down the image, c ropped it, and expanded the c anvas to give Karl's head s ome breathing room. I wouldn't want him to get c laus trophobic , and when we s tart working on the s hadow, we're going to need a bit of extra room. You c an s ee the finis hed res ult in Figure 2 - 1 2 . Finally, I went to the File Save for Web option, and s aved my file in the P N G - 2 4 format with trans parenc y. 2 4 - bit P N G format is ideal for c us tom map ic ons , bec aus e it's los s les s and the alpha layer s upport allows for s ome wonderful trans parenc y effec ts . 2.6.2. Casting the Shadow N ow that you have the foreground image s aved, you might want to s how it on your map right awaybut don't run ahead yet. We're going to want to reus e our work to c reate a s hadow image. T his is an image that gets plac ed behind the foreground image to give it that 3 D effec t, like it's s itting on top of the s urfac e of your map. U s ing a s hadow is optional, but it gives your c us tom markers more depth and c harac ter. T his s tep is a little more c omplic ated, but definitely worth your time. Figure 2-11. Erasing around the head to create the foreground image H ere's the rundown, again from A dobe P hotos hop: 1. I mage A djus tments Brightnes s /C ontras t Set both the Brightnes s and C ontras t to -100. 2. E dit Free Trans form A djus t the layer to exac tly half its original height by grabbing the top line and dragging down. 3. E dit Trans form Skew G rab the top line and drag to the right to s kew the image 4 5 degrees . Figure 2-12. The final version of the foreground image 4. I mage C anvas Size A djus t the c anvas s o that it fits your new drop s hadow. G ive it a bit of extra room s o nothing gets c ut off. 5. Filters Blur G aus s ian Blur T his will give your s hadow that fuzzy look. Try s etting it to 0.9. 6. L ayer O pac ity L ayer Style Blending O ptions Fill M ake the s hadow trans parent, s o it does n't look like a big blac k blob. Set the Fill O pac ity to about 5 0 % . 7. File Save for Web Remember to keep it a 2 4 - bit P N G file with Trans parenc y. Figure 2 - 1 3 s hows the finis hed s hadow layer for the ic on. 2.6.3. Add Your New Icon to a Map N ow that the two s ourc e images have been c reated, let's add them to your map. I f we were making a generic marker, we would c reate an ins tanc e of the GMarker c las s , us ing a GPoint objec t as an argument. To c reate a c us tom marker on the other hand, we need to add an additional argument to the GMarker c ons truc tor, a GIcon objec t. H ere is an example of how to us e the GIcon c ons truc tor: Figure 2-13. The head has a shadowy background var icon = new GIcon(); icon.image = "http://igargoyle.com/mapfiles/karol.png"; icon.shadow = "http://igargoyle.com/mapfiles/karolShadow.p icon.iconSize = new GSize(43, 55); icon.shadowSize = new GSize(70, 55); icon.iconAnchor = new GPoint(0, 0); icon.infoWindowAnchor = new GPoint(9, 2); icon.infoShadowAnchor = new GPoint(18, 25); T he GSize objec t holds the s ize of your image. I n this c as e, icon.image has a width of 4 3 pixels and a height of 5 5 pixels . T he c orres ponding icon.shadow has a width of 7 0 pixels and is 5 5 pixels high. Spec ifying thes e image dimens ions are c ritic al, bec aus e if you don't, your photo will end up being dis torted. T he iconAnchor property s tores the point on the ic on, relative to the top left c orner of our ic on image, where it s hould be anc hored to the map. T he infoWindowAnchor property is s imilar, exc ept it s pec ifies the anc hor point on the image of the information window. Finally, the infoShadowAnchor indic ates where the drop s hadow below the info window s hould be anc hored under your marker. I f your ic on is s haped like the s tandard Ride Finder ic ons , you c an leave it as it is ; otherwis e, you s hould us e your image editor to figure out where thes e points lie on your c us tom ic on. Finally, to add this to a new marker, you need to us e the GMarker c ons truc tor with the GIcon as an extra argument. var marker = new GMarker(point, icon); map.addOverlay(marker); Figure 2 - 1 4 s hows our c us tom map ic on on a s atellite map s howing Burning M an. Figure 2-14. The disembodied flying heads all swarm to Burning Man So now that you know how to c reate an ic on with both a foreground image and a s hadow, break out your artis tic s kills and make your map uniquely different. You c an make it look profes s ional, s tylis h, or even s illy, like I did. T he mes s age your map c ommunic ates will be all the s tronger for it. 2.6.4. See Also Find s ome good, free, generic ic ons at http://brennan.offwhite.net/blog/arc hives /0 0 0 2 1 1 .html. Tom Longs on Hack 15. Map a Slideshow of Your Travels Show your f riends and f amily not just what you saw on your vacation, but where you saw it. Wouldn't it be c ool to be able to s how your friends and family not only what you s aw on your vac ation, but als o where eac h photo was taken? T hanks to G oogle M aps ' s imple A P I , you c an very eas ily make a s lides how to put on your web s ite. Travelogue s lides hows are as old as the film s lide projec tor its elf. T he G oogle M aps A P I and a dab of J avaSc ript c an dus t off the anc ient tradition, and s how off the plac es you've been with an amazing amount of detail. What's more, little touc hes like the A P I 's animated map panning func tion lend a s ens e of motion to the s tory of your travels . Figure 2 - 1 5 s hows a s lides how I put together of my vac ation las t year to the Burning M an Fes tival in Blac k Roc k C ity, N evada. T his s lides how c an als o be s een online at http://igargoyle.c om/s lides how.html. Figure 2-15. Make a slideshow that will captivate your friends and family For my map, I took the photos from Blac k Roc k C ity and added titles and des c riptions for eac h image to better tell the s tory of my trip. Sinc e my relatives live on the other s ide of the world, this makes it very eas y for me to update them about what's going on in my lifeand s how off photos without having to lob off enormous emails , s tuffed with unreadable attac hments . To get s tarted, you're going to need photos , eac h with its own latitude and longitude c oordinates . T he eas ies t way to do this is by bringing along a G P S when you photograph, and mark eac h image with a waypoint or write the loc ation on a notepad. I f you're interes ted in doing large batc hes of photos , pic k up a c opy of O 'Reilly's Mapping Hacks and learn more about c ros s referenc ing G P X trac klogs with the E XI F times tamp of digital photographs . alternatively, you c an adapt the tec hnique des c ribed in "Where D id the U s er C lic k? " [Hack #11], and us e your memory and a few map c lic ks to find the c oordinates of where your photos were taken. 2.7.1. The Code H owever you as s emble the metadata for your photographs , you'll wind up with a J avaSc ript objec t that probably looks like this : var myObj = {"photos": [ {"img": "http://igargoyle.com/theman.jpg", "longitude": "-119.236402821", "latitude": "40.75 "title": "Black Rock City: 2005", "description": "A Playa Slideshow using Google Ma this to your friends, and when it loads, it will start pla automatically."}, {"img": "http://igargoyle.com/hammockhangout.jpg", "longitude": "-119.233165", "latitude": "40.75903 "title": "The Hammock Hangout", "description": "A GIANT tent that uses passive so stay cool during the day. Housed 50 hammocks, and had room up their own too."}, {"img": "http://igargoyle.com/us.jpg", "longitude": "-119.246943567", "latitude": "40.75 "title": "Some of the gang in camp ROAMnet", "description": "Karl, Jay, Jana, and Nym."}, ] }; To s et up the timers for thes e s lides , we c an ac c es s the data array like s o: for (i = 0; i < myObj.photos.length; i++) { img = myObj.photos[i].img; longitude = myObj.photos[i].longitude; latitude = myObj.photos[i].latitude; title = myObj.photos[i].title; description = myObj.photos[i].description; loadPhoto(img, longitude, latitude, i, title, descrip } T he loadPhoto func tion takes thes e arguments and c reates an anonymous func tion that c alls the brows er's built- in window.setTimeout func tion. T his is the mos t important part of the hac k bec aus e it tells the func tion to run at a c ertain time, s pec ified in millis ec onds . I n this func tion, 10000*time c alc ulates the time for eac h photo, s o the firs t photo loads immediately, the s ec ond photo loads after 1 0 s ec onds , the third photo loads after 2 0 s ec onds , and s o on. function loadPhoto(photoURL, longitude, latitude, time, ti { // A simple timer, which delays the creation of the ne // marker, changes the photo, and recenters the map. window.setTimeout( function() { // Create and place a marker for the photograph's var marker = new GMarker(new GPoint(longitude, lat map.addOverlay(marker); // Change the titleBox and descriptionBox to refle // new photo's title and description document.getElementById("titleBox").innerHTML = ti document.getElementById("descriptionBox").innerHTM // Change the src location of the photo element to document.getElementById("photo").src = photoURL; // Have our Google Map recenter or pan to the new map.recenterOrPanToLatLng(new GPoint(longitude, la }, 10000 * time); // Change 10000 to speed up or slow slideshow. } T he func tion ins ide the setTimeout does all the real work, though. To begin with, it c reates the marker for your photo us ing the GMarker c ons truc tor, and then a c all to the map's addOverlay func tion. Sec ondly, this func tion dis plays the title and des c ription on the page by c alling eac h c ontainer and s etting its res pec tive innerHTML properties . N ext, the func tion c hanges the s ourc e loc ation of the only img element on our page to that of the c urrent photo. O nc e all this is done, the map is re- c entered on the new marker by us ing a c all to the map's recenterOrPanToLatLong method. I n my example, I made s ure the points were c los e enough together to c aus e the map to pan ins tead of re- c enter, bec aus e it's great to s ee the map glide from one loc ation to another. A s lides how is a wonderful way to c aptivate your audienc e and tell a s tory. So get out there and make s omething truly wonderful that your family and friends will remember for years to c ome! 2.7.2. See Also T he s lides how c onc ept c an als o be integrated with photos s tored on Flic kr [Hacks #47 and #48]. Tom Longs on Hack 16. How Big Is the World? If you wanted to make your own Google Maps server, how much hard drive space would you need? G oogle M aps renders maps by s titc hing s mall images together. We s eek to dis c over the s torage c apac ity of s uc h an image repos itory. By c apturing and examining s c reens hots of G oogle M aps in ac tion, we c an es timate the map s c ale at eac h zoom level, whic h will give us an idea of how muc h s pac e is nec es s ary to s tore all the tiles for that zoom level. Finally, we c an add the s torage requirements for eac h zoom level and apply s ome s imple rules of thumb to arrive at an idea of how muc h hard drive s pac e is nec es s ary to s upport a web mapping s ervic e s uc h as G oogle M aps . 2.8.1. Economies of Scale Firs t, we need to dis c over the s c aling fac tors us ed at eac h of the fifteen zoom s teps . To ac c omplis h this analys is , we us e a tool c alled A rt D irec tor's Toolkit, whic h c omes bundled with M ac O S X and whic h offers an overlay des ktop ruler image for meas uring pixel dis tanc es ons c reen. I n zoom levels 0 to 6 , we meas ure the pixel length between the northeas t c orner of C olorado and the s outheas t c orner of Wyoming. T his dis tanc e is c learly marked on the map as a horizontal line, whic h makes meas uring it eas y. Figure 2 - 1 6 depic ts zoom levels 0 , 1 , and 2 , where the dis tanc es in ques tion are 1 2 , 2 4 , and 4 8 pixels , res pec tively. Figure 2-16. Zoom levels 0 through 2 I n Figure 2 - 1 7 , we s ee that, for zoom levels 3 , 4 , and 5 , the s ame dis tanc es are 9 8 , 1 9 6 , and 3 9 4 pixels . For zoom level 6 , the dis tanc e between the northeas t c orner of C olorado and the s outheas t c orner of Wyoming meas ures out at 7 9 0 pixels . Zoom level 7 was s kipped bec aus e there was nothing to meas ure for its maller things were too s mall, and bigger things were too big. (Skipping it did not negatively impac t the analys is .) Figure 2-17. Zoom levels 3 through 5 I n zoom levels 8 through 1 4 , we meas ure the pixel length of the path from the inters ec tion of Trenton Street and E as t 1 6 th A venue to the inters ec tion of Verbena Street and E as t 1 6 th A venue in D enver, C olorado, whic h is within the metropolitan area c los es t to our previous loc ations . For zoom level 8 , the dis tanc e is 9 pixels . For zoom levels 9 , 1 0 , and 1 1 , the dis tanc es are 1 9 , 3 7 , and 7 4 pixels . T he res ults are s hown in Figure 2 - 1 8 . Figure 2-18. Zoom levels 8 through 11 For zoom levels 1 2 , 1 3 , and 1 4 , the dis tanc es are 1 4 7 , 2 9 5 , and 5 9 0 pixels . Figure 2 - 1 9 depic ts this meas urement. Figure 2-19. Zoom levels 12 through 14 N ow we c an take the information from thes e meas urements , and attempt to es tablis h the numeric s c ale ratio between one zoom level and the previous one. Figure 2 - 2 0 pres ents the s ame relations hips in three nic ely formatted line graphs and Table 2 - 1 s ummarizes the data we c ollec ted. Figure 2-20. Length ratios visualized in a series of line graphs T he c onc lus ion we draw is that we c an be fairly c ertain that the s c ale doubles with every inc rement of the zoom bar. Table 2-1. Length ratios from one zoom level to the previous zoom level Zoom State border length Ratio Zoom Street length Ratio 0 12 n/a 8 8 n/a 1 24 2 9 19 2 .3 8 2 48 2 10 37 1 .9 5 3 98 2 .0 4 11 74 2 4 196 2 12 147 1 .9 9 5 394 2 13 295 2 .0 1 6 790 2 .0 1 14 590 2 2.8.2. So, How Much? By zooming almos t all the way out in G oogle M aps , we s ee that N orth A meric a fits nic ely in a 6 0 0 x 8 0 0 pixel rec tangular region, amounting to 4 8 0 ,0 0 0 pixels . A rmed with this approximation, we proc eed to es timate the pixel- area of this body at eac h zoom level. Table 2 - 2 depic ts thes e relations hips . Table 2-2. Approximate area in pixels of North America for each zoom level Zoom Scale Width Height A rea in pixels 0 1 800 600 4 8 0 ,0 0 0 1 2 1 ,6 0 0 1 ,2 0 0 1 ,9 2 0 ,0 0 0 2 4 3 ,2 0 0 2 ,4 0 0 7 ,6 8 0 ,0 0 0 3 8 6 ,4 0 0 4 ,8 0 0 3 0 ,7 2 0 ,0 0 0 4 16 1 2 ,8 0 0 9 ,6 0 0 1 2 2 ,8 8 0 ,0 0 0 5 32 2 5 ,6 0 0 1 9 ,2 0 0 4 9 1 ,5 2 0 ,0 0 0 6 64 5 1 ,2 0 0 3 8 ,4 0 0 1 ,9 6 6 ,0 8 0 ,0 0 0 7 128 1 0 2 ,4 0 0 7 6 ,8 0 0 7 ,8 6 4 ,3 2 0 ,0 0 0 8 256 2 0 4 ,8 0 0 1 5 3 ,6 0 0 3 1 ,4 5 7 ,2 8 0 ,0 0 0 9 512 4 0 9 ,6 0 0 3 0 7 ,2 0 0 1 2 5 ,8 2 9 ,1 2 0 ,0 0 0 10 1 ,0 2 4 8 1 9 ,2 0 0 6 1 4 ,4 0 0 5 0 3 ,3 1 6 ,4 8 0 ,0 0 0 11 2 ,0 4 8 1 ,6 3 8 ,4 0 0 1 ,2 2 8 ,8 0 0 2 ,0 1 3 ,2 6 5 ,9 2 0 ,0 0 0 12 4 ,0 9 6 3 ,2 7 6 ,8 0 0 2 ,4 5 7 ,6 0 0 8 ,0 5 3 ,0 6 3 ,6 8 0 ,0 0 0 13 8 ,1 9 2 6 ,5 5 3 ,6 0 0 4 ,9 1 5 ,2 0 0 3 2 ,2 1 2 ,2 5 4 ,7 2 0 ,0 0 0 14 1 6 ,3 8 4 1 3 ,1 0 7 ,2 0 0 9 ,8 3 0 ,4 0 0 1 2 8 ,8 4 9 ,0 1 8 ,8 8 0 ,0 0 0 I f we add up the areas , we find that 1 7 1 ,7 9 8 ,6 9 1 ,6 8 0 ,0 0 0 (1 7 1 trillion) pixels are needed to s tore all the bitmap information. Sinc e all maps are made up of 2 5 6 x 2 5 6 tiles , one c an venture to gues s that there are 1 7 1 ,7 9 8 ,6 9 1 ,6 8 0 ,0 0 0 ÷ (2 5 6 x 2 5 6 ) = 2 ,6 2 1 ,4 3 9 ,9 9 7 (2 .6 billion) potential tile files . T he c olor his togram of the maps in Figure 2 - 1 9 s hows that about 6 0 perc ent of it is water. A s s uming that G oogle obs erves s uc h s tatis tic s , we gues s that a s ingle tile is us ed for all water regions . T here are als o lots of regions (s uc h as tundra, des erts , and fores ts ) where uniformly c olored tiles c an be us ed. C omputing this ac c urately is diffic ult, but we will s ay it amounts to 1 0 perc entof the data. So, only 3 0 to 4 0 perc ent of the tiles have unique data on them. T his reduc es the amount of data to 5 0 to 7 0 trillion raw data pixels s tored in 7 5 0 million to 1 billion image files . A s s uming a modes t 1 byte per 6 pixels c ompres s ion ratio (for L ZW- enc oded G I F format images ), the s torage required might be 5 0 to 7 0 trillion pixels * (1 byte/6 pixels ) = 8 to 1 1 terabytes . I f we c ons ider that G oogle s upports three map types at pres ent (M ap, Satellite, and H ybrid), this s ugges ts that 2 4 to 3 3 terabytes are needed to s tore all the image data. 2.8.3. What About the Rest of the World? Sinc e we did our original analys is , G oogle M aps U K, G oogle M aps J apan, and G oogle E arth were introduc ed, providing further evidenc e of a lofty goal to c reate a world atlas . So this puny analys is (as c ompared to the world's topology and arc hitec tural landmark data nec es s ary for G oogle E arth), makes an attempt at c overing the whole earth with tiles . To do this , we mus t learn more about the world. T he CI A World Factbook provides jus t what we need. To wrap the world requires 5 1 0 million km2 of s urfac e. O f this , only 2 9 .2 % , or 1 4 7 million s quare kilometers , is land. N orth A meric a's s urfac e area is about 2 1 .4 million s quare kilometers (9 .9 for C anada, 9 .6 for the U nited States , and 1 .9 for M exic o) or 1 3 .6 % of the world's total land s urfac e area. We c onc luded from our analys is that c overing N orth A meric a requires s omewhere between 7 5 0 ,0 0 0 and 1 billion dis tinc t tiles to be fully des c ribed. N ow we know that this is only 1 3 .6 % of the tiles nec es s ary to des c ribe the world's land tiles . So, anywhere from 5 .5 to 7 billion dis tinc t tiles ought to c over the world's s urfac e area. A s s uming the c ompres s ion ratio des c ribed above, the world's tiles amount to 6 1 to 8 1 terabytes jus t for the rendered vec tor maps , and 182 to 243 terabytes for all three map types . T hat's a lot of databut then s toring and retrieving huge amounts of data is G oogle's s toc k in trade! Sinc e this was written, G oogle has added three more zoom levels to G oogle M aps , for a total of 1 8 ! T he extra math is left as an exerc is e for the interes ted reader. I n s ome ways , it s eems a bit c omic al to attempt s uc h a c alc ulation where every s tep of the way requires an approximation. T hat's why in the end we have s uc h a wide c has m of error. A nd, of c ours e, this rough analys is does not c over area dis tortion introduc ed by mapping the globe's points onto a two dimens ional s urfac e. H owever, even with this rough es timate, we think we've managed to get a dec ent s ens e of jus t what it takes to map the entire world in the s tyle that G oogle M aps has pioneered. Michal Guerquin and Zach Frazier Chapter 3. Mashing Up Google Maps 3.1. Hacks 1728: Introduction I n mus ic , when you c reate a new s ong by taking the melody from one s ong and the lyric s from another, it is c alled a mas hup. A lot of times things go poorly, but now and then the res ults are s tunning. What happens when you take piec es from two web s ites and mix them together? You get a Web 2 .0 mas hup. T he Web is moving from a c ollec tion of dis c onnec ted web s ites to a ubiquitous c omputing platform. T his new reality is often referred to as Web 2.0. I n the beginning, we had s tatic web s ites with a few links between them. T his evolved into dynamic c ontent and data- driven s ites . T he next s tep has been us ing the web as a platform. eBay is a us eful s ite for buying and s elling trinkets , tras h, or treas ure. I n that role, it is what might be c alled "Web 1 .5 ." But eBay is als o a platform. T here is a whole ec ology that has built up around eBay that us es the platform in ways that were not initially intended by the programmers . A mazon and G oogle Searc h have als o bec ome platforms . A mazon, eBay, and G oogle (not to mention Flic kr, del.ic io.us , and many more) have c reated public A pplic ation P rogramming I nterfac es (A P I s ) that allow anyone to mix and matc h information from one s ite with information from another. T he mis s ing piec e in the ec ology of open web A P I s has been loc ation. N early everything we do, on the Web or off, has a loc ation. E verything we touc h, write about, read, think, or work on has to happen s omewhere. E verything has a geos patial c omponent. P erhaps the geos patial c omponent of s ome things is irrelevant. D o you really c are where you were when you remembered to add dis h s oap to your s hopping lis t? Yes ! We are the s pec ies that looks for patterns , and where we are, and where we have been, is one of the s tronges t s ourc es of pattern in our lives ! We are able to learn huge amounts from rooting through other people's tras h, er, treas ureand we c an learn s imilar amounts by analyzing the debris of our pas s ing as rec orded in pos ition. A t the Where 2 .0 c onferenc e in San Franc is c o in J une of 2 0 0 5 , T im O 'Reilly explained his fas c ination with P aul Rademac her's H ous ing M aps s ite (http://www.hous ingmaps .c om), des c ribed in "Find a P lac e to L ive" [Hack #23]: "G oogle M aps with C raigs lis t is the firs t true Web 2 .0 applic ation, as neither of the s ites was involved…. A developer put it together. H ac kers are teac hing the indus try what to do." G oogle M aps brought loc ation into the world of open A P I s , and the res ults have been s tunning! T he res ult brilliantly demons trates the eleganc e of the Web 2 .0 c onc epta brave new world in whic h hac kers c an c ombine open s tandards and open A P I s in novel ways to c reate new s ites and s ervic es that fill a need or are s ometimes jus t plain c ool. M ixing it up with data or c ode from multiple s ites is the heart of the Web 2 .0 experienc e. T hes e mas hups are leading the way to a Web that allows eac h of us to author our unique experienc es of the Web, and to s hare thos e experienc es with others . I n this c hapter we explore jus t a few of the nearly c ountles s G oogle M aps mas hups that have c ome into exis tenc e in jus t a few months . Hack 17. Map the News See where it happened with BBC News and Google Maps. H uman beings have s pent mos t of their time in s mall groups of 1 0 0 - odd individuals , and our information- proc es s ing abilities c ame from thos e experienc es , not from our c urrent world. I f we want to keep trac k of dis turbanc es in D enmark, fog in Finland, elec tions in I s tanbul, and war all over, we need tools to help us : as s is ted c ognition. A t http://boneill.ninjagrapefruit.c om/wp- c ontent/bbc /newmaps / you c an s ee the loc ations as s oc iated with the las t 1 2 hours of BBC news , as s hown in Figure 3 - 1 . A s with mos t c artographic efforts , there is the nearly inevitable, but s till regrettable, foc us on jus t one plac es o the las t 1 2 hours of BBC news will generally be more interes ting if you prefer news of the Britis h I s les . C lic king on the markers brings up an information window like that s hown in Figure 3 - 2 . T his inc ludes the lead from the s tory, as well as date and time information and a link to the full s tory. A s we c an s ee, human interes t and s oft news c an make an appearanc e! T his hac k is pos s ible bec aus e, well, the BBC roc ks . T hey have dec ided that their res pons ibility to the public trus t means they need to open their c ontent to the public . See http://bac ks tage.bbc .c o.uk/ for data and ideas s o that you c an "build what you want us ing BBC c ontent." T his is the heart of the Web 2 .0 c onc eptthe idea that open A P I s and open formats allow us to make more us e of and draw ric her c onnec tions between the vas t amounts of information that are already out there on the I nternet. Figure 3-1. Geolocations for the last 12 hours of BBC News Figure 3-2. Not all geolocated news is created equal I n 2 0 0 3 , the BBC announc ed plans to open their arc hives of radio and televis ion programs for non- c ommerc ial us e. I ts intent is good, but s adly there are is s ues that mus t be worked out. Ben H ammers ley wrote a s tirring c all to ac tion for the G uardian at http://www.guardian.c o.uk/online/s tory/0 ,,1 5 2 2 3 5 1 ,0 0 .html. T he arc hive, Ben writes , "is a vault of the mos t important public c ulture of the pas t three generations . I t is a gift for the future that is s o far- s ighted, and s o muc h a good thing, that it is the duty of the BBC and, es pec ially, the government to follow through." What's more, "[d]igital tec hnology not only makes the C reative A rc hive pos s ible, but by doing s o makes it a moral imperative." M apping the news is an example of s omething we c an do now, with jus t the textual c ontent. I magine the pos s ibilities of geoc oded audio and video! A s Ben's artic le c onc ludes , "N ow that we c an, we mus t." Hack 18. Examine Patterns of Criminal Activity A ugment your local government's crime reports with Google Maps. C hic agoc rime.org (http://www.c hic agoc rime.org/), one of the original G oogle M aps hac ks , is a freely brows able databas e of c rimes reported in C hic ago. I t c ombines data that was s c reen s c raped from the C hic ago P olic e D epartment's Web s ite (http://1 2 .1 7 .7 9 .6 /) with G oogle M aps , enabling many new ways for C hic ago res idents to keep tabs on their neighborhoods and explore c rimes reported throughout their c ity. T he s ite lets you brows e c rime reports in many ways : c rime type, s treet name, date, polic e dis tric t/beat, ZI P C ode, c ity ward, and generic "loc ation" (e.g., bowling alley, bar, gas s tation). Figure 3 - 3 s hows a ras h of peeping toms around res idential C hic ago, while Figure 3 - 4 s hows the loc ations for bogus c hec k reports . T here's als o a C ity map page at http://www.c hic agoc rime.org/map/ that lets you c ombine s earc h c riteria. Figure 3-3. The most recent reports of illegal surveillance activity in Chicago Figure 3-4. The most likely places to find bogus checks in Chicago I developed C hic agoc rime.org over a month's worth of nights and weekends in A pril 2 0 0 5 . H aving gotten exc ited by the rec ently launc hed (at that time) G oogle M aps s ite, I s pent a few evenings digging around G oogle's J avaSc ript and trying to embed c us tom maps into my own pages . A fter s ome hac king, I was able to dis play a c us tom map s uc c es s fully. With my hac kedtogether map framework in plac e, it was jus t a matter of s c reen s c raping the C P D 's web s ite, geoc oding eac h c rime, and dis playing the data. A fter G oogle releas ed its offic ial A P I at the end of J une 2 0 0 5 , I updated C hic agoc rime.org to make us e of it. 3.3.1. Adding Ward and ZIP Code Boundaries A s ide from dis playing a c us tom G oogle M ap with relevant c rime data on almos t every page, C hic agoc rime.org us es the G oogle M aps A P I in a c ouple of innovative ways . O ne way of navigating c rime data is by polic e dis tric t. Bec aus e s ome res idents of C hic ago may not know their as s igned dis tric ts , I c reated a "Find your beat and dis tric t" featurehttp://www.c hic agoc rime.org/dis tric ts /that helps people figure out whic h polic e beat and dis tric t they live in. I t's s imple to us e: jus t pan and zoom the map to c enter it on a loc ation, then c lic k "G ues s dis tric t." I t's s imple under the hood, too. When a us er c lic ks "G ues s dis tric t," a bit of J avaSc ript c alc ulates the c enter longitude and latitude of the c urrent map view and s ends that through a J avaSc ript XMLHttpRequest to a s erver- s ide s c ript. T he s erver c ode, written in P ython and D jango (http://www.djangoprojec t.c om), us es a s patial query agains t P os tG I S, a s et of s patial extens ions to P os tgreSQ L , to determine whic h dis tric t c ontains the given point. Finally, it pas s es the ans wer bac k to the s ite's J avaSc ript in your brows er. You c an find out more about P os tG I S at http://pos tgis .refrac tions .net/. O 'Reilly's Web Mapping I llus trated offers a good tutorial on P os tG I S, as well. Similarly, C hic agoc rime.org lets you navigate c rimes by c ity ward, and there's a "Find your ward" feature on the ward page: http://www.c hic agoc rime.org/wards /. For ward and ZI P C ode pages , c hic agoc rime.org us es the G oogle M aps polyline- drawing A P I to draw the border for the given ward or ZI P C ode on the map. I did this by obtaining the ward and ZI P C ode boundaries in E SRI Shapefile format from the C ity of C hic ago's G I S department at http://www.c ityofc hic ago.org/gis /. I loaded the s hapefiles into a P os tgreSQ L databas e and c onverted the data into longitude- latitude c oordinates us ing the c onvers ion func tions in P os tG I S. Finally, it was jus t a matter of feeding the points into the G oogle M aps polyline- drawing A P I , and voila: we have ward and ZI P C ode borders . 3.3.2. See Also Rendering arbitrary G I S vec tor data on G oogle M aps is an interes ting and s till evolving s ubjec t. "H ow Big I s T hat, E xac tly? " [Hack #28] involves rendering vec tor data from G I S s ourc es on top of G oogle M aps . Adrian Holovaty Hack 19. Map Local Weather Conditions Find out whether there's weather where you are. I t's a well- known fac t that everyone likes to talk about the weather, yet no one ever s eems to do anything about it. Serious ly, though, whenever two s trangers meet and make s mall talk, it's inevitable that the rec ent meteorologic al c onditions will make an appearanc e in the c onvers ation. T he s tate of the weather outs ide today, whatever it turns out to be, is s omething we all have in c ommonwe're all obliged to endure it or enjoy itat leas t, thos e of us that go out of doors . 3.4.1. The Situation Outside Is… N aturally, it didn't take long for s omeone to s et up a G oogle M aps s ite devoted to trac king the weatherand we don't jus t mean any old weather, we mean detailed weather data, inc luding temperature, wind s peed and direc tion, relative humidity, and daily rainfall. D ave Sc horr's G oogle Weather M aps s ite, at http://www.weatherbonk.c om/, c ollec ts meteorologic al data aggregated by Weather U nderground and Weatherbug from thous ands of pers onal weather s tations ac ros s the world, and then plots that information in a ric h G oogle M aps interfac e on the Web. Figure 3 - 5 s hows the default view of weatherbonk.com, c entered on San Franc is c o, C alifornia. I f, as c hanc e would mos t likely have it, you're not in San Franc is c o, you c an s tart by entering your loc ation in the s earc h box at the top of the page. Valid loc ation s tyles take the form city, state, or city, country. U .S. ZI P C odes als o work. I n addition, you c an overlay points from multiple loc ations by s eparating eac h query with a s emic olon (;). For example, entering 33010;33446 will give you points along the s outheas t c oas t of Florida. While a good number of international c ities c ome up with res ults , you may need to be c areful about what you type in here; for example, typing in "L ondon, U K" returns nothing, while "L ondon, E ngland" returns what you would expec t. A ls o, at the time of this writing, G oogle only has detailed s treet maps for the U .S., U .K., C anada, and J apan. I f you s ee broken image links in the bac kground of the map, G oogle has not yet c reated s treet maps for your area. I n this c as e, keep zooming out until the map appears , and/or c lic k the Satellite button on the map to s witc h to the s atellite view. A s you c an s ee from Figure 3 - 6 , the Weatherbonk.c om s ite us es dynamic ally generated marker ic ons to c onvey a great deal of information at onc e. E ac h one of the weather s tation markers plotted on the map is c olor- c oded ac c ording to the loc al temperature, ranging from blue (c oldes t) to red (hottes t). A ls o, the temperature reading is dis played on the markers thems elves , in either degrees Fahrenheit or C els ius , at your option. I f pres ent, a s pike extending from a marker points into the prevailing wind direc tioni.e., toward the wind, not away from itwhile the number of tic ks s hown on the s pike indic ates the obs erved wind s peed, ranging from no tic ks , repres enting a wind s peed of under 4 mph, up to four tic ks , indic ating winds of 1 6 mph or more. A dditionally, a marker may c ontain an ic on illus trating other c urrent c onditions , s uc h as s uns hine, overc as t, or rain. A key to thes e markers is s hown at the bottom right c orner of the page. C lic king on any of the markers opens an info window with the details for that weather s tation, as s hown in Figure 3 - 6 . I f the s tation is affiliated with Weather U nderground, temperature, wind s peed and direc tion, and relative humidity are s hown. Below thes e readings , you'll s ee a graph illus trating the 2 4 - hour his tory for both temperature and dew point. T he title at the top of the info window is linked to the homepage of the maintainer of that partic ular s tation. Figure 3-5. The default view, showing the current conditions in San Francisco T he dew point, in c as e you're wondering, is the temperature at whic h the water vapor in the air begins to c ondens e into liquid water. Relative humidity, whic h is what's s hown in the info windows , is c alc ulated from a c ombination of ambient temperature and dew point. Fros ty drinks on a hot day often lower the temperature of the air immediately around them to a level below the dew point, whic h is why a layer of c ondens ation forms on the outs ide of the glas s . By c ontras t, a Weatherbug- affiliated s tation s hows an info window with a daily rainfall figure, in plac e of the his toric al graph. Some Weatherbug s tations als o have webc ams , whic h are s hown in the info window, if pres ent. Weatherbug s tations aren't s hown on the map by defaultyou need to s elec t the Weatherbug c hec kbox at the top of the page and then c lic k the U pdate M ap button at the top right of the map. O ther, not nec es s arily weather related, webc ams c an be s hown on the map as well. Selec t the Webc ams c hec kbox at the top of the page, if it is n't already s elec ted, and then c lic k U pdate M ap. T hes e loc ations , whic h are often educ ational ins titutions , are identified on the map by trans parent markers . A s you'd expec t, c lic king on a webc am ic on opens an info window s howing the c urrent image from that loc ation. Figure 3-6. Weather station details are shown in an info window T he info windows s hown on the map c an often be quite large, what with all the weather information and webc am images they inc lude. O ne res ult of this is that the X button us ed to c los e the info window c an oc c as ionally wind up obs c ured by other things on the map. Fear notyou c an always c los e an open info window by c lic king on the as s oc iated marker a s ec ond time. 3.4.2. More Than Just the Weather T he Weatherbonk.c om s ite s upports s ome other interes ting features . O n the right s ide of the map, you c an s elec t various s ourc es of radar data, to depic t c loud c over on the map. A dditionally, under the G oogle E arth s ec tion of the page, you c an ac c es s different s ourc es of c loud radar imagery in KM L format, for us e with G oogle E arth. From the s tandpoint of G oogle M aps , however, the mos t interes ting additional features are the three map c ontrol buttons at the top right c orner of the map, immediately below the map type c ontrol. T hes e buttons are labeled Zoom Box, C lear P oints , and U pdate M ap. T he C lear P oints button wipes all the markers off the map, while the U pdate M ap button loads new data from the s erver, whic h c an be handy if you zoom or pan the map to view a different area. T he Zoom Box feature is partic ularly nifty and bears a bit of explanation. I f you hold down Shift- Z, and then left- c lic k and drag your mous e ac ros s the map, a red box appears and follows your mous e drag. Releas ing the left mous e button c aus es the map to zoom into the area within the red box, whic h c an be quite handy for drilling down to a partic ular loc al region. C lic king U pdate M ap after you've us ed the zoom box feature c an s ometimes reveal weather s tations that weren't s hown on the larger area map, as the s ite tries to avoid c rowding the map with too many points at any given zoom level. A ls o, you don't ac tually need to c lic k the Zoom Box button before us ing this featurethe button its elf does n't do anything us eful, beyond dis playing helpful ins truc tions in an alert window. 3.4.3. Microclimates and Distributed Weather Reporting L ike s o many other things , the I nternet has made it pos s ible for weather reporting to be dis tributed among many people on a ground- up bas is , rather than c entralized in a top- down fas hion, as it traditionally has been. O ne thing that this dec entralization makes pos s ible is witnes s ing for yours elf the s triking variety of weather c onditions in an area with lots of mic roc limates , like the San Franc is c o Bay A rea. Try it mid- to late- afternoon P ac ific T ime (G M T - 7 during the D aylight Savings T ime, G M T - 8 otherwis e), when the fog us ually s tarts to c reep in off the oc ean, thus c ooling s ome areas , while other plac es are s till c lear and warm. To augment this view, try adding the Bay A rea fog overlay from the O verlays drop- down on the right s ide of the page. T he differenc es ac ros s an area even as s mall as San Franc is c o c an s ometimes really be quite s triking. 3.4.4. See Also T he Weather U nderground s ite at http://wunderground.c om/ has RSS feeds for weather reports in various metropolitan areas . http://api.weatherbug.c om/ is the home for Weatherbug's data ac c es s A P I . M E TA R is a very ters e text format us ed around the world for reporting weather data. You c an find out more about M E TA R, and get live M E TA R feeds from the U .S. N ational Weather Servic e at http://weather.noaa.gov/weather/metar.s html. http://anti- mega.c om/weather/ offers a s eries of (nongeoreferenc ed) RSSbas ed weather feeds , us ing data s c raped from worldweather.org. written with as s is tance from Dave Schorr Hack 20. Track Official Storm Reporting Follow the path of the latest hurricane on a Google Map. G oogle M ap hac king s tarted for me in early M arc h 2 0 0 5 , when I bec ame aware of s ome of the great hac ks that were already being c reated. M y interes t was partic ularly piqued after s eeing the beta releas e of A drian H olovaty's C hic agoc rime.org web s ite, as des c ribed in "E xamine P atterns of C riminal A c tivity" [Hack #18]. I immediately realized the myriad other applic ations for this new mapping tec hnology. To be more prec is e, I determined that it would be benefic ial to develop a s tormreporting mapping s ite, whic h you c an vis it today at http://www.s tormreportmap.c om/, as s hown in Figure 3 - 7 . Figure 3-7. The weather on Google Maps You c an c lic k on a marker to s ee more details . For example, Figure 3 - 8 s hows a report of hail in Sioux, N ebras ka. A nother interes ting feature is the hurric ane trac king maps . A s s hown in Figure 3 - 9 you c an s ee the trac ks of tropic al s torms . C lic king on the marker ic ons gives you more information about the s torm at that point. I n Figure 3 - 1 0 , we s ee that I rene has been bounc ing between a tropic al s torm and a tropic al depres s ion. T he data s ourc e for the web s ite is the N ational O c eanic & A tmos pheric A dminis tration's (N O A A ) N ational Weather Servic e (N WS) Storm P redic tion C enter (SP C ), whic h c an be found online at http://s pc .noaa.gov/. O ne of the top produc ts that the SP C maintains is their Storm Report trac ker at http://s pc .noaa.gov/c limo/. T his produc t takes reports from trained weather s potters , emergenc y and firs t res ponders , and loc al res idents , and then maps them to an unattrac tive, s tatic page. M oreover, the reports als o don't give muc h in the way of c omprehens ible loc ations , as ide from latitude/longitude c oordinates , and the c ounty and s tate where the s torm was reported. A dditionally, s inc e eac h report is s ubmitted into the databas e as a s eparate event, there are times when s everal tornado reports rec eived are ac tually all from the s ame tornado. D ue to thes e s hortc omings in the original produc t, and bec aus e of its general popularity, I felt that my projec t might enhanc e the produc t's bas ic func tionality. Figure 3-8. Hail in Nebraska Figure 3-9. Hurricane-tracking maps Figure 3-10. Good night, Irene! 3.5.1. Getting the Data T he SP C began c ollec ting s torm report data in mid- 1 9 9 9 . U nfortunately, they did not begin putting the data into a webfriendly format until early 2 0 0 4 . T herefore, without pars ing through three different vers ions of web s ites , the projec t will only s how s torm report data from early 2 0 0 4 on. T he data is obtained through a Comma Separated Values (C SV ) file that is pos ted along with eac h update. T his very friendly format allows me to pars e through the file, c onvert it into an array, format it to my liking, and pus h the c ontents out as an XM L file. I f you are getting your data from a third- party s ite through an XM L or RSS feed, it's important to realize that bandwidth often c os ts money. Before beginning this projec t, I realized that obtaining the data I want and in the timeframe I wanted it might pres ent a problem for the remote SP C web s ite. O ur as s umptions us ing information obtained from the s ite were the following: T he c urrent day's map is updated every 1 5 minutes . Yes terday's map is updated in 3 - hour inc rements . O nc e a map is more than 2 days old, it is no longer updated. I c ouldn't develop a projec t that would s imply leec h off the SP C web s ite's data for every vis it to my s iteit's dis res pec tful, lazy, and, mos t of all s low. I determined that the bes t model would be to us e a bac k- end databas e to s tore all the reques ted data and load the mos t c urrent data us ing a s eries of times tamps . H ere's how the s ite handles the data refres h when a us er vis its the s ite: 1. T he s ite loads the report data for the reques t. 2. A times tamp indic ating when the data was las t updated for eac h day is s tored in the databas e. 3. Sinc e eac h page load requires that the databas e load the report data, the s ite als o c hec ks to s ee when the data was las t updated. 4. T he s ite updates today's data, if more than 6 0 minutes have elaps ed between the s tored times tamp and the c urrent times tamp. 5. T he s ite updates yes terday's data, if more than 2 4 hours have elaps ed between the s tored times tamp and the c urrent times tamp. 6. For his toric al data, no times tamp c hec king is done, bec aus e the mos t c urrent data is already loaded, bas ed on previous as s umptions . 7. T he page dis plays the data to the us er. T his model dras tic ally reduc es the traffic and bandwidth s ent to the remote SP C web s ite, and I would rec ommend us ing it for any s ite that us es regularly updated third- party data from remote web s ites . 3.5.2. The Hack When the G oogle M aps A P I was finally releas ed, I dec ided to c hec k out its func tionality firs thand. Sinc e the original s ite was weather related and hurric ane s eas on was jus t beginning to get in the s wing of things , a hurric ane trac ker us ing the new A P I was in order. T he H urric ane Trac k M ap us es the G oogle M aps A P I to develop a G oogle M ap without jumping through all the hoops that the preA P I XSLT methods required. T he c atc h is that there is quite a bit more J avaSc ript development that you will need to inc lude. G oogle has gone to great lengths to try and give enough doc umentation for a novic e developer to get s tarted, but even s ome veteran programmers have trouble getting it to work c orrec tly. T his c ode s nippet s hows jus t how you c an us e the GXmlHttp c las s from the G oogle M aps A P I to load XM L data from a file on your s erver. A s us ual, you c annot retrieve remote files from other s ites us ing A J A X; only files within your domain or hos t c an be loaded, whic h is another good reas on to c ac he the data in your own databas e firs t. var request = GXmlHttp.create(); request.open("GET", "data.xml", true); request.onreadystatechange = function() { if (request.readyState == 4) { markers = []; points = []; infoHtmls = []; categorypoly = []; var xmlDoc = request.responseXML; var markers = xmlDoc.documentElement.getElementsByTagN // Loop through the XML document and grab the data contain // with the tags. Store that data into an array. for (var i = 0; i < markers.length; i++) { points[i] = new GPoint(parseFloat(markers[i].getAt parseFloat(markers[i].getAttribute("la name = markers[i].getAttribute("name"); type = markers[i].getAttribute("type"); advisory = markers[i].getAttribute("advisory"); timestamp = markers[i].getAttribute("timestamp"); windspeed = markers[i].getAttribute("windspeed"); pressure = markers[i].getAttribute("pressure"); moving = markers[i].getAttribute("moving"); point = points[i]; // Append a hurricane category rating on it based on the // Wind Speed. if (type == "Tropical Depression") {category = "TD else if (type == "Tropical Storm") {category = "TS else { // Its a hurricane if (windspeed >= 74 && windspeed <= 95) {categ else if (windspeed >= 96 && windspeed <= 110) else if (windspeed >= 111 && windspeed <= 130) else if (windspeed >= 131 && windspeed <= 155) else {category = "5";} } categorypoly[i] = category; // Call to the createMarker function to create the marker var marker = createMarker(point, name, type, advis windspeed, category, pressure, moving); // Overlay the markers on the map map.addOverlay(marker); } T he createMarker( ) func tion is c alled in order to build the info window for that partic ular marker. A ls o, this func tion as s igns a c us tom ic on to the marker, depending on whether the s torm is c las s ified as a tropic al s torm, a tropic al depres s ion, or a c ategory 1 through 5 hurric ane. N ext, our c ode adds a polyline to go along with the markers . T his is valuable, bec aus e hurric ane trac ks are very unpredic table, and often make loops and turns before they make landfall or get pus hed bac k out to s ea. var pointset = []; // Loop through the array of points created above. Each po // upon the category it received will receive a line segme // well as the width. for (q=0; q < points.length; q++) { pointset.push(points[q]); if (categorypoly[q] == "TD") {color = "#660099";si else if (categorypoly[q] == "TS") {color = "#33339 else if (categorypoly[q] == "1") {color = "#33FFFF else if (categorypoly[q] == "2") {color = "#33FF66 else if (categorypoly[q] == "3") {color = "#FFFF66 else if (categorypoly[q] == "4") {color = "#FF9933 else {color = "#FF3333";size = 17;} // Add point to the GPolyline so the map can draw it. map.addOverlay(new GPolyline(pointset, color, size pointset = []; pointset.push(points[q]); } 3.5.3. See Also See http://c ode.s tormreportmap.c om/ for more s ourc e c ode and referenc es . A ll s ourc e c ode is releas ed under the G N U G eneral P ublic L ic ens e. You may us e and publis h as you wis h without any c opyright notic e being retained or trans ferred. I f you wis h to c ontac t me, I c an be reac hed at webmas ter@ s tormreportmap.c om. Anthony Petitoa Hack 21. Track the International Space Station Track the International Space Station and the Space Shuttle in near-real time. You c an trac k anything on G oogle M aps all you need is a s ourc e of data. Tom M angan c reated his own s ite to trac k the Spac e Shuttle and I nternational Spac e Station (I SS) at http://gmaps .tommangan.us /s pac ec raft_trac king.html. T he s ite trac ks the loc ation of the I SS and, when it is in orbit, the Spac e Shuttle, as s hown in Figure 3 - 1 1 . T he exc itement c an c ome from being able to s pot the Shuttle and I SS from the ground, and in watc hing on the map as they rendevous . When you firs t load the page you s hould get one or two markers , depending on whether the Shuttle is in orbit. I f you leave the page open the markers leave a trail of where the I SS and Shuttle have been. O ver the c ours e of about 9 0 minutes (ac tually, 9 1 .5 5 minutes for the I SS, ac c ording to the Wikipedia page at http://en.wikipedia.org/wiki/I nternational_Spac e_Station), the c harac teris tic s ine wave s hape of low E arth orbits appears . N o, objec ts in s pac e don't bounc e around like tennis balls ; this repres ents the effec ts of repres enting a three dimens ional orbit onto a flat map. T he firs t rule of c artography is that you always dis tort s omething! Figure 3-11. Shuttle and ISS tracking, with an amusing note G oogle's A dSens e ads are often the funnies t part of a page. H ere we have a link to "N A SA Spac e Shuttle for s ale. C hec k out the deals now! " I don't think I want to buy an affordable s pac ec raft on eBay! M aybe in a few years . 3.6.1. How It Works M os t of the work happens in the J avaSc ript in the s ite's autoUpdate( ) func tion. autoUpdate( ) is c alled as s oon as the page loads . <body style="background-color: #000; text-align: center;" onload="autoUpdate();"> T he autoUpdate func tion us es the GXmlHttp c las s from G oogle M aps to fetc h the is s .j s file from the s erver. You c an take a look at the file at http://gmaps .tommangan.us /is s .js . -48.6;-11.7;369.8;-51.6;-31.9;291.1 T his s hows the latitude and longitude of the I SS firs t, and then that of the s huttle. T he c ode reads the file, then s plits the res ults into the array coords with the split method. T he res t of the method is hous ekeeping to do a s anity c hec k on the returned res ult, then adds the points to the c urrent arrays of res ults for the Shuttle and I SS. function autoUpdate() { var request = GXmlHttp.create(); request.open("GET", "iss.js", true); request.onreadystatechange = function() { if (request.readyState == 4) { var response = request.responseText; coords = response.split(';'); var valid = (coords[0]&&coords[1]&&coords[3]&&coor &&coords[0]>-90&&coords[0]<90&&coords[1]>-180 &&coords[1]<180&&coords[3]>-90&&coords[3]<90 &&coords[4]>-180&&coords[4]<180); if (valid) { map.clearOverlays(); var sPoint = new GPoint (coords[4],coords[3]); var sMarker = new GMarker (sPoint,pinWhite); if (coords[4] < -174) { sTrack=[]; } sTrack.push (sPoint); map.addOverlay(sMarker); var issPoint = new GPoint (coords[1],coords[0]); var issMarker = new GMarker (issPoint,pinRed); if (coords[1] < -174) { issTrack=[]; } issTrack.push (issPoint); map.addOverlay(issMarker); refreshCoords(); drawTrack(); } } } request.send(null); window.setTimeout ('autoUpdate()', 60000); } T he final tric k is the las t line of autoUpdate(): window.setTimeout ('autoUpdate()', 60000); T his tells the window to timeout after 6 0 ,0 0 0 millis ec onds , i.e., one minute. When it times out it c alls autoUpdate() and s tarts the c yc le again. T here is a s c ript running on the s erver that queries the N A SA s ite for the c urrent pos ition of the Shuttle and I SS, and then writes that out the is s .j s file. You c an us e thes e s ame tec hniques to do dynamic updating of your own maps . I f you are the s ort of pers on who goes in for s pac e s huttle trac king, you'll like a c ouple of Tom's other projec ts at http://gmaps .tommangan.us /. H e has a map that s hows the c urrent known loc ations of all of the SR 7 1 Blac kbirds and aerial photos of A rea 5 1 . Both projec ts us e his T P hoto extens ion to the G oogle M aps A P I , whic h lets you embed your own images within G oogle M aps [Hack #55]. 3.6.2. See Also N A SA 's Satellite Trac king P age, whic h inc ludes applic ations to trac k many different s atellites , although not with G oogle M aps : http://s c ienc e.nas a.gov/realtime/. Hack 22. Witness the Effects of a Nuclear Explosion Sometimes a map can reveal truths we'd rather not know. For over 5 0 years , the human rac e has lived under the s hadow of the threat of nuc lear war. E ric A . M eyer's H Y D E Sim (H igh-Y ield D etonation E ffec ts Simulator) web s ite, whic h us es G oogle M aps in a s omewhat novel way to illus trate the blas t effec ts of a nuc lear detonation. You c an s ee the res ults for yours elf at http://meyerweb.c om/eric /tools /gmap/hydes im.html. Figure 3 1 2 s hows the default view, whic h illus trates the effec t of a 1 5 0 kiloton explos ion at ground level in downtown M anhattan. Figure 3-12. Depiction of the blast wave of a 150-kT nuclear explosion in downtown Manhattan T he blas t effec t of a nuc lear explos ion is us ually rec koned in terms of overpres s ure, whic h is a meas ure of how muc h forc e is exerted on people and buildings at a given dis tanc e away from ground zero. O n the map, this is s hown as four c onc entric rings of dec reas ing intens ity, whic h s pread outward from the hypothetic al explos ion s ite, repres enting overpres s ures of 1 5 ps i, 5 ps i, 2 ps i, and 1 ps i, res pec tively. T he dis play on the left s hows the blas t radius for .2 5 ps i overpres s ure as well, although this ring is not s hown on the map. What exac tly do thes e figures mean, though? T he des c riptions s hown in Table 3 - 1 are taken from s ec tion 5 of the N uc lear Weapons FA Q at http://nuc learweaponarc hive.org/N wfaq/N faq5 .html. Table 3-1. Destructive effects of atmospheric overpressure Overpressure Structural ef f ects Human injuries 1 ps i Window glas s s hatters . L ight injuries from fragments oc c ur. 3 ps i Res idential s truc tures c ollaps e. Serious injuries are c ommon, fatalities may oc c ur. 5 ps i M os t buildings c ollaps e. I njuries are univers al, fatalities are wides pread. 1 0 ps i Reinforc ed c onc rete buildings are s everely damaged or demolis hed. M os t people are killed. 2 0 ps i H eavily built c onc rete buildings are s everely damaged or demolis hed. Fatalities approac h 100%. A lthough the res ults are s implified, they s ure don't look prettyat that loc ation and yield, s uc h a nuc lear explos ion would literally wrec k all of downtown M anhattan. What's wors e, this map does n't take the effec ts of heat or radiation into ac c ount. (O n the other hand, this map does n't take the attenuating effec ts of terrain and weather into ac c ount, either.) A lthough the des truc tive effec ts of nuc lear weapons are hardly news to anyone, it is s till kind of morbidly interes ting to be able to s ee them on a map. A dditionally, the s ite allows you to s ee the effec ts on c ertain other U .S. c ities lis ted in the drop- down box at the upper right, and, if you happen to know the latitude and longitude of a plac e that partic ularly interes ts you, you c an enter them into the c oordinates box below that. I f you live in the States and don't happen to know the c oordinates of, s ay, your hometown, you c an look up a s pec ific addres s on the G eoc oder.U S web s ite at http://geoc oder.us /. Finally, you c an adjus t the yield of the hypothetic al explos ion, whic h is meas ured in kilotons of T N T. By experimenting, we c an s ee that a 1 megaton nuc lear explos ion over the Brooklyn Bridge would des troy mos t of M anhattan, Q ueens , and Brooklyn. Fortunately, thes e high- yield nukes have been phas ed out of mos t of the world's military s toc kpiles . O n the other hand, we c an s ee that even a relatively "s mall" detonation on the order of 5 kilotons c ould wreak utter mayhem in s ignific ant parts of the c ity. 3.7.1. The Code From a tec hnic al s tandpoint, what makes this hac k interes ting is this bit of J avaSc ript c ode, whic h you c an find for yours elf by viewing the s ourc e of the aforementioned web page: var base = new GIcon(); base.image = "radii.png"; base.shadow = 't.png'; base.shadowSize = new GSize(1, 1); var GZ = new GIcon(base); GZ.image = "crosshair.png"; GZ.iconSize = new GSize(13, 13); GZ.iconAnchor = new GPoint(6, 6); GZ.infoWindowAnchor = new GPoint(6, 6); var p15 = new GIcon(base); p15.iconSize = new GSize(det.radius.p15*2/mpp, det.radius. p15.iconAnchor = new GPoint(det.radius.p15/mpp, det.radius p15.infoWindowAnchor = new GPoint(det.radius.p15/mpp, det.radius.p15/mpp); var p5 = new GIcon(base); p5.iconSize = new GSize(det.radius.p5*2/mpp, det.radius.p5 p5.iconAnchor = new GPoint(det.radius.p5/mpp, det.radius.p p5.infoWindowAnchor = new GPoint(det.radius.p5/mpp, det.ra T his c ode, whic h you'll find in the buildOverlays( ) func tion, us es the s tandard G I c on marker objec t from the G oogle M aps A P I to render the blas t radius rings us ing the s ame s emi- trans parent radii.png image. E ac h one is s ized s eparately, ac c ording to the blas t radii c alc ulated from the detonation yield in the Detonation( ) c ons truc tor (not s hown here), and the mpp variable, whic h s tores the map s c ale at the c urrent zoom level. A dditionally, a c ros s hair ic on is c reated to repres ent ground zero its elf. T he ups hot is that when the map is loaded, or whenever the detonation loc ation is moved, the individual blas t radius markers are s tac ked on top of one another at the s ame loc ation on the map. T he s emi- trans parent c irc les then give the vis ual impres s ion of blas t intens ity dec reas ing, as it moves away from ground zero. T he res ult, whic h perfec tly c onveys the des ired information, is a very c lever us e of the G oogle M aps marker ic ons , whic h are us ually us ed to repres ent groc ery s tores or yard s ales ! T he s ame tec hnique c ould be us ed to repres ent any kind of data via G oogle M aps that involves c onc entric radii of dec reas ing intens ity. O ne immediately thinks of volc anic explos ions or earthquake damage as c andidates for this kind of interfac e, but there are probably les s des truc tive topic s that c ould be illus trated the s ame way. C ertainly, the pros pec t of nuc lear war, or even of an is olated nuc lear explos ion in a populated area, is a terrifying one. So far, humanity has managed to s how c ons iderable res traint in its applic ation of nuc lear weapons , but an es timated 2 0 ,0 0 0 nuc lear warheads s till exis t in the world's military ars enals . Ridding ours elves of this menac e remains one of the mos t important outs tanding is s ues in international politic s . H opefully, ac c es s to the kind of information offered by the H Y D E Sim s ite will bring home to people how tragic the pos s ibilities are, and jus t how imperative it is that the menac e never bec omes a reality. 3.7.2. See Also T he N uc lear Weapons FA Q (http://nuc learweaponarc hive.org/N wfaq/N faq0 .html) ans wers a lot of c ommon ques tions about nuc lear weapons . T he A tomic A rc hive's N ew York example (http://www.atomic arc hive.c om/E xample/E xample1 .s html illus trates a s ituation muc h like the one s hown in Figure 3 - 1 2 , only in muc h more detail. Wikipedia's L is t of N uc lear A c c idents at http://en.wikipedia.org/wiki/L is t_of_nuc lear_ac c idents makes for an interes ting read and illus trates jus t how c los e we've c ome over the years to s erious ac c idental nuc lear explos ions . Hack 23. Find a Place to Live Why slog through endless listings of apartments that all look the same, when you can pick and choose based on where you actually want to live? Finding a plac e to live, partic ularly in large c ities , c an be a huge pain. L oc ating a plac e at a pric e you c an afford is enough of a c hallenge, but, even when you c an loc ate s uc h plac es , they're often not s ituated where you ac tually want to live. Real es tate and rental lis ting s ites like C raigs lis t.org go a long way towards eas ing this pain by offering s earc hes agains t lis tings bas ed on keywords and pric e brac kets , but often even the s earc h res ults thems elves are s till daunting. Where the hec k are all thes e plac es ? H ow c los e are eac h of thes e apartments to the groc ery s tore? To public trans it? To my friends ' hous es ? T he lis tings often inc lude neighborhood names , or even s treet addres s es or nearby inters ec tions , but if you're not partic ularly familiar with the area, thes e names might not mean anything to you. P aul Rademac her's H ous ingM aps s ite offers an inventive s tart on a s olution to this problem: take one part C raigs lis t.org real es tate lis tings , one part G oogle M aps A P I , and s tir! 3.8.1. What to Do? T he front page of H ous ingM aps , whic h you c an find at http://hous ingmaps .c om/, s hows a G oogle M aps view of the U nited States and C anada, as s een in Figure 3 - 1 3 . T he green ic ons on the map mark many of the major urban areas s erved by C raigs lis t, and c lic king one opens a c all- out, from whic h you c an s elec t real es tate for s ale, rentals , rooms for rent, and s ublets or temporary hous ing for that c ity. I f you find this view a bit c onfus ingor find the ic ons hard to c lic k, as in the northeas tern U nited States , where the ic ons are bunc hed a bit c los e togetherthen you c an s elec t the metropolitan area of your c hoic e from the drop- down box at the top left, and then us e the links above to narrow your s earc h. (A lternatively, you c an rec enter with a mous e drag or doublec lic k, and then zoom in! T his is G oogle M aps , after all.) Finally, another drop- down box at the top allows you to indic ate pric e ranges of properties to s how on the map. Figure 3-13. Why live anywhere when you could live, er, anywhere? A fter s elec ting a type of lis ting for a given c ity, you're taken to a view of the available properties of that type in that c ity. Sinc e I 've been looking for a c heap s hort- term s ublet in north Brooklyn, I s elec t s ublets in N ew York C ity, and then us e the zoom and pan c ontrols to foc us in on that area. Yellow ic ons identify lis tings with photos , while red ic ons identify thos e without. I s tarted by c lic king one of the yellow ic ons on the map, as s hown in Figure 3 - 1 4 .A G oogle M aps info window pops up, s howing the details of the property, inc luding c ontac t details and any photos . Figure 3-14. A search for rentals in north Brooklyn using HousingMaps A lis t of identifiable properties for that c ity and type is s hown on the right s ide, s orted by pric e. C lic king on one of the ic ons rec enters the map on that property and opens its c all- out, while c lic king on the adjac ent link takes you direc tly to that entry in C raigs lis t. A dditionally, you c an apply the s ame filters to your s earc h that C raigs lis t offers , s uc h as keywords , pets permitted, and the pres enc e of photos in a lis ting. Finally, there's a "permalink" option that allows you to bookmark a partic ular s earc h for future us e onc e you've zeroed in on the part of town and the s earc h filters you're interes ted in. D oes this beat paging through mind- numbing lis ts of rentals that all look the s ame or what? 3.8.2. How It Works H ow does this mirac le of modern tec hnology func tion? P art of the ans wer lies in the RSS feeds offered by C raigs lis t for eac h c ategory they provide. T he Brooklyn s ublets , for example, are lis ted at http://newyork.c raigs lis t.org/brk/s ub/. A t the bottom of the page, there's a link labelled RSS, whic h points to http://newyork.c raigs lis t.org/brk/s ub/index.rs s . T his file c ontains an XM L doc ument that provides a mac hine- readable vers ion of the 1 5 mos t rec ent lis tings for that c ategory. H ere's a s nippet: <item rdf:about="http://newyork.craigslist.org/brk/sub/872 <title>***Bedroom Avail in Apt with Garden- Aug Sublet*** $650 3bd</title> <link>http://newyork.craigslist.org/brk/sub/87294481.html< <dc:rights>Copyright 2005, craigslist.org</dc:rights> <dc:language>en-us</dc:language> <dc:date>2005-07-27T14:52:39-04:00</dc:date> <dc:type>text</dc:type> </item> T he main thing to note, of c ours e, is the U RL in the <link> element. T hat H T M L page is the rental lis ting its elf and, buried within it, are a few c hoic e bits of H T M L c omments that C raigs lis t puts in every page: <!-- START CLTAGS --> <!-- DO NOT EDIT these unless you're really feeling brave posting messed up. You have been warned. --> <!-- CLTAG xstreet0=Boerum Street --><!-- CLTAG xstreet1=B <!-- CLTAG city=Brooklyn --><!-- CLTAG state=NY --> T hes e c omment tags , of c ours e, c ontain enough information to plot the approximate loc ation of the rental on a map! We'll s how how to do this for U .S. s treet addres s es with G eoc oder.us in "Find the L atitude and L ongitude of a Street A ddres s " [Hack #62]. T he prac tic al ups hot is that, on the s erver s ide, the H ous ingM aps web s ite periodic ally s piders the C raigs lis t RSS feeds , finds new lis tings , and s c rapes the loc ation data out of eac h one. (T he downs ide is that if there is n't any loc ation information in the lis ting, it's awfully diffic ult to s how it on the map! ) Finally, the s ite produc es its own data file c ontaining the lis ting information, links to photos , and, of c ours e, the loc ation data, whic h is then fed into the G oogle M aps interfac e in your web brows er to produc e the lovely maps you s ee before you, us ing XMLHttpRequest. O f c ours e, now that G oogle has releas ed a proper A P I for G oogle M aps , there are eas y ways to do this yours elf, as we'll als o s ee later on in the book. 3.8.3. See Also M onkey H omes (N ew York, N Y ): http://monkeyhomes .c om/map/maps .php C olorado Future (D enver, C O ): http://www.c oloradofuture.c om A partmentRatings .c om (nationwide U .S.): http://www.apartmentratings .c om Hack 24. Search for Events by Location Events listed in the EVDB event database can easily be plotted on a Google Map. U s ing a generic s earc h engine is n't a good way to find out about events s uc h as mus ic al performanc es or garage s ales . You c an't s pec ify that only event des c riptions are wanted, and even if you c ould, the res ults aren't dis played in a way that organizes them us efully in time and s pac e. Wouldn't you like to be able to type keywords ("U 2 ", "pug meetup", etc .) into a s pec ialized event s ervic e, and get bac k not only a lis t of textual des c riptions , but als o a map s howing event loc ations and a c alendar highlighting event dates ? Well, that's what E V M apper does . You c an try E V M apper for yours elf at http://mapbureau.c om/evmapper/. Figure 3 - 1 5 is a s c reens hot of the res ults of the "pug meetup" s earc h. Figure 3-15. Pug meetup locations You c an c lic k on a map dot, or an event lis ting, or a highlighted c alendar date, and details about the event at that plac e or time will be dis played. I f there is more than one, a lis t is dis played ins tead. Whenever an event is s elec ted, and however the s elec tion took plac e, its loc ation will be marked on the map by the big balloon and its date will be marked by a little red s quare on the c alendar. You c an als o c lic k your way through the events in time. 3.9.1. How It Works E V M apper is a mas hup of two s ervic es : E V D B and G oogle M aps . E V D B (http://evdb.c om) is the E vents and Venues D atabas e, a free s ite that allows anyone to s ubmit or s earc h for events . A n E V D B s earc h dis plays a lis t of events ; events c an als o be organized into pers onal c alendars . H owever, maps are not c urrently part of the experienc e at the E V D B s ite. E V D B provides a RE ST ful A P I to the event databas e (http://api.evdb.c om). When a us er enters a query into E V M apper, an /events/search c all is made to the A P I ; for example: http://api.evdb.com/rest/events/search?app_key=…&keywords= T he XM L returned by E V D B c ontains des c riptions of the matc hing events . T he des c riptions s pec ify plac e by name (e.g., c ity, s tate, and s ometimes ZI P C ode or s treet addres s ), not latitude/longitude, s o E V M apper needs to do the geoc oding. E V M apper implements the s imples t pos s ible geoc oding method, whic h is adequate to demons trate the idea of event mapping: it looks up c ity/s tate in a G N I S databas e c overing the U nited States only. T he G eographic N ames I nformation Sys tem is the offic ial repos itory of plac e names in the U nited States . You c an query the G N I S at http://geonames .us gs .gov/. A s of this writing, E V D B has rec ently begun to provide lat/long c oordinates with s ome event des c riptions , and E V M apper will s oon exploit this development with dis patc h. E V M apper us es RD F, rather than E V D B's s pec ialized XM L , for its internal data. RD F makes E V M apper's repres entation and proc es s ing of events fully extens ible, s inc e RD F is built from an open- ended s eries of voc abularies , eac h for its own applic ation domain. RD F datas ets freely mingle voc abularies for as many domains as are relevant to the applic ation at hand. I n future, E V M apper may aggregate events from a variety of s ourc es , not jus t E V D B. N ew bits of RD F voc abulary, as s erting things like tonnage of s hips for s hipwrec ks or Ric hter Sc ale values for earthquakes , will be added as needed, with no need to dis turb the underlying implementation. O f c ours e, trans lators from other formats may be required, as was the c as e for E V D B. E V M apper is implemented in Fabl (http://fabl.net), a programming language for whic h RD F is the native data repres entation. 3.9.2. See Also T he World Wide Web C ons ortium's RD F P rimer at http://www.w3 .org/T R/rdf- primer/. Chris Goad Hack 25. Track Your UPS Packages With Google Maps and a simple Greasemonkey user script, you can watch your UPS packages travel across the country. A nyone who's rec eived a pac kage delivered by U P S, or any other large s hipping c ompany, probably has had the experienc e of wondering where the hec k the pac kage is right now, and when exac tly it's going to arrive. By entering the pac kage's trac king number into a form on the U P S web s ite, you c an get bac k a lis t of the c ities whic h the pac kage has traveled through to date. O f c ours e, this is enough information to allow us to vis ualize the pac kage's progres s on a map! 3.10.1. The Hack A s us ual, the tric k of mas hing up G oogle M aps with information from another s ite, s uc h as that from the U P S trac king form, involves a bit of c ontortion, to get around s ec urity res tric tions in the brows er. O ne s olution to this problem (at leas t for M ozilla Firefox us ers ) is to us e a G reas emonkey us er s c ript to modify the c ontents of a web page to inc lude a link to a map of the things on that page. T he G reas emonkey approac h [Hack #27] is exac tly the one taken by M atthew King, when he dec ided he wanted to vis ualize the path travers ed by his new las er printer, on its way from the warehous e to his hometown. Firs t, you'll need to be running M ozilla Firefox. You'll als o want to ins tall the lates t vers ion of the G reas emonkey extens ion from http://greas emonkey.mozdev.org/, if you haven't done this already; s ee "A dd G oogle M aps to A ny Web Site" [Hack #27] for more information on how this works . To ins tall the U P S trac king us er s c ript, vis it http://www.thrall.net/~mking/maps /ups trac k.us er.js in Firefox, and then s elec t Tools I ns tall U s er Sc ript from the menu bar. A c onfirmation window will pop up, in whic h you c an s imply c lic k O K. N ow you're ready to trac k your U P S pac kages ! V is it the U P S pac kage trac king form at http://www.ups .c om/c ontent/us /en/index.js x, enter a trac king number, c lic k the c hec kbox to ac c ept the terms and c onditions of us e, and then c lic k the button marked Trac k. A s ummary page will load, with a "V iew pac kage progres s " link. C lic k this link as well. You s hould get a res ults page that looks s omething like Figure 3 - 1 6 . T his partic ular example s hows the c ours e of a box of O 'Reilly's Mapping Hacks s ent from the c ompany's warehous e in Tennes s ee to our old hous e in San Franc is c o. So far this looks jus t like the regular U P S pac kage details page, with a lis t of c ities , dates , and s tatus mes s ages . H owever, if you look c los ely, you'll s ee that the G reas emonkey s c ript you ins talled earlier has added a s pec ial link to this page that reads s imply "M ap P rogres s ." G o on, c lic k it! A new window s hould open, s howing a map of your pac kage's progres s ac ros s the c ountry, as s hown in Figure 3 - 1 7 . Figure 3-16. The UPS package tracking details page, augmented by Greasemonkey Figure 3-17. The Google Maps representation of a package's travels I f you don't have a pac kage of your own to trac k, you c an always try out M att King's example page at http://www.thrall.net/~mking/maps /ups _s ample.html. 3.10.2. The Code T he G reas emonkey c ode for this hac k is ac tually really s imple and offers a good example of how to us e G reas emonkey to pic k elements from an exis ting page on the Web and us e them to ins ert new elements into the s ame page. T his firs t c hunk of c ode from ups track.us er.j s extrac ts all the loc ations from the U P S detailed res ults page: var lastLoc = null; var loc = null; var locations = new Array; var allDivs, thisDiv; allDivs = document.evaluate("//div[@class='modulepad']", documen XPathResult.UNORDERED_NODE_SNAPSHOT_ for (var i = 0; i < allDivs.snapshotLength; i++) { thisDiv = allDivs.snapshotItem(i); var html = thisDiv.innerHTML; html = html.split(/[\t\n\r]+/).join(' '); html = html.replace("<br> ", ''); if (html.indexOf(', US') == -1) continue; loc = html; if (loc == lastLoc) continue; locations[locations.length] = loc; lastLoc = loc; } T he c ode s tarts by c reating an empty array of loc ations and then pas s es an XP ath to Firefox's document.evaluate( ) method to find all of the H T M L div elements of the c las s modulepad, whic h apparently c ontain the loc ation s trings . T he s c ript then iterates over eac h div node, extrac ting the loc ation s tring, c leaning it up a bit, and then pus hing it on to the array of loc ations , c hec king eac h one to make s ure that it's not redundant with the loc ations already s tored. T he next bit of c ode in the s c ript handles the ins ertion of the M ap P rogres s link into the res ults page: if (locations.length > 1) { locations.reverse(); var locStr = locations.join(" to "); allDivs = document.evaluate("//span[@class='brownbold']", do XPathResult.UNORDERED_NODE_SNAPS for (var i = 0; i < allDivs.snapshotLength; i++) { thisDiv = allDivs.snapshotItem(i); var html = thisDiv.innerHTML; var estr = escape(locStr).replace(/\ //g, '%2F'); html += '&nbsp; &nbsp; &nbsp;' + '<a href="http://www.thrall.net/~mking/maps + 'v=0.4&trip=' + estr + '" target="_blank">Map Progress</a>'; thisDiv.innerHTML = html; } } I n this s ec tion, the c ode c hec ks to s ee if any loc ations were found, and, if s o, joins them with the s tring " to", yielding s omething like NASHVILLE TN to KANSAS CITY MO to SAN FRANCISCO CA in the locStr variable. T he s c ript then looks for div elements of the c las s brownbold, whic h pres umably holds the "P ac kage P rogres s :" text dis played on the page above the lis t of loc ations , and ins erts a link to M att King's http://www.thrall.net/~mking/maps /ups trac k.c gi s c ript into the div's innerHTML, pas s ing a U RL- es c aped rendition of locStr as an H T T P G E T parameter. T his res ults in the M ap P rogres s link that you c an c lic k to s how the map in a new brows er window. T he s erver- s ide s c ript geoc odes eac h loc ation and returns a G oogle M ap with markers bas ed on the U P S logo over eac h loc ation, with c olored polylines c onnec ting themthus des c ribing the path of your pac kage. 3.10.3. Hacking the Hack You'll note that this c ode als o ens ures that the loc ation is within the U nited States , whic h means it won't work if the pac kage's origin or des tination is outs ide the States . I f you live outs ide the U .S. (and are feeling adventurous ), you might try removing or c ommenting that line out in your loc al c opy of ups track.us er.j s (buried s omewhere in your M ozilla us er direc tory) and then res tarting Firefox to s ee if it does indeed work for you. Hack 26. Follow Your Packets Across the Internet Ever wonder where your network traf f ic goes when you visit a site on the 'Net? N ot long after the I nternet began to be widely us ed in our s oc iety, a new word began to gain c urrenc y among the public to evoke the experienc e of being able to find information and c ommunic ate with people from all over the globe, and that word was cybers pace. I n fac t, the word "c ybers pac e," taken from the term cybernetics , a tec hnic al term for human- c omputer interfac es , has been s o overus ed that it c omes ac ros s as trite or hac kneyed today. A ll the s ame, the word c onjures up an image of s weeping digital vis tas , waiting to be explored and homes teaded, and s o has a great deal of potenc ywhic h is probably why the word bec ame a c lic he in the firs t plac e. T he fac t, however, is that the I nternet works s o beautifully and, us ually, s o trans parently, that mos t people don't take the time to c ons ider that c ybers pac e and meats pac e (as we hac kers s ometimes jokingly refer to the Real World) are ac tually c onnec ted. O bvious ly, every web s erver, D SL router, c able modem, dial- up s ervic e, and s o on, is loc ated s omewhere on the planet. But who knows where? 3.11.1. From Clicks to Bricks A s it happens , the Whereis s ervic e at http://www.pars ec .it/whereis / knows where I nternet addres s es are hos ted in the real world, s ometimes with as tonis hing ac c urac y. T he front page of the s ite, c learly modeled after G oogle's , offers a s imple s earc h box, where you c an type in an I nternet domain name or an I P addres s in dotted- quad format (e.g., 192.168.1.1). C lic king the loc ate button takes you to the view s hown in Figure 3 - 1 8 , with a G oogle M ap s howing a marker over the mos t probable phys ic al loc ation of that I nternet addres s . C lic king on the marker pops up s ome bas ic information about the addres s , inc luding the c ountry and loc ale that it's believed to be phys ic ally loc ated in or near. Whereis us es the s tandard G oogle M aps A P I to dis play the map on the res ults page. E mbedded within a J avaSc ript bloc k on the res ults page is a c all to the GMarker( ) c ons truc tor, whic h s pec ifies the phys ic al c oordinates of the I nternet addres s and generates the marker that you s ee on the map. What's partic ularly interes ting about Whereis is how ac c urately it identifies the approximate loc ation of high- s peed res idential c onnec tions , s uc h as D SL and c able modems . I f you have s uc h a c onnec tion, try putting in your own I P addres s at home. I f you don't happen to know what your I P addres s is at homeand it may be as s igned dynamic allyyou c an us e an online s ervic e like http://www.whatis myipaddres s .c om/ to find out what public I P addres s you're appearing from, and then c ut and pas te that addres s into the Whereis s earc h box. What's even more interes ting about Whereis is that when it fails , as it might if your I nternet provider us es an ups tream web proxy (whic h A O L has been known to do). A s a res ult, Whereis may dec ide that you're in, s ay, Res ton, V irginia, even though the s ign outs ide your hous e s ays "Welc ome to Rapid C ity, I owa! " N ote als o that what Whereis tries to return is the phys ic al loc ation of the hardware hos ting the domain, not the plac e that the web s ite or even the domain name purports to repres ent, whic h is why web s ites s uc h as zooleika.org.uk and www.freemap.in turn up in Fremont, C alifornia, rather than in L ondon or M umbai. A ls o, it's c onc eivable that s ome large web s ites might be hos ted in different loc ations , with different I P addres s es for the s ame domain name, whic h might res ult in different loc ations being returned on different tries for a s ingle addres s . Figure 3-18. Whereis correctly places www.google.com in Mountain View, California 3.11.2. How It Works T he fac t that Whereis does as well as it does s eems nothing s hort of mirac ulous , under the c irc ums tanc es . T he I nternet A ddres s and N aming A uthority (I A N A ), lic ens es a number of organizations around the world to manage the alloc ation of I P addres s es and domain names . E ac h of thes e organizations maintains its own public databas e of addres s as s ignments , whic h typic ally c an be ac c es s ed through the whois s ervic e on the 'N et. T he problem is that eac h whois databas e returns res ults that have different information and are formatted in different ways . N ot only that, but even onc e you've got, s ay, a mailing addres s for the owner of a given range of I P addres s es , you s till don't nec es s arily know where that plac e is in the world, in terms of latitude and longitude, whic h means you c an't yet put it on a map or s ay what els e is nearby. So, the problem of phys ic ally loc ating an I P addres s turns out to be quite diffic ults o diffic ult, in fac t, that there aren't any worthwhile free- as - in- freedom s ourc es of this information on the 'N et that are more prec is e than the c ountry level. M apping I P addres s es to c ountries c an be us eful for c ollec ting s tatis tic s on international vis itors to your weblog, but it's no good for making dec ent maps . I ns tead, P ars ec Tec h s .r.l., the maintainers of the Whereis s ervic e, would s eem to be us ing M axM ind's G eoI P databas e, whic h, as you c an s ee, does offer pretty impres s ive res ults . You c an learn about M axM ind's produc ts , whic h, interes tingly enough, are us ed firs t and foremos t for c redit c ard fraud prevention, at http://www.maxmind.c om/. 3.11.3. Hacking the Hack Seeing where your favorite web s ites ac tually live in the real world c an be quite fas c inating, but does n't it make you c urious to s ee how your reques ts get there in the firs t plac e? I t definitely did for me, s o I dec ided to hac k the hac k, by building a trac eroute mapping s ervic e on top of Whereis . I n tec hnic al parlanc e, the term trac eroute is us ed to des c ribe an attempt to dis c ern whic h c omputers an I nternet P rotoc ol pac ket travels through on the way to its des tination, after the U nix network diagnos tic s tool des igned for that purpos e. (A very s imilar tool s hips with Windows , but its name has been abbreviated to tracert.) T he traceroute utility works as follows : all traffic s ent over the I nternet is broken up into pac kets , and eac h pac ket that's s ent is marked with the I P addres s of the s ender and the intended rec eiver. A dditionally, eac h I P pac ket is marked with a T ime- toL ive (T T L ), whic h s pec ifies how many network hops the pac ket c an travel through. E ac h time a c omputer forwards the pac ket towards its des tination, the T T L value in the pac ket header is dec remented by one, and if it ever reac hes zero, a mes s age is s ent bac k to the s ender informing it that the rec eiver was unreac hable. T his feature of the I nternet P rotoc ol is des igned to allow network engineers to detec t loops and other routing problems . traceroute piggybac ks on this proc es s , by firs t s ending out a tes t pac ket to a given des tination with a T T L of 1 , and then a pac ket with a T T L of 2 , and s o on. E ac h time, the c omputer at eac h s uc c es s ive network hop along the way drops the T T L to zero and bounc es the pac ket, thereby revealing its I P addres s . T he proc es s c ontinues until the T T L value reac hes the number of network hops to the des tination, at whic h point the entire route is known. T he time taken to perform eac h s tep provides an es timate of round- trip network latenc y and c an be us ed to identify bottlenec ks in a network route. Fortunately, traceroute has a s uffic iently s imple output format that the res ults c an eas ily be pars ed in J avaSc ript by a web brows erand that's exac tly what the G oogle M aps trac eroute at http://mappinghac ks .c om/projec ts /gmaps /trac eroute.html does . Start by running TRaceroute <hostname> from your * nix or O S X terminal, or TRacert <hostname> from the Windows c ommand line, where <hostname> is an I nternet domain name or an I P addres s . C opy the output to the c lipboard, then go bac k to your web brows er and pas te the res ults into the text box on the right, as s hown in Figure 3 - 1 9 . Finally, c lic k "Trac e your pac kets ! " and watc h the hos ts between you and your c hos en des tination appear on the map, one by one. C lic king on any of the markers that s how up opens an info window that s hows the c ountry and loc ale, the s ervers hos ted there, and the reported network latenc y to that hos t. Figure 3-19. The route from New York City to googlemapshacks.com O n Windows , you c an get to the c ommandline interfac e by going to Start Run, typing in cmd, and then c lic king O K. U nder the hood, when you c lic k Trac e, a J avaSc ript func tion pars es the individual entries from the s upplied traceroute output by looping over it with a regular expres s ion. N ext, it s ends eac h I P addres s to Whereis via as ync hronous XMLHttpRequest(), and then us es another regular expres s ion to s c rape the c oordinates out of the J avaSc ript in the returned H T M L page. A s the res ults c ome bac k, a marker is c reated on the map for eac h unique loc ation, us ing G oogle M aps GMarker objec ts . Some c are is taken to note when I nternet hos ts are lis ted as being at the s ame loc ation, s o as to avoid redundant overlapping markers . A dditionally, a line is drawn between eac h s uc c es s ive loc ation with GPolyline overlays , to mark out the path of your pac kets as they s peed through the ether. T he c ode runs to over 1 8 0 lines , s o we don't have room to print it here, but you c an always view the s ourc e of the page in your brows er if you're c urious to s ee how it works . Try it with a few different hos ts and s ee what s ort of res ults you get. You might s ee c ertain patterns emerge, s uc h that your pac kets may have to run through a number of s pec ific hops jus t to get out of your I SP. For variety's s ake, you might try mapping trac eroute res ults from any of the online trac eroute s ervic es lis ted at http://trac eroute.org/. Finally, if you map network routes that c ros s the P ac ific O c ean, you may dis c over an interes ting flaw in G oogle M aps polylines , as s hown in Figure 3 - 2 0 , whic h is that they c an't c ros s the I nternational D ate L ine! O ops ! Figure 3-20. Hey, wait! You're going the wrong way! Hack 27. Add Google Maps to Any Web Site Greasemap adds inf ormative Google Maps to almost any page on the Web. T here are lots of s ites on the Web that don't have maps but c ould really us e them. A ny web page with an addres s or a s et of latitude and longitude c oordinates is a c andidate for a potentially us eful map. L et's s ay, for example, that you want to vis it O 'Reilly's global headquarters to purc has e the next hot A nimal book s traight from the books tore in the rec eption lobby. You c ould go to http://www.oreilly.c om/oreilly/c ontac t.html and get the addres s , but what good does that do you? A t the very leas t, you'll have to c opy the addres s to your c lipboard, and then go to http://maps .google.c om/ in another brows er window, pas te the addres s in there, and s o on. I s n't there s ome way your web brows er c ould jus t do this for you? 3.12.1. Greasemap to the Rescue A s it happens , there is a wayif you're running M ozilla Firefox. Firefox s upports an extens ion c alled G reas emonkey, whic h allows c us tom J avaSc ript- bas ed us er s cripts to, well, monkey with the c ontents of any page you view in your brows er. A s you c an imagine, there is a wealth of pos s ibilities inherent in the G reas emonkey c onc ept. V inq.c om's G reas emap is one s uc h us er s c ript for G reas emonkey. G reas emap augments any web page you vis it, by s earc hing the page for s treet addres s es and c learly marked geographic c oordinates . I f it finds any, G reas emap provides a c lic kable mes s age bar ac ros s the top of the page, notifying you that a map is available. C lic king on the mes s age bar adds an I Frame to the top of the page, in whic h a G oogle M ap is loaded, dis playing all the loc ations found on that page. T he maps from G oogle remain interac tive; you c an zoom in, pan around, and s o on. T he map will be one wide map if there are multiple loc ations found, or two s maller maps an overview map and a zoomed in mapif there is jus t one loc ation found on the page. 3.12.2. Installing Greasemap I ns talling G reas emap takes a few s hort s teps and s hould be almos t painles s . 1. D ownload and ins tall G reas emonkey (http://greas emonkey.mozdev.org/). When you firs t try to ins tall G reas emonkey, you may s ee a thin bar at the top of Firefox that s ays "Firefox prevented an extens ion from loading." C lic k the button at the right s ide of that bar, then "A llow extens ions from that s ite." O nc e you've done this , try ins talling G reas emonkey again; it s hould work the s ec ond time around. 2. Res tart Firefox. T his allows Firefox to load the newly ins talled extens ion. 3. V is it.the G reas emap homepage at http://www.vinq.c om/greas emap/. A bout halfway down the page, you'll s ee a link to ins tall the G reas emap s c ript. Right- c lic k this link, and then c hoos e the I ns tall U s er Sc ript option to ins tall the G reas emap s c ript in your brows er. To unins tall G reas emap, go to the Tools M anage U s er Sc ripts menu in Firefox, s elec t G reas emap, and c lic k the U nins tall button. You c an als o us e this panel to temporarily dis able it. You c an als o temporarily dis able G reas emap by dis abling G reas emonkey its elf, by c lic king the G reas emonkey ic on in the lower- right c orner of your brows er. T he ic on s hould turn gray, indic ating that G reas emonkey is deac tivated. C lic king the ic on again reac tivates G reas emonkey. To upgrade G reas emap, firs t unins tall it, then follow Step 3 above to ins tall the lates t vers ion. U nfortunately, there's no way to avoid unins talling firs tthis is a limitation of G reas emonkey. 3.12.3. Taking Greasemap Out for a Spin O nc e you've got G reas emap ins talled, getting a map for any loc ation s hown on a web page bec omes a s nap. Figure 3 - 2 1 s hows the G reas emap vers ion of O 'Reilly M edia's c ontac t page, with the mes s age bar at the top of the page. Figure 3-21. O'Reilly Media's contact page, with the Greasemap message bar C lic king on the mes s age bar loads a G oogle M ap in an I frame at the top of the page, with a marker plac ed on the map for eac h loc ation found on the page, as s hown in Figure 3 - 2 2 . C lic king a marker on the map highlights the matc hing loc ation on the right s ide of the frame, and c lic king the "Big map in new window" link does jus t what it s ays : it opens a larger vers ion of the s ame map in a new brows er window. From this larger map, you c an c lic k on the markers to get an info window that allows you to s earc h for direc tions to that plac e, as s hown in Figure 3 - 2 3 . Figure 3-22. O'Reilly Media's contact page plus the Greasemap frame Figure 3-23. Search for driving directions in a new browser window with a single click I ns tead of a whole lot of frus trating c utting and pas ting, and opening new brows er windows , G reas emap turns the proc es s of finding direc tions to a loc ation s hown on a web page to a mere three c lic ks of the mous e button. Sometimes G reas emap reports more loc ations in the mes s age bar than it ac tually s hows on the map. T he reas on for this is that although G reas emap is fairly liberal about identifying loc ations on a web page, oc c as ionally not all of them c an be identified with ac tual geographic c oordinates when it c omes time to generate the map. A ddres s es aren't the only thing that G reas emap c an illus trate on a map. Several other types of loc ation, s uc h as geourl.orgs tyle I C BM tags c an be detec ted and mapped, as well. For example, Figure 3 - 2 4 s hows the "loc ation" of Ric h G ibs on's home page at http://www.tes tingrange.c om/. A lthough there aren't any addres s es direc tly vis ible on Ric h's s ite, there is an H T M L meta element embedded in the page that s pec ifies a latitude and longitude, that G reas emap c an identify and plot on a G oogle M ap. Figure 3-24. Rich's home page, automatically identified and mapped by Greasemap 3.12.4. How Greasemap Identifies Locations G reas emap us es J avaSc ript regular expres s ions to identify loc ations in a web page. T he following s tyles of loc ation referenc e are c urrently s upported: 1600 Amphitheatre Parkway, Mountain View, CA 94043 A t the moment, only U .S. addres s es are s upported. T he ZI P C ode is optional. <meta name="geo.position" content="41.328,-110.292"> T his s tyle of H T M L meta element is us ed by s ites that are indexed from geourl.org. <meta name="ICBM" content="41.328,-110.292"> T his is an alternate form of the s ame. N 42 25.159 W 071 29.492 D egrees and dec imal minutes are often us ed as geoc ac he c oordinates on geocaching.org. geo:lat=…and geo:long=… T his W3 C - derived s tyle of geotagging is frequently us ed on s ites s uc h as del.ic io.us and Flic kr. See http://www.flic kr.c om/photos /tags /geotagged/ for examples . Sinc e the G oogle M aps A P I does n't offer addres s lookups , G reas emap c urrently turns U .S. s treet addres s es into latitude/longitude c oordinates on the s erver s ide, us ing the C ens us Bureau's T I G E R/L ine data with the Geo:: Coder::US P erl module. C anadian and U K addres s es s hould be c oming s oon. I f you're interes ted in having G reas emap identify other kinds of addres s es or c oordinates , have a look at the J avaSc ript s ourc e at http://www.vinq.c om/greas emap/. I f you wind up modifying the G reas emap s ourc e to inc lude your favorite way to s pec ify a loc ation, pleas e s end us the c ode! We're always looking for new ways to improve the us efulnes s of this tool. 3.12.5. See Also Geo::Coder::US c an be found on the Web at http://geoc oder.us /. See "Find the L atitude and L ongitude of a Street A ddres s " [Hack #62] for more info on how to us e the web s ervic e bas ed on it. M ark P ilgrim's Dive I nto Greas emonkey provides an exc ellent introduc tion to c reating and improving G reas emonkey s c ripts . You c an read the entire book online at http://www.diveintogreas emonkey.c om/. Mark Torrance Hack 28. How Big Is That, Exactly? Explore the size of geographic regions in terms of those you already know. A G oogle s earc h for "roughly the s ize of" returns 3 9 8 ,0 0 0 res ults . C ertainly this s ugges ts that, when it c omes to vis ualizing the s ize of faraway plac es , we feel the need to refer to the unknown in terms of the familiar. Take this news paper quote, for example: …when the A mazon s hrank a rec ord 1 1 ,2 0 0 s quare miles , an area roughly the s ize of Belgium, or the A meric an s tate of M as s ac hus etts …. I read that and get a vague s ens e of c onfus ion and think, "Wow, I bet the people in Belgium and M as s ac hus etts know what that means , but I s ure don't." T here's more: "H uge ic eberg menac es A ntarc tic a…roughly the s ize of the is land of J amaic a." (http://www.theregis ter.c o.uk/2 0 0 5 /0 5 /2 0 /ic eberg_penguin_m "T he larges t- known ic eberg was from this region. I t was roughly the s ize of the s tate of Rhode I s land." (http://www.fac tmons ter.c om/ipka/A 0 7 8 1 6 6 8 .html) "M onths later, after I dis c us s ed what I had s een with the oc eanographer C urtis E bbes meyer, perhaps the world's leading expert on flots am, he began referring to the area as the 'E as tern garbage patc h.' But 'patc h.' does n't begin to c onvey the reality. E bbes meyer has es timated that the area, nearly c overed with floating plas tic debris , is roughly the s ize of Texas ." (http://www.naturalhis torymag.c om/1 1 0 3 /1 1 0 3 _feature.html A s earc h for "roughly the s ize of" reveals interes ting things . T he fac t that the writer needed to find s omething, anything, to us e to provide a meas ure of s patial c ontext hints at s omething odd and interes ting. A n "E as tern garbage patc h…roughly the s ize of Texas "? T he image is vivid. 3.13.1. The Hack T he s tatement "roughly the s ize of…" demands the ability to c ompare the unknown with a known quantity. A t http://www.mappinghac ks .c om/projec ts /gmaps /s ize_of.html you c an s elec t the outline of a s tate or c ountry and pin it onto the map. P ic k the s hape from a drop- down box then s c roll around on the map until you find a familiar plac e and c lic k. Figure 3 - 2 5 s hows an outline of P enns ylvania on top of H ungary. State boundaries c an have an his toric al bas is , but often are rather arbitrary. T here is no partic ular reas on for us to res pec t the work of our forebearers , and with G oogle M aps we don't need to! Figure 3 - 2 6 s hows an outline of the s tate of D elaware, rotated 9 0 degrees c loc kwis e and pinned over the San Franc is c o Bay area. Figure 3-25. Hungary is roughly the size of Pennsylvania Figure 3-26. Delaware is roughly the size of the Bay Area D epending on how you maneuver the outline, D elaware is roughly the s ize of the San Franc is c o Bay A rea. O r perhaps the Bay A rea is roughly the s ize of D elaware. O nc e you s tart doing c omparis ons like this , you need a fully dec lens ed language, like L atin, s o you c an s pec ify whic h plac e is nominative and whic h one ac c us ative. (O ddly, neither would be loc ative.) P inning a s tate or c ountry onto the world expands our unders tanding of geography. For example, people don't apprec iate how very long C hile is . Figure 3 - 2 7 s hows C hile on top of the wes t c oas t of C aliforniait goes from the s outhern tip of A las ka to the bottom of Baja C alifornia! Figure 3-27. Chile flipped over and pinned to the west coast of North America T his image of C hile has been flipped, s o s outhern C hile is near A las ka and northern C hile over Baja. T he latitudes roughly matc h, and there is a general c orres pondenc e in c limate. T he north of C hile inc ludes the A tac ama des ert, the dries t plac e on earth. I n parts of the A tac ama, there has been no rainfall in rec orded his tory. Baja C alifornia is not quite that dry, but it is pretty darn dry! T he c entral part of C hile is a ripe agric ultural region, analogous to C alifornia, then tending toward fores ts in the Southern L akes dis tric t, whic h is evoc ative of the I nland P as s age of C anada and A las ka. (A gain, we have that nominative and ac c us ative ques tion: whic h one is analogous to the other, and whic h one is the defining ins tanc e? ) When we rotate C hile and lay it over the whole of the U nited States , it reac hes mos t of the way from C alifornia to Florida, as s hown in Figure 3 - 2 8 . Figure 3-28. Chile shows her length You don't need G oogle M aps to demo this , but the eas e with whic h the G oogle M aps A P I handles everything on the c lient s ide (from rendering the map bac kground to overlaying the boundary outlines to handling the us er interac tion), made this interes ting idea an implementation in jus t a few hours . 3.13.2. The Code We s tarted by taking outlines of our example regions from c ommon s ourc es in E SRI Shapefile format. We then us ed a s imple P erl s c ript to extrac t thes e outlines and c alc ulate the bounding box of the c oordinates in the outline. Taking the average of the c orners of the bounding box, we es timated a c enterpoint for eac h region, and then c alc ulated the offs et of eac h c oordinate in the perimeter from that c enter point. T his allows us to draw the outline of the c ountry or s tate around any arbitrary point that a us er might c lic k on the map. A ls o, we took this opportunity to quantize the c oordinate values es s entially s napping them to a grid of an arbitrary s izeand then removed the duplic ate c oordinates to get the region's outline down to a number of points that's manageable for G oogle M aps . A dditionally, we s c aled the longitudinal dis tanc es by the c os ine of the c enter latitude, s o that the areas dis play at more or les s the right s ize anywhere on the map. T hes e doc tored outlines were then put in individual text files on our s erver. T he J avaSc ript us es the GXmlHttp c las s from the G oogle M aps A P I to fetc h the file for a given c ountry or s tate from our s erver: function loadPolygonData (url, displayNow) { if (!url) url = document.forms['selectPoly'].area.value; var xmlHttp = GXmlHttp.create(); msg.innerHTML = "Fetching " + url; xmlHttp.open('GET', url, true); xmlHttp.onreadystatechange = function () { msg.innerHTML = "Fetching " + url + "(readyState " + xmlHttp.readyState + ")"; if (xmlHttp.readyState == 4) { shape = parsePolygonData( xmlHttp.responseText if (displayNow) { var center = map.getCenterLatLng(); drawPolygon(null, center); } } } } xmlHttp.send(null); } T he U RL of the file that gets fetc hed is pulled from the following s elec t box: What's roughly the size of <select name="area"> <option value="size_of/california.txt">California</opt <option value="size_of/texas.txt">Texas</option> <option <option <option <option <option value="size_of/minnesota.txt">Minnesota</optio value="size_of/pennsylvania.txt">Pennsylvania< value="size_of/delaware.txt">Delaware</option> value="size_of/rhode_island.txt">Rhode Island< value="size_of/chile.txt">Chile</option> <option value="size_of/italy.txt">Italy</option> <option value="size_of/mexico.txt">Mexico</option> <option value="size_of/australia.txt">Australia</optio <option value="size_of/india.txt">India</option> </select>? Click on the map to find out. A s one example, the points file for C alifornia is at http://mappinghac ks .c om/projec ts /gmaps /s ize_of/c alifornia.txt and s tarts out like this : -3.93254 4.72960 -0.58090 4.72519 -0.58141 1.73040 3.44982 -2.02319 4.08442 -2.96202 3.77594 -3.31706 3.77654 -3.71225 T his data is proc es s ed with the parsePolygonData( ) func tion: function parsePolygonData (txt) { var rePoint = /^(\S+)\s+(\S+)$/igm; var match, pts = []; msg.innerHTML = "Parsing polygon data…"; while (match = rePoint.exec(txt)) { var lon = parseFloat(match[1]), lat = parseFloat(match[2]); pts.push(lon, lat); } msg.innerHTML = "Click anywhere on the map to continue return pts; } T his bit of c ode defines a regular expres s ion to read the pairs of points as longitude and latitude, and pus h them onto an array c alled pts[]. N ext, the drawPolygon( ) func tion is c alled when a us er c lic ks on the map: function drawPolygon (overlay, point) { msg.innerHTML = "Got click at " + point; if (point && shape) { var angle = parseInt(document.forms["selectPoly"]. var poly = makePolygon( point, angle, shape ); // msg.innerHTML = "Showing poly " + poly + " at " map.centerAndZoom(point, 13); map.clearOverlays(); map.addOverlay(poly); } } T he drawPolygon( ) func tion takes the angle that you are applying to turn the s tate or c ountry outline, and then c alls makePolygon( ) to generate a polygon repres ents the s tate or c ountry borders . Finally, the polygon is added to the map with map.addOverlay( ), and the map is rec entered and zoomed in. T he mathematic al c ore of the c ode is in the makePolygon( ) func tion. function makePolygon (center, angle, ptsIn) { var ptsOut = []; if (isNaN(angle)) angle = 0; var theta = - angle * Math.PI / 180; for (var i = 0; i < ptsIn.length; i += 2) { var x = ptsIn[i] * Math.cos(theta) - ptsIn[i+1] * Math.sin(theta) + center.x; var y = ptsIn[i] / phi * Math.sin(theta) + ptsIn[i+1] * Math.cos(theta) + center.y; var pt = new GPoint(x, y); ptsOut.push } var poly = new GPolyline(ptsOut, 'ff0000', 3, 1); msg.innerHTML = "Generated polygon centered at " + cen return poly; } T he makePolygon( ) func tion takes the reques ted angle, c onverts it from degrees to radians , and s tores it in theta. T he x and y c oordinates are c ompos ed by s c aling eac h point from the geographic outline by the horizontal and vertic al c omponents of theta, and then offs etting that point from the point where the us er c lic ked on the map. T hes e c oordinates are us ed to c reate GPoint objec ts that are pus hed onto an array, and then as s embled into a GPolyline, whic h is returned and then dis played on the map by drawPolygon(). 3.13.3. How Big Is "That Big"? We would hope that this tool helps provide a bit of s patial pers pec tive to addres s a weaknes s in geographic al literac y. P roblems of c ultural referents remain. For example, it is s aid that one differenc e between A meric a and E ngland is that A meric ans think 1 0 0 years is a long time, and the E nglis h think 1 0 0 miles is a long way. P erhaps the tool needs the addition of a s et of radio buttons , modeled after a Slas hdot poll. When fac ed with a 1 0 0 - mile trip, I will: H appily drive down in the morning and bac k that night Try to s c hedule it for the bes t time G o for a week- long trip C ons ider it an abs urdly extreme ordeal T he Bentley hardly gets up to s peed in 1 0 0 miles C owboy N eal/I 'm on a home releas e program, you ins ens itive c lod H umor as ide, c alibrating perc eived dis tanc es is an important tas k. T he J hai P rojec t http://www.jhai.org/ is ins talling c omputers and Wi- Fi relays to allow people in remote villages to c onnec t with eac h other and the world. Farmers c an s ee what the c urrent market pric es are before dec iding to take their goods to market, bec aus e a 1 0 - mile trip c an take hours , and the the differenc e between s elling on a bad- pric e day and a good- pric e day has an enormous effec t on the well- being of an extended family. By getting c urrent market pric es and dealing direc tly, farmers and c rafts people are able to double their inc ome. I c an drive from Sebas topol, C A down to San Franc is c o I nternational A irport, fly to L os A ngeles , and return in les s time than it takes to get to the neares t market town in the mountains of L aos . A mile (or kilometer) may be the s ame dis tanc e the world round, but it does n't mean the s ame thing to me as it does to a L aotian farmer. E ven though (for s ome people) our world is getting s maller every day, areas and dis tanc es s till matter to humanity a great deal. Chapter 4. On the Road with Google Maps Sec tion 4 .1 . H ac ks 2 9 4 1 : I ntroduc tion H ac k 2 9 . Find the Bes t G as oline P ric es H ac k 3 0 . Stay O ut of Traffic J ams H ac k 3 1 . N avigate P ublic Trans portation H ac k 3 2 . L oc ate a P hone N umber H ac k 3 3 . Why Your C ell P hone D oes n't Work T here H ac k 3 4 . P ublis h Your O wn H iking Trail M aps H ac k 3 5 . L oad D riving D irec tions into Your G P S H ac k 3 6 . G et D riving D irec tions for M ore T han Two L oc ations H ac k 3 7 . V iew Your G P S Trac klogs in G oogle M aps H ac k 3 8 . M ap Your Wardriving E xpeditions H ac k 3 9 . Trac k Your E very M ove with G oogle E arth H ac k 4 0 . T he G hos t in G oogle Ride Finder H ac k 4 1 . H ow G oogle M aps G ot M e O ut of a Traffic T ic ket 4.1. Hacks 2941: Introduction By now, you s hould be familiar with the bas ic us e of G oogle M aps for finding driving direc tions . H owever, the flexibility of G oogle M aps offers plenty more opportunities for figuring out how to get from point A to point B. We'll s ee that G oogle M aps c an as s is t you in finding the bes t gas oline pric es , avoiding traffic c onges tion, and even avoiding the us e of an automobile altogether! I n this day and age, one of the mos t us eful tools of the digital c artographer is her Global Pos itioning Sys tem, or G P S, rec eiver. We're als o going to explore s everal us eful c ombinations of G P S and G oogle M aps , inc luding loading routes from G oogle M aps into your G P S rec eiver, plotting your travels from the G P S rec eiver's trac klog within G oogle M aps , and how to us e your G P S to make G oogle M aps of loc al wireles s network c overage. A s a bonus , we'll als o s ee how G oogle M aps s aved one man from an expens ive traffic fine! Hack 29. Find the Best Gasoline Prices Drive your mouse f or cheaper f ueland then catch a movie. M y friends in c ons truc tion s pend a lot of time driving up and down H ighway 1 0 1 , and they all know where the c heap gas is . I s pend my time s itting in front of a c omputer, but thanks to http://www.ahding.c om/c heapgas /,I als o know where the c heap gas flows . 4.2.1. What a Gas! T he C heap G as s ite in Figure 4 - 1 us es data from http://www.gas buddy.c om/, whic h aggregates us er reports of gas pric es s o that everyone c an benefit. You c an als o c ontribute to the G as Buddy web s ite by bec oming one of their volunteer s potters , thus gratifying your natural human des ire to tell other people s omething that they don't know. Figure 4-1. Where are the deals? A fter you pic k a c ity, the s ite lis ts gas s tations on the s ide bar and markers on the map. T he green ic ons repres ent the lowes t half of gas s tations by pric e and the red ic ons are the high half. A s s hown in Figure 4 - 1 , eac h s tation has a marker with more information. What is interes ting about this example is the integration with http://www.gas buddy.c om/. G as Buddy.c om provides the databas e of c heap gas , but is not run by c artographers , s o A hding.c om was able to c reate the now- c las s ic mas hup. What c aus es gas pric e variations ? A n interes ting projec t in geos patial analys is would be to s ee if one c ould draw any c onc lus ions about why there is s uc h variation in pric es from s tation to s tation. O verlaying different thematic layers and doing c alc ulations bas ed on multiple data s ets is exac tly what a G eographic I nformation Sys tem (G I S) is all about, but G oogle M aps has s hown that there has been an enormous demand for an eas y- to- us e "put a pus h pin on a map" s olution. T hat is now a s olved problem! O nc e you get your fuel pric e woes s traightened out, you c an c lic k on the M ovies link at http://www.ahding.c om/movie/ and us e the s ame bas ic interfac e to query the I nternet M ovie D atabas e (http://www.imdb.c om) to c hec k out loc al movies . 4.2.2. GasWatch A nother low- c os t- gas oline s olution is G as Watc h by A drian G onzales , whic h is available from http://www.widgetgallery.c om/view.php? widget=3 6 5 0 0 . T his is a widget that will run under Konfabulator for Windows and M ac O S X (the gras s is greener on both s ides ) and s how you the bes t pric es for gas . "G as Watc h s hows you the lowes t pric ed gas in your ZI P C ode. I t als o provides a handy button to s how a map to the gas s tation. M aps for M ac us ers provided by G oogle M aps ." To ins tall the widget you need Konfabulator (http://www.konfabulator.c om/download). Konfabulator is a J avaSc ript environment for your des ktop. P eople c an write s mall programs c alled widgets , and you c an run them under Konfabulator. For M ac O S X, download the dis k image (.dmg) file. When it is finis hed downloading, mount the .dmg by double- c lic king on it. When the folder opens , drag the ic on into your applic ations folder. N ow you c an download the G as Watc h widget. D ouble- c lic k and it will prompt for your ZI P C ode, and then s it quietly on your D es ktop, as s hown in Figure 4 - 2 , letting you know the c urrent c heapes t loc al gas pric es . Figure 4-2. Cheap gas on your desktop C lic king on the M ap button will bring up G oogle M aps with this addres s highlighted. T his is a great example of the value to be gained from c onnec ting different s ourc es of data in new ways . Hack 30. Stay Out of Traffic Jams A f ew Google Maps mashups to keep you and your car out of trouble. A c c ording to s tatis tic s publis hed by the BBC in 2 0 0 2 , there are nearly half a million traffic jams in Britain every yearor more than 1 0 ,0 0 0 a weekand thos e numbers were on the ris e. A quarter of Britain's main roads are jammed every day, and nearly 1 in 4 res idents of the U .K, have to c ontend with heavy automobile traffic daily. I n our c ar- obs es s ed U nited States , automobile c ommuters s pent an average of 4 7 hours delayed by traffic c onges tion in 2 0 0 3 alone, ac c ording to es timates publis hed by the Texas Trans portation I ns titute. I n the ten larges t metro areas in the States , that figure goes up to an average of 6 1 hours a year. T hat's two and a half whole days out of every year, s pent by the average driver, jus t s itting in the c ar, idling in bumper- to- bumper gridloc k! Fortunately, the hac kability of G oogle M aps offers hardy urban dwellers s uperior ac c es s to timely information in this fas t- pac ed era! A lmos t as s oon as G oogle's flas hy road maps hit the Web, hac kers went to work plotting out the mias ma of traffic c onges tion that plagues the lives of s o many in the urbanized wes tern world. 4.3.1. Avoiding Gridlock in the United States T he bes t G ooglified traffic maps of the States c ome from the G oogle-Traffic . c om Traffic - Weather M aps s ite at http://s upergreg.hopto.org/google- traffic .c om/. U s ing RSS from the Traffic .c om web s ite, "Super" G reg Sadets ky has as s embled an informative s ervic e that reports the loc ations of traffic c onditions in major U .S. c ities . From the front page, you c an s elec t your c ity of interes t, and c lic k the G o! button to be taken direc tly to the map. Figure 4 - 3 s hows the c urrent traffic c onditions in P hiladelphia. Figure 4-3. A Google-Traffic.com traffic map of Center City, Philadelphia C us tom ic ons s how the type of delayeither c ons truc tion or s ome kind of inc identand the c olor of the ic on indic ates the s everity of the delay, from yellow to red. C lic king on any of the ic ons loads a c allout that dis plays the details of the traffic delay. M irac ulous ly, the Sc huylkill E xpres s way (I - 7 6 ) is c lear this morningbut it's early yet, only about 6 :3 0 A .M .while the Broad Street exit of I 9 5 s hould plainly be avoided, es pec ially later this evening when bas eball fans will floc k to Veterans Stadium to watc h the home team los e to the Rangers . N aturally, you c an c lic k on the Satellite link to get the s ame view of c urrent traffic c onditions , laid over s atellite imagery, ins tead of road maps . (A lthough it's not entirely c lear what utility this feature ac tually offers , it's s till pretty darn c ool.) You c an link to thes e maps , bookmark them, or embed them on your own page in an H T M L iframe, us ing the following U RL format, s ubs tituting your c ity of interes t for "P hiladelphia,+P A ": http://supergreg.hopto.org/google-traffic.com/traffic.php? Traffic details for 2 3 major c ities are offered on the s ite, inc luding A tlanta, Baltimore, Bos ton, C hic ago, D allas , D etroit, H ous ton, L os A ngeles , M iami, M inneapolis , N ew York, O rlando, P hiladelphia, P hoenix, P itts burgh, P rovidenc e, Sac ramento, San D iego, San Franc is c o, Seattle, St. L ouis , Tampa, and Was hington, D .C . A s a bonus , weather information for the s elec ted c ity is als o pulled from an RSS feed and is embedded in a s mall horizontal bar at the bottom edge of the map. I f you don't c are for this feature, you c an turn it off by adding &weather=0 to the U RL for your c ity. 4.3.2. Avoiding Gridlock in the United Kingdom T he opening of the BBC Bac ks tage s ervic e, whic h offers ac c es s to RSS feeds of many different kinds of information from the BBC , was almos t perfec tly timed with the initial releas e of G oogle M aps U K. I t didn't take long at all for s everal hac kers to leap to the c hallenge of plotting the BBC 's traffic feeds on G oogle's new road maps of Britain. O ne s olid example is A ndrew N ewdigate's Traffic M eis ter at http://gtraffic .datatribe.net/, whic h offers the by- now- familiar G oogle M aps view of the entire U K, with c us tom, c lic kable ic ons indic ating the type of delay. Figure 4 - 4 s hows an example of roadwork near Southampton. A nother interes ting take on the s ame idea c an be found on A lis tair Rutherford's gTraffic s ite at http://www.gtraffic .info/, whic h us es c olored ic ons to indic ate the s everity of the delay. A dditionally, the gTraffic s ite dis plays the lates t alerts in c hronologic al order down the right s ide of the page. Figure 4 - 5 s hows the s ame roadwork delay near Southampton on gTraffic .info. P otentially even more us eful to res idents of the U nited Kingdom, where petrol is more expens ive and private automobiles not quite the ins titution they are in the States , is the drop- down box at the top of the page that offers a Trans port option. Figure 4 - 6 illus trates the inc reas ingly dis mal s tate of Britis h rail in the modern era of trans port privatization. Figure 4-4. A TrafficMeister map of the southeastern UK Figure 4-5. A gTraffic.info map of the southeastern UK A s imilar take on this s ad s tate of affairs c an be found on D unc an Barc lay's s ite at http://bac ks tage.mindata.c o.uk/travel/, where you c an als o view either road or rail delays . Figure 4 - 7 s hows the s ame delayed train s ervic e, this time on the min-data.co.uk s ite. I nteres tingly, on this map, the marker has been plac ed at Watford J unc tion, where the train departed from, rather than Brighton, where its arrival has been delayed. Figure 4-6. Delayed train service to Brighton Figure 4-7. Delayed train service from Watford Junction 4.3.3. But, Wait, There's More! T he eagle- eyed reader will probably have already dis c overed this , but at leas t a c ouple of s ites have gone as far as remixing G oogle M aps with the BBC 's webc ams of traffic hots pots in s urveillanc e- happy L ondon. gTraffic .info has a C C T V option in the drop- down on the upper left; Figure 4 - 8 s hows the s ituation this morning outs ide St. J ames 's P ark, along P ic c adilly. Figure 4-8. It's a circus out there! T he amazing gmaptrac k s ite offers a s imilar view at http://www.gmaptrac k.c om/map/loc ations /2 4 /4 4 , where you c an als o c lic k a link to s ee the image at its s ourc e on the BBC L ondon J am C ams web s ite. O n either s ite, you c an c lic k the links on the right to view the c amera image in a c allout over the map loc ationprobably bes t to take a bic yc le this morning! 4.3.4. Hacking the Hack Several other web s ites that offer this kind of experimental traffic map c an be found on the BBC Bac ks tage web s ite at http://bac ks tage.bbc .c o.uk/. A lthough web- bas ed maps of traffic c onditions are nothing new, the eas e with whic h hac kers have been able to remix RSS feeds of traffic reports with G oogle's s tylis h mapping interfac e is a tes tament to the pos s ibilities inherent in open s ys tems loos ely joined by open protoc ols , even before G oogle publis hed its M aps A P I ! Hack 31. Navigate Public Transportation Finding your way around local public transit just got a lot easier. You have an appointment in town s omewhere, and you've jus t dis c overed from "Stay O ut of Traffic J ams " [Hack #30] that it's definitely not worth driving this morning. You fire up your loc al public trans it authority's web s ite, download their s ketc hy s c hematic map of the s ubway or bus s ys tem, and then dis c over to your c hagrin that the map gives you no idea of whic h s top on whic h route is ac tually c los es t to your des tination. D oes this s ound familiar? I f the G oogle M aps hac kers get their way, your experienc e will s oon be a thing of the pas t. A s of this writing, G oogle M aps enhanc ed public trans portation maps are only available for a few c ities in N orth A meric a. H ere's a rundown of what's available. 4.4.1. Vancouver T he firs t s top on our tour of G oogle M aps trans it mas hups is D avid P ritc hard's Vanc ouver Trans it M ap for the public trans portation s ys tem in Vanc ouver, BC . T he Vanc ouver Trans it M ap lives on the Web at http://www.david.enigmati.c a/maps /trans it.html. A s you c an s ee from Figure 4 - 9 , the s ite us es G oogle M aps polylines to depic t the major trans it routes in town. Figure 4-9. Public transit in Vancouver, BC T he trans it line s tops are depic ted with c irc les , whic h open an info window s howing the name of the s top and the inters ec ting bus lines . T he text labels s howing the names of major s tops at different zoom levels are als o c lic kable, and make for a nic e touc h in terms of the map's readability. 4.4.2. Boston M att King's Bos ton Subway Station M ap at http://www.thrall.net/maps /mbta.html takes s omething of a s imilar approac h, as you c an s ee in Figure 4 - 1 0 . I ns tead of the s tation labels on the map, along the top we get a row of c olorc oded drop- down boxes , organized by s ubway line, to help find individual s tations . C lic king any of the s tation markers opens an info window with the s tation name, s treet addres s , and navigational links . T he "To here" and "From here" driving direc tions links are pretty s elfexplanatory, but the "Zoom in" and "Zoom out" navigation links are s pec ial. I f the map is zoomed out, c lic king "Zoom in" will c aus e the map to iteratively zoom in, one level at a time, on a delay interval, s o that you c an s ituate the s ubway s top in the larger geographic c ontext of Bos ton. O nc e zoomed in, the "Zoom out" link performs the revers e operation. T his progres s ive zoomin/zoom- out is referred to by digital c artographers as ballis tic zoom. Figure 4-10. Subway stations in Boston, MA 4.4.3. Seattle C hris Smoak's Seattle Bus M ons ter s ite at http://www.bus mons ter.c om/ is probably the mos t feature- ric h of the G oogle M aps trans it mas hups we've s een s o far. T he s ite has three bas ic s ec tions : Bus Stops , Routes , and Traffic C onditions . I n the Bus Stops s ec tion, you type in an addres s , inters ec tion, or landmark to find bus s tops near that loc ation, as s hown in Figure 4 - 1 1 . C lic king on an individual bus s top s hows , almos t mirac ulous ly, the expec ted arrival times for the next few bus es on that route (if available). I n the Routes s ec tion, you c an type in route numbers to view routes , s tops along thos e routes , and c urrent bus loc ations . T he Traffic C onditions s ec tion s hows hundreds of traffic c ams in the area. P erhaps the mos t remarkable feature of this s ite is that, in the Routes view, you c an c lic k on a partic ular bus s top and s et an "alarm" for that s c heduled bus arrival. O nc e you've c reated the alarm, you c an c lic k on the alarm ic on in the info window, and you'll be prompted for a number of minutes lead time and an email addres s to s end the alarm to. I f your c ellular provider relays email to your phone as text mes s ages and mos t doyou c an enter the email addres s of your phone and be notified in real time when the bus is on its way! Figure 4-11. Public buses in Seattle, WA T he Bus M ons ter s ite makes heavy us e of the XM aps extens ion to the G oogle M aps A P I [Hack #64]. 4.4.4. New York City N aturally, the Big A pple, with one of the mos t extens ive public trans portation s ys tems in N orth A meric a, wouldn't be without at leas t one G oogle M aps trans it mas hup. Will J ames is res pons ible for the N Y C Subway M ap at http://www.onnyturf.c om/s ubwaymap.php. T he bas ic func tionality of this map is s imilar to that of other maps c lic k on a s tation, and an info window pops up, with the s tation name and one or more ic ons provide links to the M TA 's web page for the relevant s ubway lines that s top at that s tation, as s hown in Figure 4 - 1 2 . What's exc eptional about the N Y C Subway M ap is that, unlike the other trans it mas hups , it does n't us e the G oogle M aps GPolyLine c las s to depic t the s ubway lines . I ns tead, Will dec ided that the variety of c olors in the s tandard M TA s ubway map mes hed poorly with the default c olor s c heme of G oogle M aps , and that the map would look betterand be more read- ableif he made his own bac kground tiles . A n additional map type c ontrol marked "SU BWA Y " at the top- right c orner of the map, allows you to s witc h bac k and forth between that and the traditional G oogle M aps bac kgrounds . Will's proc es s for generating c us tom G oogle M aps bac kground tiles is des c ribed in C hapter 7 . 4.4.5. Chicago A drian H olovaty's C hic ago Trans it A uthority map page (http://www.holovaty.c om/blog/arc hive/2 0 0 5 /0 4 /1 9 /0 2 1 6 des erves s pec ial mention for being one of the earlier G oogle M aps mas hups . I ns tead of providing an integrated interfac e us ing the G oogle M aps A P I , the C TA map relied on a Firefox extens ion to integrate A drian's c us tom map tiles into G oogle M aps on the c lient s ide at the right time and plac e (namely, zoom level 5 over C hic ago). U nfortunately, as of this writing, the extens ion no longer works , probably due to s ubs equent c hanges to the G oogle M aps interfac e. Figure 4-12. Subway stations in New York City 4.4.6. Where's My City? D on't live in any of thes e plac es ? C an't find a G oogle M aps trans it mas hup for your hometown? P erhaps that's a s ign that you s hould finis h this book and then go out and make your own! Hack 32. Locate a Phone Number Perf orm reverse lookups with Google Phonebook and Google Maps. H ave a phone number, but you don't know where it originates ? You c an us e G oogle to get an addres s , and then G oogle M aps to pinpoint it. Your s earc h engine is a phone book? Why not? P hone numbers are jus t another thing that c an be s earc hed on! When you enter a phone number into the s earc h box on http://google.c om, the firs t link is to the G oogle P honebook (as s uming that the number is found). For example, doing a s earc h on the U .S. phone number (707) 827-7000 brings up the res ults s hown in Figure 4 - 1 3 . T he G oogle phone book is very forgiving. You c an s earc h for 707 827-7000 or 707-827-7000 or even 7078277000 and P honebook will s till work. I nteres tingly enough, you c an't s earc h for a phone number direc tly through the G oogle M aps s earc h box: you have to go through the regular G oogle Searc h firs t! Figure 4-13. Google Phonebook results for (707) 827-7000 T he G oogle P honebook is mapping- s ervic e agnos tic , s howing links to this addres s in G oogle M aps , Yahoo! M aps , and M apQ ues t. I f you c lic k on the G oogle M aps link, you c an do a loc al s earc h for s omething c ommon, s uc h as pizza, and then c lic k on "L ink to this page" near the top right of the page to get a page like Figure 4 - 1 4 . T he point is n't to get information on pizza, but to s how that when you c lic k on "L ink to this page," G oogle M aps loads the U RL for the c urrent map in your brows er. T hat U RL inc ludes the latitude and longitude of the c enter of your s earc h area as the sll parameter, whic h s tands for s earch lat/long. L ook at the addres s bar in Figure 4 - 1 4 , and you c an s ee the U RL query s tring ? q=pizza&sll=38.411170,-122.841720. So, phone number (7 0 7 ) 8 2 7 7 0 0 0 is loc ated at 3 8 .4 1 1 1 7 0 N , 1 2 2 .8 4 1 7 2 0 W. T hat loc ation is n't perfec t, but it is pretty darn good. See "I ns ide G oogle M aps U RL s " [Hack #7] for more on the s truc ture of G oogle M aps U RL s . Figure 4-14. Pizza near (707) 827-7000 A nother thing to note about that original G oogle s earc h for the phone number in Figure 4 - 1 3 , is that a s earc h for a phone number als o does a s tandard G oogle s earc h. T his c an be interes ting bec aus e it pulls things up in a new way. T he firs t G oogle link for O 'Reilly's phone number is a Road Warrior's C hris tmas lis t. Who would have thought that? Revers e lookup availability appears to vary over time. A t one point, a revers e lookup on my home phone number pulled up my s treet addres s . A s of this writing, it jus t returns the c ity and ZI P C ode. O ther res idential phone numbers that I 've tes ted s till work, and bus ines s lis tings s till pull up a full addres s . Hack 33. Why Your Cell Phone Doesn't Work There Trouble getting a signal? Google maps and the FCC database can help. I live almos t in the s hadow of a 3 0 .2 - meter c ell phone tower, and I have to go out on the porc h to get dec ent rec eption. What is up with that? I know the exac t height of the tower, thanks to M obiledia. You c an go to its s ite at http://www.c ellrec eption.c om/towers /index.html and brows e for c ell towers by c ity or s tate. When I look up Sebas topol, C alifornia, I get the map in Figure 4 - 1 5 . I live near the S in Sebas topol, s o you'd think I 'd have pretty good c overage 2 .5 bloc ks from the tower. C lic king on the overlay marker brings up information on the owner of the tower, as s hown in Figure 4 - 1 6 . So my problem appears to be that there is a tower, but my c ell provider does n't have gear up there. Figure 4-15. Cell towers near Sebastopol, CA You c an c lic k on the overlay marker bec aus e marker labels are H T M L and s upport links . M obiledia defines marker text with this line of c ode: var html="<h1><a href='http://www.cellreception.com/towers id + "'>" + name + "</a></h1><br>" + address + "<br>" + ci T his builds a U RL that c alls a s c ript on its s ite with more details . T his is an example of how you c an inc lude links and arbitrary H T M L in pop- up markers . M obiledia us es the FC C databas e of antennas , and as explained on the s ite: T he FC C does not require every antenna s truc ture to be regis tered, and the map may not lis t all the towers in the area. A dditionally, many c arriers have s old their tower as s ets to third party c ompanies , and leas ing agreements are unknown. I f this is the c as e, the bes t way to determine c arrier c overage is by reading c omments in the loc al area. So it is pos s ible that my provider rents s pac e on the tower, but s inc e the bes t way to determine c overage is to read the c omments , I think it is s afe to jus t as s ume that my c alls don't go to the mos t c onvenient tower. O n the right s idebar is a "C ell phone rec eption s earc h." E nter a ZI P C ode and it pops up a reader forum on rec eption, or in reality more likely the lack of rec eption. You c an als o s earc h for dead s pots and add your own reviews . Figure 4-16. Ah, that would be why I don't have service A nother neat feature of the s ite is that you c an get H T M L that lets people s earc h the rec eption and tower databas es from your s ite. J us t go to http://www.c ellrec eption.c om/add/index.html and fill out the form, and they s end links to an H T M L form that you c an embed in your own web page. Hack 34. Publish Your Own Hiking Trail Maps Tell your own stories with a mix of social sof tware and cartography. We've all found ours elves c limbing through hills ide brambles on a hot s unny day thinking, "T hat's the las t time I trus t that trailhead pamphlet." O r wors e, wanting to s how a friend a s pec ial plac e you found on a hike a few months ago but now c an't quite plac e. I f you're a hiker, mountain biker, roc k c limber, weekend warrior, amateur geologis t, s c out troop leader, endorphin junkie, eques trian, pedes trian, roc k c limber, birder, or s imple romantic , then have we got a hac k for you! T he s ite, whic h lives at http://BayA reaH ikingTrails .ning.c om, looks like Figure 4 - 1 7 . Bay A rea H iking Trails (BA H T ), written by Saumi M ehta and M ay Woo, allows you to c apture and publis h your trail maps with c omments , G P S trac klogs , and photos . E ven better, you c an eas ily overlay your G P S trac klogs on G oogle M aps via the A P I and provide a vis ual repres entation of your hike, bike, or ride alongs ide all thes e other goodies . But that's only the s tart. You c an als o offer thes e annotated trail maps to friends or s trangers for rating and reviewing. You c an even look for new hiking friends and fellow enthus ias ts . H ow's that for s oc ial? Figure 4-17. Bay Area Hiking Trails A ll right, s o that may not be enough. L et's take it one s tep further. N o s ingle s oc ial map c an c over all s c enarios of what you might want to do with it. With jus t a little bit of P H P knowledge, BA H T enables you to eas ily c hange or extend the us er input forms s o that you c an rec ord your own s pec ialized data: birds s een, bikers met, geoc ac hes planted, or geoc ac hes found. You c an als o go further and c hange the H T M L layout, add new features , or introduc e new kinds of objec ts for your us ers to edit. P erhaps you are employed by a loc al parks s ervic e to identify invas ive plant s pec ies and want a new kind of form input to des c ribe thos e. O r you're a mountain biker who wants to have a s lightly s pec ialized s oc ial mapping applic ation to doc ument the roc kines s , s teepnes s , or expos ure of c ertain trails . BA H T is extens ible for s uc h us es bec aus e it is built on the N ing P layground, whic h is a free online s ys tem that enables you to c lone, mix, and run fullblown s oc ial web apps like BA H T without worrying about a bunc h of pes ky details . T he N ing P layground handles us er ac c ount management, s ys tem adminis tration, hos ting, and bandwidth nightmares , not to mention the tedium of performanc e and s c alability is s ues . I f you don't know P H P, you c an s till do a lot with BA H T or any s oc ial applic ation running on N ing. I f you want to c opy BA H T to c reate M alibu H iking Trails , Bay A rea Roc k C limbs , Yos emite M ountaineering Routes , or Sonoma Bike Rides , jus t s elec t the applic ation and c hoos e C lone I t on the righthand s idebar to ins tantly c reate your own running vers ion of the applic ation, with an exac t c opy of the c ode behind the c opied applic ation, ready to be c us tomized. You jus t c hange the title to apply the app to the plac e, interes t, or ac tivity you want. N ow you're all s et to s tart adding your own relevant trails , roc ks , mountains , rides , or romantic s pots , and invite your friends and neighbors to do the s ame. I f you know P H P, then it gets even better. You c an go under the hood of the app by c lic king on "view s ourc e," and, with thos e P H P s kills , c hange the us er input forms , add or delete features , or make the app anything you want. BA H T c ombines the benefits of gadgets , data, and the real world experienc e of you and others to help you find and s hare the perfec t plac e. You c an c ompare your trips agains t your friends ' trips or blend different trips together to get a c ompos ite view of s ome new trip you've never thought of before. BA H T helps you return to your favorite plac es over and over and eas ily find new favorites . I t dis s olves boundaries between the profes s ional and the amateur by letting you c reate your own maps and your own mapping s ervic es . U ltimately, perhaps its mos t powerful role is that it helps you and your friends more eas ily s hare s omething valuable and important: this hugely c omplex and beautiful natural world we live in. I look forward to s eeing what kinds of new projec ts you invent bas ed on this s tarting point. Ans elm Hook Hack 35. Load Driving Directions into Your GPS From Google straight to your Global Positioning System receiver, thanks to GPSBabel. G P SBabel (http://www.gps babel.org) makes it pos s ible to c onvert driving direc tions from G oogle M aps into various formats us able by other s oftware and devic es . T his is pos s ible bec aus e G oogle enc odes the c oordinates of the entire route in the J avaSc ript that is s ent to the G oogle M aps c lient and us ed to generate the route that is put on the map. T he firs t s tep is , of c ours e, to get G oogle M aps to make s ome driving direc tions . We'll us e one of the examples given on the G oogle M aps home page. E nter "J FK to 3 5 0 5 th A ve, N ew York" and hit the Searc h button. A fter a s hort c alc ulation, a map like that in Figure 4 - 1 8 appears , with the route highlighted. Figure 4-18. Directions from JFK to Fifth Avenue N ow, we need to get the output into a predic table format. To do that, we firs t need a U RL that c ontains everything we need to rec reate our route. Fortunately, G oogle provides a tool to do jus t that! C lic k "L ink to this page." T he dis played map won't c hange, but the U RL in the addres s bar will c ontain your query and the parameters needed to return to this map at this zoom level. T he las t s tep is to modify that U RL to output the J avaSc ript that the G oogle M aps c lient us es internally. To do that, jus t add &output=js to the end of the U RL in your addres s bar and hit E nter. Your U RL will look like this (but all on one line): http://maps.google.com/maps?q=jfk+to+350+5th+ave,+new+york =0.103861,0.199934&hl=en&output=js T he obs ervant reader will note that the ins truc tions "J FK to 3 5 0 5 th A ve, N ew York" are inc luded in that U RL , with s pac es having been replac ed with plus s igns . With this information you c an s kip the s teps of looking up an addres s , c lic king on "L ink to this page," and c hanging the U RL to inc lude &output=js, and ins tead jus t enter the U RL of the J avaSc ript page s traight into your brows er. H ere is a link to the page c ontaining the points for direc tions from J FK to San Franc is c o I nternational A irport the hard way: http://maps.google.com/maps?q=jfk+to+sfo&spn =0.103861,0.199934&hl=en&output=js T he res ulting page will appear mos tly blank, but the H T M L s ourc e c ontains all the data we need to extrac t the c oordinates of the route. Save that page to your loc al hard dis k with the File Save A s menu option. I f you are us ing I nternet E xplorer, make s ure to s elec t Web P age, H T M L O nly from the "Save as type" drop- down. Saving as Web P age, C omplete will c aus e the file to be rewritten as non- c ompliant XH T M L , whic h G P SBabel will not be able to read. G ive the file a namewe'll c all ours nyc.htmand hit the Save button. N ow we have a file to feed to G P SBabel. What c an we do with it? O ne thing we c an do is to load this route to a handheld G P S unit. T hes e have limits on the number of points , s o we c an us e G P SBabel to reduc e the route G oogle M aps has c omputed for us to a s maller number of points . G P SBabel c omes with a G U I frontend, but the real power lies in the c ommand- line interfac e. For our example, we mus t us e the c ommand- line interfac e bec aus e the G U I does not s upport filters . Start a c ommand prompt; make s ure that G P SBabel is in your path, and s witc h to the direc tory where you s aved your map file as nyc.htm. C onnec t a s upported M agellan or G armin G P S rec eiver to com1: or a s erial or U SB port. I f you are running L inux, this is likely to be /dev/ttyS0 or /dev/ttyS1. I f you are us ing M ac O SX with a U SB adapter, it may be /dev/cu.us bs erial0. A s s uming you us ed com1:, type the following all on one line and hit E nter. O therwis e, replac e com1: with the name of your s erial or U SB port. For a M agellan G P S rec eiver: c:\> gpsbabel i google f nyc.htm x simplify,count=30 o mag For a G armin G P S rec eiver: c:\> gpsbabel i google f nyc.htm x simplify,count=30 o gar T hat's it! G P SBabel will read the driving direc tions produc ed by G oogle M aps , pic k the 3 0 mos t s alient points along the route, and upload the new route to your G P S rec eiver. N ow you c an follow along on this route as you walk, bic yc le, or drive! O ne other thing you might want to do is to s ave thos e points to a G P X file s o that you c an inc lude them on your own G oogle M ap, or upload them to a s ite like http://gps vis ualizer.net/. T he Topografix s ite at http://www.topografix.c om/gpx.as p des c ribes the G P X format: G P X (the G P S E xc hange format) is a light- weight XM L data format for the interc hange of G P S data (waypoints , routes , and trac ks ) between applic ations and Web s ervic es on the I nternet. T his c ommand will c onvert all of the points , without s implifying them, into a G P X file: c:\> gpsbabel i google f nyc.htm o gpx F nyc.gpx You c an als o reduc e the number of points from this G P X file and load them into your G P X. T he following c ommand will load the points from nyc.gpx, s elec t the 3 0 bes t fit points and upload them to a G armin G P S on com1:. c:\> gpsbabel i gpx f nyc.gpx x simplify,count=30 o garmin N aturally, this is analogous to the earlier c ommand we us ed to go direc tly from G oogle M aps output to the G P S rec eiver, exc ept that this time the input file is in G P X format. G P SBabel is s uc h a great tool that any G oogle M aps hac kers s hould c ons ider bec oming Babelheads ! 4.8.1. See Also T he G P SBabel page at http://www.gps babel.org/. A nother implementation c an be found at http://www.els ewhere.org/G M apToG P X/. Ron Parker Hack 36. Get Driving Directions for More Than Two Locations Going f rom here to there is okay, but going f rom here to there to another there to here is better. I n "L oad D riving D irec tions into Your G P S" [Hack #35] we s aw how to c ompute a route and load it into a G P S. T he hac k s howed how to direc tly c reate a U RL that will fetc h the G oogle M aps file that c ontains the route points . G P SBabel c an pars e the points out of a route file and you c an do whatever you would like with this information. T his s ugges ts a s c ript that takes a lis t of loc ations that G oogle c an unders tand and then generates driving direc tions between eac h point. I n addition to normal loc ations s uc h as "San Franc is c o, C A to D enver, C O ," G oogle M aps c an generate driving direc tions bas ed on latitude and longitude. T he res ults of s earc hing for direc tions from 38, -121 to 39.526421, -119.807539 are s hown in Figure 4 - 1 9 . Figure 4-19. Directions from latitude/longitude to latitude/longitude L at/long routes don't always work. T here are s ome plac es that are jus t a bit too far off of the beaten trac k for road- bas ed routing to be effec tive. I f you try 38, -121 to 39.731482, -119.53537, you get "We c ould not c alc ulate driving direc tions between 3 8 , - 1 2 1 and 3 9 .7 3 1 4 8 2 , - 1 1 9 .5 3 5 3 7 ." Sinc e 38, -121 worked in the firs t example, G oogle mus t have a problem with 39.731482, -119.53537. A glanc e at Figure 4 - 2 0 s hows that G oogle s hould be forgiven for this routing diffic ulty. A pparently the engineers didn't antic ipate helic opter- bas ed mountain- top expeditions . But lat/longbas ed direc tions work often enough to be interes ting. G reat, but why would you want to get driving direc tions for multiple points or for lat/longs ? L et's s ay you want to drive from San Franc is c o to D enver; you c an generate the route in Figure 4 - 2 1 with the query SFO to DEN, us ing an airport- to- airport s earc h. Why do you need more than one s et of direc tions ? You've got everything you need1 ,2 9 9 miles , and you are there. But it turns out you want to s top in M oab for s ome of that Slic kroc k ac tion. You c an't (yet) enter a reques t to G oogle for multipart driving direc tions , s uc h as SFO to Moab, UT to DEN, but with this hac k you c an get s omething s imilar. D ownload the P erl s c ript c alled takeme.pl from http://mappinghac ks .c om/projec ts /gmaps /takeme.html. T he s c ript c an ac c ept any c ombination of loc ations that G oogle c an unders tand and G P S waypoints s tored in G P X format. For example: Figure 4-20. You can't always get driving directions to a lat/long Figure 4-21. San Francisco and Denver are just a click apart $ perl takeme.pl SFO to wy_small.gpx to Moab, UT, to DEN T he program returns the c ombination of driving direc tions from eac h point to the next, as well as a s implified lis t of lat/long points . new route segment 37.61830, -122.38632 to 38.57320, -109.5 San Francisco Airport to Slick Rock Capitol ---------------------------------------------------------Head west 0.5| mi (734 meters) for 1 min ---------------------------------------------------------Take the I-380 W ramp to San Francisco (I-280)/San Bruno 0.1| mi (197 meters) for 12 secs You might want to s pec ify multiple loc ations , inc luding a detour to vis it friends , or you might want to tric k the routing algorithm into us ing a route that it c ons iders s ub- optimal. H ere's a real life example of tric king a routing algorithm: my dad and s tep- mom had jus t gotten a P rius with a navigation s ys temthey had had it les s than two weeks . M y dad, while quite bright, is not partic ularly tec hnic al. O ne day they were driving and playing with the navigation s ys tem. M y dad s aid, "D on't s et it to go to our des tination until you get to this turnit will take us a bad way from here." M y nontec hnic al dad had figured out the tool in under a week. Without knowing how, he was dynamic ally gaming the s ys tem's s hortes t- path algorithm by artific ially inc reas ing the weight of one s egment by adding the c os t of turning around to get bac k to that s egment. H e made that s egment les s attrac tive to the routing algorithm by ins erting another s egment in between hims elf and the dreaded s lower path. Spec ifying intermediate points (or des ired s ide trips ) adds loc al knowledge to the c os t c alc ulation us ed in the routing s ys tem. I n G oogle M aps terms , it s ure would be nic e to have "do not us e this s egment" c hec kboxes next to eac h s tep in the route, followed by "rec alc ulate my route without the c hec ked s egments ," but until that happens , you c an us e the takeme.pl tool! Hack 37. View Your GPS Tracklogs in Google Maps Plotting your GPS tracklogs on Google Maps allows others to see where you've been. Sharing trac klogs and waypoints from your G P S rec eiver bec ame a lot eas ier with the invention of the GPX format, whic h is an open XM L s tandard that enc odes your G P S wanderings to a file readable by many applic ations . T he bes t waypoints are pubs s o why not plot them on G oogle M aps , as in Figure 4 - 2 2 ? Figure 4-22. Some waypoints of London pubs, shown in Google Maps You c an go to http://www.tom- c arden.c o.uk/googlegpx/ and upload your own G P X format file. A ny waypoints appear as marker pins , and the s tart and end of trac ks will be marked with pins , as s hown in Figure 4 - 2 3 . Figure 4-23. A bit of a "derive" captured on the GPX viewer 4.10.1. Processing GPX Tracks to Reduce Complexity T here are s everal ways to proc es s a G P X file into s omething G oogle M aps will unders tand, and we demons trate two methods here. U s ing s erver- s ide proc es s ing, you upload the file from your brows er and proc es s it on your s erver (in this c as e us ing Ruby) and return a s c ript that dis plays the data. A lternatively, you c an put the G P X onto your own s erver and us e s ome J avaSc ript to open it, proc es s it on the c lient s ide, and pas s it to G oogle M aps . T he us ual c aveats for pas s ing information around in a brows er applythere are res tric tions on what s c ripts are allowed to ac c es s but old friends like the iframe element and new friends like XMLHttpRequest c an help us here. N o matter what method you us e to proc es s the G P X data, a G P X file will typic ally c ontain thous ands of points far too many for G oogle M aps to handle. Why is this ? When you dis play polylines in G oogle M aps , your vec tors are rendered into an image file on G oogle's s ervers . T he more points , the more time it takes to generate the images . E xc ept this is n't the whole s toryG oogle only does this if you aren't us ing I nternet E xplorer. I E has a built- in vec tor language c alled V M L , whic h renders the vec tors very quic kly in the brows er. Being fans of Firefox and M ozilla, for us it was n't good enough to rely on I E . T herefore we thought up a way to s elec tively c hoos e whic h points to dis play s o we didn't have too many, yet had enough to s how the route without s lowing G oogle down. A s eemingly obvious s olution would be to s imply drop every fifth point to reduc e the number of points by 2 0 % but the problem is that one of thos e ignored points might be the c ruc ial part of a turn or otherwis e c aus e dis tortions of the route. C ons ider another s c heme in whic h points are intelligently dropped on s traight lines but not on c omplex bends . I n this s c enario, s uc c es s ive points in a s traight line add little information to a route and may be forgotten. P oints that turn direc tion quic kly would then be kept as they are more important than thos e that only reinforc e a s traight line. T he key here is determining the amount of c hange in direc tion in order to pic k thos e points that s hould be dis played. You c ould s imply c hoos e an angle and c hoos e s uc c es s ive points bas ed on whether the path they mapped out deviated more than that angle, and it's a good c hoic e. T he problem, however, is that a G P X file may have 1 ,0 0 0 or 1 0 ,0 0 0 points within it, and thes e mus t be mapped down to a s uffic iently s mall number of points to ac tually plot in both c as es bec aus e G oogle M aps c an't plot too many. A nd s o we developed an adaptive algorithm that gets a good number of points to dis play. Before des c ribing the algorithm, we s hould be hones t and point out that this hac k does n't c hoos e points bas ed on angle, but s omething a little more c rude that is effec tively equivalent. I ns tead of angle, it is the differenc e vec tor between s uc c es s ive line s egments . What does that mean? P erhaps the diagram s hown in Figure 4 - 2 4 will help. Figure 4-24. One method for simplifying tracklogs for display C ons ider three trac kpoints rec orded by your G P S unit, where you travel from a to b to the bottom of c. Take the vec tor 2 between b and c, s o that it s tarts at a and you c an c ompare the vec tor 1 between a and b to it. N otic e the das hed line between them. T his das hed line is the differenc e between the vec tors . I t's like the angle between them but both quic ker to c ompute and s uffic ient, bec aus e we only need a rough gues s to figure out the c hange in direc tion. T here is one final fac t we mus t admit, whic h is that thes e vec tors are laid out in linear latitude and longitude. So when you're in L ondon one degree in latitude is a different abs olute length (s ay, in meters ) than one degree in longitude. You c ould equalize thes e but for our purpos es it does n't matter that muc h. Bac k to that adaptive algorithm: we c hoos e a s mall number as a thres hold for the length of that das hed line. T hen, for every s uc c es s ive pair of line s egments in a G P X trac k we s ee if the das hed line is bigger than our thres hold. I f it is bigger, then we inc lude the point; otherwis e, we forget about it. By going through the entire G P X file, we may dec ide to forget 1 0 0 points but have 4 ,0 0 0 left. T his is far too many for G oogle to plot. We therefore make our s mall number a bit bigger and try again, this time dropping more points . We repeat this c yc le until we have les s than 2 0 0 points and then us e thos e points to plot in our trac k. T his algorithm has been implemented with both a s erver- s ide Ruby bac kend and J avaSc ript c lient pars ing. 4.10.2. Converting GPX to JavaScript Calls Using Ruby H ere is the Ruby s c ript to plac e s erver s ide, if that's the way you want to plot your G P X files . We rec ommend us ing A pac he and mod_ruby to run it, and muc h doc umentation is available for both. #!/usr/bin/ruby # make sure we can speak CGI and XML: require 'cgi' require 'rexml/document' include REXML cgi = CGI.new print cgi.header("type"=>"text/html") stringfile = cgi['gpxfile'] doc = Document.new stringfile.read # Put the header of the HTML file: puts '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict/ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript"> function addPoints( ) {' count = 201 trackcount = 0 diff = 0.000000001 firstpt = '' lastpt = '' # For each track point in a segment doc.elements.each('gpx/trk/trkseg') do |e| count = 201 diff = 0.000000001 # So long as the total count of points to draw is less tha while count > 200 output = ' first = true oldlon = 0.0 oldlat = 0.0 parent.gpxtrack(new Array(' oldvx = 0.0 oldvy = 0.0 count = 0 # For each point in a segment e.elements.each('trkpt') do |pt| lat = pt.attributes['lat'].to_f lon = pt.attributes['lon'].to_f # Always add the first point if first output+= pt.attributes['lat'] + ',' + pt.attribute first = false count = 1 firstpt = 'parent.addpin(' + pt.attributes['lat'] pt.attributes['lon'] + ', "Start of track ' + tra else vx = oldlon - lon vy = oldlat - lat # If the point is bigger than our small value if ((oldvx - vx)*(oldvx - vx))+((oldvy - vy)*(oldv # Then add it count += 1 output += ',' + pt.attributes['lat'] + ',' + pt. oldvx = vx oldvy = vy oldlat = lat oldlon = lon end end end # Make our small distance value 5 times bigger and try diff *= 5 end if count > 1 puts output + '));' puts firstpt trackcount += 1 end end # Now, for each waypoint plot it with the description: doc.elements.each('gpx/wpt') do |e| lat = e.attributes['lat'] lon = e.attributes['lon'] str = '' e.elements.each('name') do |wpt| str += wpt.get_text.value + '<br>' end e.elements.each('cmt') do |wpt| str += wpt.get_text.value + '<br>' end e.elements.each('desc') do |wpt| str += wpt.get_text.value end puts ' parent.addpin(' + lat + ',' + lon + ',"' + end # put the end of the HTML puts ' }' puts ' </script> </head> <body onload="addPoints( );"> <p>uploaded successfully as far as we can tell</p> </body> </html>' O nc e that s c ript is in a s uitable loc ation, you need an H T M L page with a little J avaSc ript to hook it up to. 4.10.3. Supporting HTML and JavaScript for GPX Viewing We s tart with the mos t bas ic G oogle M aps ins tanc e, modified to s upport V M L and I nternet E xplorer. <!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" xmlns:v ="urn:schemas-microsoft-com:vml"> <head> <title>Google Maps GPX Viewer</title> <style type="text/css"> v\:* { behavior:url(#default#VML); } </style> <script src="http://maps.google.com/maps?file=api&v= =YOUR_KEY_GOES_HERE" type="text/javascript"></scr <script type="text/javascript"> //<![CDATA[ var map; function addMap( ) { map = new GMap(document.getElementById("map")); map.addControl(new GLargeMapControl( )); map.addControl(new GMapTypeControl ( )); map.centerAndZoom(new GPoint(0.0, 0.0), 16); } //]]> </script> </head> <body onLoad="onMap( );"> <div id="map" style="width: 740px; height: 500px; m </div> </body> </html> T he Ruby c ode des c ribed above expec ts to rec eive a G P X file from an H T M L multipart form. T hat form s hould look s omething like this : <form name="gpxupload" action="ruby/upload-gpx.rbx" enctype="multipart/form-data" method="POST" target="se <label for="gpxfile">Choose a GPX file here:</label> <input type="file" name="gpxfile" /> <input type="submit" value="submit" /> </form> You c an s ee that this form is being s ubmitted to a frame c alled sekrit. T hat's pretty s traightforward to add to the H T M L too: <iframe width="740" height="200" border="1" name="sekrit" id="sekrit"></iframe> A nd onc e thos e items are in your H T M L file, all that remains is to add the following J avaSc ript after the addMap( ) func tion. // whenever a waypoint element is encountered (used by Rub function addpin(lat,lon,text) { if (lat && lon) { var p = new GPoint(lon,lat); var marker = new GMarker(p); if (text) { // supplied text is wrapped in a <p> tag but can con var html = "<p>" + text + "</p>"; GEvent.addListener(marker, "click", function( ) { marker.openInfoWindowHtml(html); }); } map.addOverlay(marker); map.centerAndZoom(p,4); } } // whenever a trkseg element is encountered (only used by function gpxtrack(track) { if (track) { if (track.length >= 4) { var points = []; for (i = 0; i < track.length; i+=2) { points[points.length] = new GPoint(track[i+1],track[ } map.addOverlay(new GPolyline(points)); map.centerAndZoom(points[0],4); } } } 4.10.4. Client-Side Implementation I ns tead of pars ing the G P X on the s erver s ide, and returning s ome J avaSc ript to an iframe, whic h c alls func tions in its parent, we c an ac tually us e J avaSc ript to do the whole jobfetc h the G P X file and pars e it, too. T he one problem with this approac h is that J avaSc ript is only allowed to ac c es s files hos ted on the s ame domain as the web page it runs in. To get around this , we implemented a P H P proxy that bounc es remote G P X files off our s erver to let J avaSc ript have it's way with them. To s ee this in ac tion, add the following to the J avaSc ript after the gpxtrack( ) func tion above. // this is called on submit from an html form function fetchfile( ) { // disable the form (there's probably a nicer way to do document.getElementById("submitbutton").disabled = true; // find the URL from the form (you might want to check t URL) var url = document.getElementById('gpxfile').value; // create an XMLHttpRequest object, using Google's utili // abstracts away the browser differences var request = GXmlHttp.create( ); // fetch the URL via a proxy script on your server // (otherwise you can only fetch URLs from the same doma // as the javascript is server from) request.open("GET", 'proxy.php?url='+URLencode(url), tru // tell the request what to do if the file is successful request.onreadystatechange = function( ) { if (request.readyState == 4) { var xmlDoc = GXml.parse(request.responseText); if (xmlDoc) { var lastPoint; // for centring the map on the last var trks = xmlDoc.documentElement.getElementsByTag for (var i = 0; i < trks.length; i++) { var trksegs = trks[i].getElementsByTagName("trks for (var j = 0; j < trksegs.length; j++) { var var var var trkpts = trksegs[j].getElementsByTagName( points; // array to contain GPoints count = 201; diff = 0.000000001; while (count > 200) { // empty the points array points = []; // we always add the first point var first = true; // characteristics of the last GPoint added var var var var oldlon = 0.0; oldlat = 0.0; oldvx = 0.0; oldvy = 0.0; var lat; var lon; for (var k = 0; k < trkpts.length; k++) { lat = parseFloat(trkpts[k].getAttribute(" lon = parseFloat(trkpts[k].getAttribute(" if (first == true) { points[points.length] = new GPoint( lon first = false; count = 1; } else { vx = oldlon - lon; vy = oldlat - lat; dx = oldvx - vx; dy = oldvy - vy; if ( (dx*dx)+(dy*dy) > diff ) { count += 1; points[points.length] = new GPoint( l oldvx = vx; oldvy = vy; oldlat = lat; oldlon = lon; } } } // for // if we have >200 pts, we'll try again usi diff *= 5.0 } // while map.addOverlay(new GPolyline(points)); lastPoint = points[0]; } // for j (each trkseg) } // for i (each trk) var wpts = xmlDoc.documentElement.getElementsByTa for (var i = 0; i < wpts.length; i++) { var text = "Waypoint info:<br/>" for (var wpt = wpts[i].firstChild; wpt; wpt = w // different browsers handle xml attributes d // this should present waypoint attributes as if (wpt.text) { text += wpt.nodeName + ": " + wpt.text + "< } else if (wpt.nodeType != 3) { text += wpt.nodeName + ": " + wpt.firstChil } } addpin( parseFloat(wpts[i].getAttribute("lat")) parseFloat(wpts[i].getAttribute("lon")) text ); } map.centerAndZoom(lastPoint,4); } else { alert("xmldoc seems to be null: " + xmlDoc); } } } request.send(null); document.getElementById("submitbutton").disabled = fals } // this is ugly, and possibly there's a better way to do // it with some "proper" javascript. I found it on the web function URLencode(sStr) { return escape(sStr).replace(/\+/g, '%2B') .replace(/\"/g,'%22').replace(/\'/g, '%27'); } You c an remove the iframe s inc e we're us ing XMLHttpRequest this time, and c hange the H T M L form to the following: <form name="gpxform" onsubmit="fetchfile( ); return false; <label for="gpxfile">Type the (valid) URL of a (valid) GPX file here:</label> <input type="text" name="gpxfile" id="gpxfile" value="h <input type="submit" value="submit" id="submitbutton" n </form> T he P H P proxy we us ed in proxy.php looked like this : <?php // note that this will not follow redirects // you really should validate the URL too readfile($_GET['url']); ?> A nd that's it! 4.10.5. Other Possibilities T here are a lot more things you c an do with this . A few of the mos t obvious inc lude: Fix the waypoint metadata J avaSc ript pars er to work in Safari. I mplement the waypoint metadata pars ing in Ruby. I n Ruby, s ave the res ulting file on your s erver, s o the maps are linkable. With J avaSc ript or Ruby, ac c ept a U RL in a query s tring, and then fetc h it via H T T P s o that the maps are linkable. For the Ruby vers ion, s ubmit the file us ing XMLHttpRequest and return a bit of J avaSc ript to eval, ins tead of futzing around with iframe. 4.10.6. See Also H ow to us e G oogle M aps ' XSLT voodoo to proc es s the G P X file: http://c s emjmc l.c s e.bris .ac .uk/blog/2 0 0 5 /0 7 /2 6 /1 1 2 2 4 1 4 8 8 2 4 0 6 H ow to modify the pin ic on/c ontents : http://maps .kylemulka.c om/gpxviewer.php A s tandalone V B vers ion: http://www.planets ourc ec ode.c om/vb/s c ripts /ShowC ode.as txtC odeI d=6 1 8 5 7 &lngWI d=1 Tom Carden & Steve Coas t Hack 38. Map Your Wardriving Expeditions Found Wi-Fi nearby? Put it on a map! M y interes t in Wi- Fi is what got me s tarted with G I S. I had been following the early 8 0 2 .1 1 devic es and was ps yc hed to read about new modern and c heaply made wireles s equipment in the news and then ac tually s ee them on the s helves of various s tores . Bus ines s es of all s izes and millions of hous eholds s tarted buying and ins talling thes e devic es all over the plac e. I wondered where thes e things were being ins talled, and jus t how many were around. N ot long afterwards , I learned that there were people who would go out in their c ars with G P Ss and laptops , rec ording the loc ations of thes e wireles s s ignals . T hes e wardrivers , I learned, weren't breaking into thes e networks , but were c omparing findings s uc h as the funny names for s ome of the networks and the loc ations of the inc reas ingly popular loc al wireles s hots pots . I figured I had to try this out, and after about five minutes , I was hooked. I was s till c urious about what my findings looked like. I had to figure out not only how to plot them, but als o how to plot them on a map and on the Web. A fter a while, and with another c urious pers on, E ric Blevins , we put together http://WiFiM aps .c om. WiFiM aps .c om is a web- bas ed geographic map of where Wi- Fi has been ins talled. T he loc ations are updated by the us ers , who upload their wardriving s c ans of various areas . I n turn, the s ite us es T I G E R, M aps erver, and a hos t of other open s ourc e and otherwis e free tools to plot s treet- level maps of Wi- Fi ins tallations for thos e who wonder. You too c an do the s ame thingand not jus t the wondering part, but als o the where part. We'll do s ome wardriving and us e a P H P s c ript to pars e the data found, and then plot the Wi- Fi s pots on G oogle M aps . 4.11.1. The Hack For c ollec ting Wi- Fi data, I generally us e N ets tumbler, available from http://www.nets tumbler.c om, whic h is popular among wardrivers . For free 'nix operating s ys tems , Kis met (http://www.kis metwireles s .net/) is the tool of c hoic e, while on M ac O S X, there's both M ac Stumbler (http://www.mac s tumbler.c om/) and Kis M A C (http://kis mac .binaervarianz.de). I n this hac k, we'll be exporting data from thes e programs in the WiScan log format, whic h all four programs s hould happily generate. WiSc an is a tab- delimited text file with its own c harac teris tic s , and perhaps there are other wardriving pac kages that als o export to this format. So, go out for a wardrive! I f you are in a dens ely populated area, even a 2 0 - minute wardrive c an produc e thous ands of points . Be s afe! D on't be tempted to ac c es s any of the networks you find while wardriving unles s you have permis s ion from the owner, or you are at a public hots pot. A ls o, pay attention to the road while c ollec ting datanot your laptop. 4.11.2. The Code We have four c omponents to mapping the data you've jus t c ollec ted: the H T M L form, the plain and s imple G oogle M aps c ode, the wac ky P H P pars er bits , and s ome interes ting loc al data to plot. You'll need ac c es s to and permis s ion for a web s erver with P H P, and to be familiar enough with thos e to get the c ode s ituated. L et's s tart with the H T M L upload form, whic h will allow us to s end our WiSc an log to the s erver to be mapped. C all this file index.html: <html> <head> <title>Wi-Fi Data on Google Maps</title> </head> <body> <form enctype="multipart/form-data" action="post.php" method="post"> Send this file: <input name="userfile" type="file"> <input type="submit" value="Send File"> </form> </body> </html> T his is quite s imple, and I may have even not inc luded s ome extra func tionality. T his s eemed to work okay, however. T hen we c an go to the G oogle M aps default J avaSc ript s etup des c ribed in C hapter 2 . I dec ided to add the large zoom c ontrol and the map type c ontrol, s o you c an s witc h between s treet maps and s atellite imagery. Map.addControl(new GLargeMapControl()); Map.addControl(new GMapTypeControl()); N ext is the magic al P H P c ode. We'll keep s ome s anity here by paring things down by M A C addres s and doing an average on the various points . T his will give us a ps eudoc enter for plac ing our markers . We als o us e a s patial average to generate the s tarting map. Where you would normally put the following line in your J avaSc ript: map.centerAndZoom(new GPoint(-122.141944, 37.441944), 4); … replac e it ins tead with the P H P c ode s hown here: <?php // PHP WiScan parser // Strips-off header and entries with no lat/lng function stripulate($line) { if ( ereg("^#", $line) ) { return 0; } if ( ereg("^[NS] 0.0000", $line) ) { retur return 1; } // self parsing accumulator function splitotron($line) { global $MAC; global $center; // Change N/S to +/$line = ereg_replace("^N ", "", $line); $line = ereg_replace("^S ", "-", $line); // Strip-off parenthesis $line = ereg_replace("[ )\t(]+", "\t", $li // Change E/W to +/$line = ereg_replace("^([0-9.-]+)\tE\t", " $line = ereg_replace("^([0-9.-]+)\tW\t", " // Split by tabs $cols = preg_split("/\t/", $line); // Add lats with same MAC $MAC[$cols[4]]["lat"] += $cols[0]; // Add longs with same MAC $MAC[$cols[4]]["lng"] += $cols[1]; // We'll just make them equal here $MAC[$cols[4]]["ssid"] = $cols[2]; // Accumulate how many per MAC $MAC[$cols[4]]["cnt"] ++; // Add 'em all together for the center $center["lat"] += $cols[0]; $center["lng"] += $cols[1]; // Accumulate for the center $center["cnt"] ++; } // Deal with the upload $name = $_FILES['userfile']['name']; if (copy($_FILES['userfile']['tmp_name'], "tmp/$name") $uploadfile = file("tmp/$name"); // Apply Stripulate function to the uploaded data $uploadfile = array_filter($uploadfile, "stripulate // Apply Splitotron to the uploaded data $uploadfile = array_map("splitotron", $uploadfile); // Generate centerpoint for map $centerlat = $center["lat"] / $center["cnt"]; $centerlng = $center["lng"] / $center["cnt"]; echo "map.centerAndZoom(new GPoint({$centerlng},{$c // Generate points and markers foreach ($MAC as $mac => $unique) { $divlat = $unique["lat"] / $unique["cnt"]; $divlng = $unique["lng"] / $unique["cnt"]; echo "var point = new GPoint({$divlng}, {$d echo "var marker = new GMarker(point); \nmap.addOverlay(marker);"; } } ?> O nc e you have thes e s c ripts in plac e, you will need to c reate a temporary direc tory with appropriate write permis s ions . You s hould then be able to c all up your P H P s c ript, upload a WiSc an file, and have the res ults dis played on a G oogle M ap, whic h might look like Figure 4 - 2 5 . Figure 4-25. Some results from a wardriving expedition 4.11.3. Hacking the Hack I f you're us ing Kis met, you c an have it generate logfiles in its c us tom XM L format and us e a c ombination of J avaSc ript and XSLT to trans late the log entries direc tly into H T M L for the info window, without the need for P H P. You c an s ee an example of this online at http://mappinghac ks .c om/projec ts /gmaps /kis met.html. Sinc e you c an view s ourc e on that page to s ee its inner workings , we'll jus t c over the juic y bits . H ere's a s omewhat s implified s nippet of a Kis met XM L log: <wireless-network wep="false" first-time="Sat Nov 27 16:35:00 2004" last-time="Sat Nov 27 18:21:56 2004"> <SSID>linksys</SSID> <BSSID>00:11:22:33:44:55</BSSID> <channel>6</channel> <encryption>None</encryption> <gps-info unit="metric"> <min-lat>6.2069</min-lat> <min-lon>-75.5629</min-lon> <max-lat>6.2078</max-lat> <max-lon>-75.5618</max-lon> </gps-info> </wireless-network> E ac h wireless-network element in the log c ontains details about eac h network s een, inc luding a gps-info element that des c ribes the area in whic h the network was detec ted. We c an us e an XSLT s tyles heet to turn eac h of thes e entries into H T M L : <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org <xsl:template match="wireless-network"> <div style="width: 200px; max-height: 75px;"> <div style="font-size: 125%; font-weight: bold; <xsl:value-of select="SSID" /> </div> <div style="font-color: #ccc"> <div><xsl:value-of select="BSSID" /></div> <div>Channel <xsl:value-of select="channel" <div>Encryption: <xsl:value-of select="encr </div> </div> </xsl:template> </xsl:stylesheet> T he s tyles heet identifies a log entry by looking elements in the log c alled wireless-network, and then outputs an H T M L div element, us ing the values of the SSID, BSSID, channel, and encryption elements from ins ide eac h log entry. T he H T M L that would res ult from the XSLT trans formation of the example log entry us ing this s tyles heet would look s omething like this : <div style="width: 200px; max-height: 75px;"> <div style="font-size: 125%; font-weight: bold;">linksys <div style="font-color: #ccc"> <div>00:11:22:33:44:55</div> <div>Channel 6</div> <div>Encryption: None</div> </div> </div> O n our map page, we fetc h the Kis met log us ing GXmlHttp and feed it to a func tion c alled mapFeed( ). T his func tion us es the J avaSc ript D O M A P I to find all the wireless-network entries and then looks ins ide eac h one to find the minimum latitude and longitude of the network's c overage area. For eac h network node with geographic information, a GPoint objec t is c reated with its c oordinates , whic h is pas s ed to another func tion, addMarker( ), to c reate a marker on the map for that node. function mapFeed (xml) { var items = xml.documentElement .getElementsByTagName("wireless-network map.clearOverlays( ); for (var i = 0; i < items.length; i++) { var gpsinfo = items[i].getElementsByTagName("gps-i if (gpsinfo.length == 0) continue; var lon = gpsinfo[0].getElementsByTagName("min-lon .childNodes[0].nodeValue; var lat = gpsinfo[0].getElementsByTagName("min-lat .childNodes[0].nodeValue; var x = parseFloat(lon); var y = parseFloat(lat); if (x && x != 90 && y && y != 180) { var point = new GPoint(x, y); var marker = addMarker(point, items[i]); map.addOverlay(marker); } } } T he addMarker( ) func tion is almos t painfully s imple: function addMarker (point, xml) { var marker = new GMarker(point); GEvent.addListener(marker, "click", function ( ) { marker.openInfoWindowXslt( xml, "kismet2marker.xsl }); return marker; } T he s upplied point is us ed to c reate a new GMarker, and then a c lic k event is added to that marker, and the marker is returned. L ater, when a us er c lic ks on the marker, the event handler c alls marker.openInfoWindowXslt( ), whic h fetc hes our XSLT s tyles heet from the s erver, applies it to the D O M element c ontaining the log entry for that wireles s node, and then takes the res ulting H T M L and s tic ks it into a new info window over the marker. T he res ult is quite elegant, bec aus e ins tead of having to as s emble the H T M L layout of the info window in J avaSc ript (whic h c an get quite mes s y), we c an us e an external XSLT s tyles heet to c leanly s eparate our logic and our pres entation. I f we want to add other data from the logfiles to the info window, we c an do s o by updating the XSLT without ever having to touc h the J avaSc ript again. T he J avaSc ript in this example c ould s tand s ome improvement. For example, we c ould fetc h the maximum lat/long for eac h node and average them with the minimum lat/long for a more ac c urate pos ition. We c ould als o dis play a different marker bas ed on the c ontents of the encryption field, s o that we c ould s ee, at a glanc e, whic h networks were open and whic h were c los ed. We c ould add s ome logic to trac k the maximum and minimum c oordinates of our logfile and s et the map c enter and zoom level appropriately [Hack #58]. Finally, as wardriving logs tend to pic k up lots of points quic kly, we might want to look into us ing "Show L ots of StuffQ uic kly" [Hack #59] as a means of s peeding up the map dis play. Drew from Zhrodague Hack 39. Track Your Every Move with Google Earth Ever wanted to have your own spy in the sky watching your every move, tracking you wherever you go? G oogle E arth, formerly known as Keyhole, is the des ktop- bas ed big brother to G oogle M aps , offering 3 D overviews of major c ities , mountains , and other terrain, as well as loc al bus ines s es and information, driving direc tions , and maps . I ts features are far too numerous to mention here, but you c an find out more and download a free vers ion at http://earth.google.c om/. Tragic ally, although it's bas ed on the O penG L s tandard, G oogle E arth is , as of this writing, s upported on Windows only. O ne of G oogle E arth's mos t interes ting features is the ability to bookmark a partic ular view of a plac e or plac es , and then export that view to other G oogle E arth us ers via the Keyhole M arkup L anguage (KM L ) format. T he XM L bas ed KM L format is good for adding s tatic c ontent to G oogle E arth (e.g., bridges , monuments , or buildings ), but how do we map things that move? Fortunately, G oogle E arth has s omething c alled a Network Link, whic h we'll look at a bit more in a s ec ond. T he ups hot is that we c an us e it to read in a .kml file that holds our pos ition every few s ec onds . We als o have a G P S s ys tem that updates our pos ition every few s ec onds . T he hac k we're going to attempt is to c ons tantly get the values from the G P S s ys tem into the .kml file. T his is s urpris ingly eas y to do on L inux, but we're running G oogle E arth on Windows , where things are s lightly more, er, entertaining. Firs t, the tools we're going to us e: G oogle E arth (and its N etwork L ink feature), Firefox, one G armin G P S rec eiver with a s erial c able, a c opy of G arnix for M S- D O S, two .bat files , ping, pos s ibly s ome s tic ky tape, s tring, and a bit of luc k. We'll talk about the other bits of s oftware, like G P SBabel, but even if you don't have all this s tuffi.e., you have a different brand of G P S rec eiverthere s hould s till be enough here to get you hac king around any problems . 4.12.1. Peering into the Keyhole L et's have a c los er look at the .kml file we're going to be c reating. Start up G oogle E arth, zoom into s omeplac e near home, and pres s C trl- N to add a new P lac emark. C all it s omething us eful like "M e" and c lic k O K. T he P lac emark will appear on the map, as well as in the P lac es s ec tion over on the left. Rightc lic k on the P lac emark and s elec t Save A s . Save it as me.kml (not .kmz) into s omewhere really eas y to get to, as we'll be writing D O S .bat files in a while, s o s omewhere c los e to the root drive with a s hort name is preferable. I made a folder c alled c:\geo\ and us ed that. I f you open your .kml file in N otepad, or any other text editor, you'll s omething along the lines of the following: <?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://earth.google.com/kml/2.0"> <Placemark> <name>Me</name> <LookAt> <longitude>-2.189175686596352</longitude> <latitude>53.0420501867381</latitude> <range>769.3231615683798</range> <tilt>-8.237346562804484e-011</tilt> <heading>-0.002462111503350637</heading> </LookAt> <styleUrl>root://styleMaps#default+nicon=0x307+hicon=0x3 <Point> <coordinates>-2.19004490258348,53.04134242507396,0</co </Point> </Placemark> </kml> T he values we're primarily c onc erned with are the <longitude>, <latitude> and <coordinates> elements . T hes e s hould matc h eac h other, as the plac e we are looking at and the point we're at s hould be the s ame. I normally s et the tilt and heading values to be 0 when I generate .kml files with c ode. Bac k to G oogle E arth, right- c lic k the P lac emark, and then delete itbac k to s quare one. We're doing this bec aus e it's jus t no roc kn- roll fun as a "normal" P lac emark: we'll make ours far more dynamic , by loading it in as a N etwork L ink! From the top menu bar, pic k A dd N etwork L ink. O nc e more, pic k a us eful name, e.g., "M e", and then hit the Brows e button and loc ate the me.kml file we jus t s aved. A t the moment, it's s till ac ting as a normal P lac emark, s o c hange the time- bas ed Refres h When option to P eriodic ally and make the period every 1 0 s ec onds . Finally (for fun) tic k the Fly to V iew on Refres h c hec kbox, then pres s O K. What do we have? G oogle E arth loading in the s ame KM L file over and over again, every 1 0 s ec onds , going to the s ame loc ation over and over again. T he next s tep is fairly obvious : we want to update the values in that .kml file every few s ec onds from s ome gnarly c ode we've thrown together. I f you're s o inc lined and outfitted, try firing up your favorite development environment and having it s pit random values into the KM L fileand then s it bac k and watc h as G oogle E arth tries to fly all over the plac e! 4.12.2. Back Down to Earth O f c ours e, we want your loc ation, not s ome random one. We'll be us ing your G armin G P S rec eiver to get your pos ition and the c able you probably felt you were paying far too muc h money for (unles s it c ame with your rec eiver or you built it yours elf, in whic h c as e, good for you) to c onnec t it to your P C . We als o need s ome s oftware that'll fetc h your longitude and latitude from the G P S devic e. You would think that would be a s imple tas k, but unles s my s earc h engine fu is failing me badly, I c ouldn't find anything that jus t got our loc ation from the devic e. L ots of applic ations for downloading waypoints and trac klogs , loads of neat s c ripts for L inux, but Windows programs for lat and long in an eas y to us e format? N o s uc h luc k. T he c los es t I c ould find was the M S- D O S binary vers ion of G arnix from http://homepage.ntlworld.c om/anton.helm/garnix.html. D ownload it and unzip it into your c:\geo\ folder, or where ever you dec ided to put your .kml file. You'll need to edit the GARNI X.CFG file in N otepad to read as follows : port: deg_min_sec; datum: "com4"; "WGS84"; ;grid: "UTM"; ;zone: "33"; ; ;See datum.cfg for datum names ;See grid.cfg for grid and zone names Replac e com4 with whatever c om port your G P S devic e c onnec ts onus ually s omewhere from com1 through com4and make s ure the s emic olon is removed from the front of the deg_min_sec line. I f you don't know what c om port your G P S us es , and you own G oogle E arth P lus , c onnec t your G P S, turn it on and then pic k Tools G P S D evic e, whic h will probably figure out whic h port it's c onnec ted on. A lternatively, you c an experiment with E as yG P S from http://www.eas ygps .c om. With your G P S s ys tem c onnec ted to your P C , go outs ide until you get a G P S reading loc ked in and have your lat/long pos ition. I f you c an't go outs ide, try hanging the G P S unit out the window, maybe attac h it to a s tic k or polethis is where the s tic ky tape and s tring c omes in! (A nd you thought we were kidding about that? ) I f none of thos e options are pos s ible, then there's a s lightly les s exc iting one: mos t G P S units have a demo mode, hidden s omewhere in the s ettings menu. I f you turn that on, it'll s tart making up pos itions for you. O pen up a c ommand window by c lic king Start Run and then type in cmd, and c lic k O K. T hen c hange to the c orrec t direc tory and tes t out G arnix as follows : c:\>; cd c:\geo c:\geo\> garnix -x With luc k you'll get a res pons e along the lines of: Device ID: Device Time: eTrex Software Version 2.14 17:06:31-2005/07/23 Current Position (WGS84): Latitude 53deg 6min 2.43sec Longitude -2deg 11min 55.59sec D ifferent devic es may give s lightly different res ults . We'll have to deal with this later on, but it only takes a little tinkering. I f you c an't get c onnec ted with G arnix, all is not los t. A s long as your G P S s ys tem is c ofnnec ted on c om ports 1 to 4 you c an s e G 7 To(W) from http://www.gps information.org/ronh/#g7 to. T he c ommand line you'll need to us e is : c:\geo\> G7tow n i G45P n is the s erial port your unit is attac hed to. T he output is different from G arnix, s o you'll need to hac k the J avaSc ript s hown later. A lternatively, you c an try us ing G P SBabel, as des c ribed later on in the hac k. N ow we have the information, but not in a us eful format. T here are a few options ; for example, you c ould download the s ourc e c ode and hac k it around to output the numbers in dec imal format, or even take it a s tep further and write out the whole .kml file. (P leas e email us if you do this ! ) You c ould probably throw together s ome regular expres s ions in P erl to perform mys terious voodoo c oding to automagic ally c onvert the output or, as we're going to do now, turn to Firefox and c ode up a quic k s olution in J avaSc ript. Before we do that, bac k to the c ommand line onc e more, to do this : c:\geo\> garnix x > results.txt T his writes the information into a text file, whic h we c an us e for tes ting. You c an return indoors now or pull the G P S bac k through the window and s witc h it off; we'll not be needing it for a while. 4.12.3. The Code N ext, we need to turn the output from G arnix into s omething G oogle E arth c an us e. To keep things s imple(is h) we're going to us e J avaSc ript and open the page in Firefox to run it. I n the s ame folder as everything els e, c reate an index.html file and c opy the c ode below into it. A lternatively, you c an download the c ode from http://googlemaps hac ks .c om/projec ts /gmaps /trac king/. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional/ <html> <head> <meta http-equiv="refresh" content="10"> <title>geo convert</title> <script> var readfile = "c:\\geo\\results.txt"; var writefile = "c:\\geo\\me.kml"; var fAlt = "750"; T he above c ode s ets up the H T M L page to reload every 1 0 s ec onds and defines where we want to read and write the files to. T he fAlt variable is the altitude we want the c amera in G oogle E arth to hover above the s urfac e. D ifferent s ituations warrant different values , s o it's bes t to play around to s ee what s uits you bes t. T he next two func tions deal with reading and writing files to the loc al drive. A c ertain amount of jumping through s ec urity hoops is needed to get Firefox to allow J avaSc ript to interac t with the files ys tem. A t the end of the fnRead func tion we'll c all the fnWrangleText func tion, whic h does the hard work. When you run this page, jus t load it into Firefox as a file us ing File O pen File. You're not trying to load this as a web pageand indeed the file read/write will fail if you do. N o web s erver is needed for this hac k! function fnWrite(sText) { try { netscape.security.PrivilegeManager. enablePrivilege("UniversalXPConnect"); } catch (e) { alert("Permission to save file was denied."); } var file = Components.classes["@mozilla.org/file/local .createInstance(Components.interfaces file.initWithPath( writefile ); if ( file.exists( ) == false ) file.create( Components.interfaces.nsIFile.NORMAL_F var outputStream = Components.classes["@mozilla.org/network/file-outpu .createInstance( Components.interfaces.nsIFi outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 ); var result = outputStream.write( sText, sText.length ); outputStream.close( ); } function fnRead( ) { try { netscape.security.PrivilegeManager. enablePrivilege("UniversalXPConnect"); } catch (e) { alert("Permission to read file was denied."); } var file = Components.classes["@mozilla.org/file/loca .createInstance(Components.interface file.initWithPath( readfile ); if ( file.exists( ) == false ) alert("File does not exist"); var is = Components.classes["@mozilla.org/network/fil .createInstance( Components.interface nsIFileInputStream ); is.init( file,0x01, 00004, null); var sis = Components.classes["@mozilla.org/scriptableinputs .createInstance( Components.interfaces. nsIScriptableInputStream ); sis.init( is ); var readText = sis.read( sis.available( ) ); fnWrangleText(readText); } T he next part is where it gets interes ting. Firs t of all, we'll c reate pointers to the two textboxes that'll we'll us e to s ee what's going on. function fnWrangleText(sText) { var sInput = document.getElementById('txtInput'); var sOutput = document.getElementById('txtOutput'); We want to get to the values right at the end of the text. T here are all s orts of ways to do this , but I happen to find this the eas ies t to follow. We're going to remove all the line breaks and extra s pac es to make the text jus t one long line. N ext, we turn the text into an array, us ing the s pac es that are left as the divider, s o that eac h word bec omes its own element in the array. sText = sText.replace(/\s+/g, " "); sInput.value = sText; var aText = sText.split(" "); T he information we want is held in the las t eight words , or elements , as they are now; therefore, we c an c ount bac k from the end to get at the data we want. Sometimes , there will be a s pac e at the very end, whic h we have to take into ac c ount. I f we c ount bac k from the end, we s ee that "5 3 deg" (us ing the example output from above) is the 7 th word from the end, planning for the extra s pac e we c ount 8 bac k to get at it. For the latitude we need the 8 th, 7 th, and 6 th words from the end, then the 4 th, 3 rd, and 2 nd for the longitude. T he divis ion of minutes by 6 0 and s ec onds by 3 ,6 0 0 allows us to c ombine all three values into dec imal degrees . var fLatDeg = parseFloat(aText[aText.length-8]); var fLatMin = parseFloat(aText[aText.length-7])/60; var fLatSec = parseFloat(aText[aText.length-6])/3600; var fLat = Math.abs(fLatDeg) + fLatMin + fLatSec; if (fLatDeg < 0) fLat *= -1; var fLonDeg = parseFloat(aText[aText.length-4]); var fLonMin = parseFloat(aText[aText.length-3])/60; var fLonSec = parseFloat(aText[aText.length-2])/3600; var fLon = Math.abs(fLonDeg) + fLonMin + fLonSec; if (fLonDeg < 0) fLon *= -1; O ne las t c hec k s hown below makes s ure we have a valid number for the latitude and longitude. I t's pos s ible that your output from G arnix is s lightly different from that s hown above, s o you may need to c hange the values needed to c ount bac k from the end. Sometimes you may als o get a c las h when you attempt to read the file jus t as G arnix is writing it, whic h will jus t c aus e us to s kip an update us ing the c ode below. if (isNaN(fLon) || isNaN(fLat)) { sOutput.value = fLatDeg + ' ' + fLatMin + ' ' + fLatSe + fLonDeg + ' ' + fLonMin + ' ' + fLonSec; return; } Finally the important bit: we c ons truc t the c ontents for our .kml file, putting the new values into it, then we s end it to the fnWrite( ) func tion to s ave it bac k out. sOutput.value = '<?xml version="1.0" encoding="UTF-8"? sOutput.value = sOutput.value + '<kml xmlns="http://ea sOutput.value = sOutput.value + '<Placemark>\n'; sOutput.value = sOutput.value + ' <name>Me</name>\n' sOutput.value = sOutput.value + ' <LookAt>\n'; sOutput.value = sOutput.value + ' <longitude>' + fL sOutput.value = sOutput.value + ' <latitude>' + fLa sOutput.value = sOutput.value + ' <range>' + fAlt sOutput.value = sOutput.value + ' <tilt>0</tilt>\n sOutput.value = sOutput.value + ' <heading>0</head sOutput.value = sOutput.value + ' </LookAt>\n'; sOutput.value = sOutput.value + ' <styleUrl>root://styleMaps#default+nicon=0x307+ 0x317</styleUrl>\n'; sOutput.value = sOutput.value + ' <Point>\n'; sOutput.value = sOutput.value + ' <coordinates>' + fLon + ',' + fLat + ',0</coord sOutput.value = sOutput.value + ' </Point>\n'; sOutput.value = sOutput.value + '</Placemark>\n'; sOutput.value = sOutput.value + '</kml>\n'; fnWrite(sOutput.value); } </script> </head> T he onLoad attribute of the body element below s tarts the whole thing off. T he remainder of the H T M L is jus t layout and formatting. <body onload="fnRead( )"> <table> <tr> <td> <strong>Input Text</strong><br /> <textarea id="txtInput" cols="80" rows="3"></t </td> <td rowspan="2" valign="top"><strong>Map Results</ </tr> <tr> <td> <strong>Output Text</strong><br /> <textarea id="txtOutput" cols="80" rows="18"> </td> </tr> <tr> <td colspan="2"><strong>Save Results</strong></ </tr> </table> </body> </html> We have G oogle E arth loading in the .kml file every 1 0 s ec onds and the J avaSc ript page reading in the res ults .txt file and writing out the me.kml file every 1 0 s ec onds . T here's jus t one thing left to do, whic h is to grab the data from the G P S unit every few s ec onds . T ime to go bac k outs ide or put the unit into demo mode! What we want to do is c all the c ommand garnix x > results.txt onc e every few s ec onds . We c ould, for example, write a .bat file c alled go.bat and put the following in it: garnix -x > results.txt go T hat'll run the c ommand and then c all its elf again. H owever, that'll really mes s us up: C P U us age will roc ket up and, mos t of the time, the file will be in an open, deleted, or being- c reated s tate. A s a res ult, our J avaSc ript will never get a look ins ide. We need to be able to paus e the running for a s hort while. Sadly, M ic ros oft didn't s hip M S- D O S with a paus e or wait c ommand. T here is a file c alled s leep.exe that's part of a 1 2 M B res ourc e kit, but I for one don't want to download 1 2 M B worth of files jus t for one s mall applic ation. I t's c heeky, but here's what we'll do: we'll c reate a new file c alled wait.bat and enter this into it: @ping 127.0.0.1 -n 11 -w 1000 > nul go We're going to ping ours elves as a way of ins erting a delay in our s c ript. (yes , s erious lywe did s ay it was a hac k! ) T he parameters we us e are -w 1000, whic h s ets the timeout to 1 ,0 0 0 millis ec onds , and -n 11, whic h tells it to s end off 1 1 pings . I n princ iple, this s hould delay for about 1 0 s ec onds , s inc e it won't paus e after the las t ping. With a bit of experimentation, you'll be able to c alibrate how many pings you need for c ertain lengths of time. N ow, go bac k and edit the original go.bat file like this : garnix -x > results.txt wait A nd we're all s et! Wire up the G P S unit and make s ure it's on and c onnec ted. T hen c hec k that the c orrec t c om port is s elec ted in the garnix.cfg file. Take a deep breath and type go from the Windows c ommand line. A c yc le s hould s tart with go.bat c alling wait.bat and wait.bat after a delay c alling go.bat. To s top it, type C trl- C . N ow, get all three things running: the .bat file c yc le in the c ommand s hell, the index.html page reloading in Firefox, and, las tly, G oogle E arth reading in the me.kml file. 4.12.4. Hacking the Hack 4.12.4.1. Pre-cache the Google Earth data. I 'll be the firs t to admit that needing a wireles s c onnec tion when you're on the move is n't always ideal or even pos s ible. Firs t off, if you're planning a c ar trip or even a quic k walk, you c an go over the route in G oogle E arth firs t, and it'll c ac he the high- res olution images , roads , and other details you dec ide to enable. You c an inc reas e the s ize of the c ac he by going to Tools O ptions C ac he. Stic k the G P S unit and the laptop onto the das hboard, and off you go! You're jus t playing with the files in the loc al c ac he, s o no I nternet c onnec tion is needed. Tracking with Perl I f the idea of us ing Firefox to read and write loc al files s eems mor than a bit weird to you, you might try obtaining a Windows vers ion P erl, s uc h as A c tiveP erl (http://www.ac tives tate.c om/), and try ru the following bit of P erl c ode with perl.exe: my ($lat, $lon); while (1) { sleep 10; unless (open GARNIX, "garnix -x|") { warn "Can't read from garnix: $!\n"; next; } while (<GARNIX>) { if (/Lat\w+\s+(-?\d+)deg\s+(\d+)min\s+([\d.]+)sec/o) $lat = abs($1) + $2 / 60 + $3 / 3600; $lat *= -1 if $lat < 0; } elsif (/Long\w+\s+(-?\d+)deg\s+(\d+)min\s+([\d.]+)se $lon = abs($1) + $2 / 60 + $3 / 3600; $lon *= -1 if $lat < 0; } } close GARNIX; unless (open KML, ">me.kml") { warn "Can't write to me.kml: $!\n"; next; } print KML <<End; <?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://earth.google.com/kml/2.0"> <Placemark> <name>Me</name> <LookAt> <longitude>$lon</longitude> <latitude>$lat</latitude> <range>750</range> <tilt>0</tilt> <heading>0</heading> </LookAt> <styleUrl> root://styleMaps#default+nicon=0x307+hicon=0x317 </styleUrl> <Point> <coordinates>$lon,$lat,0</coordinates> </Point> </Placemark> </kml> End close KML; } A s you c an s ee, this c ode does bas ic ally the s ame thing as the J avaSc ript, but without the need for Firefox and the res ults .txt file. H owever, if you're willing to us e G P SBabel [Hack #35] ins tead of G arnix, you c an ac tually get away with this s imple batc h s c ript, s i G P SBabel knows how to generate KM L direc tly: @echo off :again gpsbabel -i garmin,get_posn -f com1: -o kml \ -F\tmp\me.kml ping 127.0.0.1 -n 1 -w 1000 > nul: goto again E ither way, by doing without Firefox, we los e the feedbac k provide the brows er window, partic ularly s ome of the nifty bits des c ribed i "H ac king the H ac k" s ec tion. Figuring out, for example, how to s c r FT P or s cp to upload this file to a s erver without us ing Firefox will left as an exerc is e for the us er. 4.12.4.2. Let other Google Earth users follow along in real time. You're about to c yc le ac ros s the c ountry, s o obvious ly you're going to be uploading your photos to Flic kr and blogging your progres s . I t's all very well us ing the G P S and G oogle E arth to determine where you are, but what about letting other people know? We want to put our .kml file up onto the I nternet s o other people c an c onnec t to it with their N etwork L ink. I t's time to update our index.html file. E dit the table at the bottom to look like this : <table> <tr> <td> <strong>Input Text</strong><br /> <textarea id="txtInput" cols="80" rows="3"></t </td> <td rowspan="2" valign="top"> <strong>Map Results</strong><br /> <iframe id="iMap" width="300" height="400"></i </td> </tr> <tr> <td> <strong>Output Text</strong><br /> <textarea id="txtOutput" cols="80" rows="1 </td> </tr> <tr> <td colspan="2"> <strong>Save Results</strong><br /> <iframe id="iSave" width="800" height="40"></ </td> </tr> </table> To put the .kml file up onto the I nternet, we're going to need a s erver and s ome s erver- s ide s c ripting. I 'll us e P H P as an example, but it s hould be eas y enough to c onvert to any other language. H ere's the P H P file, whic h we'll c all s aveKML.php, and whic h needs to be uploaded to a s erver s omeplac e: <?php $kml = '<?xml version="1.0" encoding="UTF-8"?>'; $kml .= '<kml xmlns="http://earth.google.com/kml/2.0">'; $kml .= '<Placemark>'; $kml .= ' <name>Me</name>'; $kml .= ' <LookAt>'; $kml .= ' <longitude>'.$HTTP_GET_VARS['fLon'].'</longitude $kml .= ' <latitude>'.$HTTP_GET_VARS['fLat'].'</latitude $kml .= ' <range>750</range>'; $kml .= ' <tilt>0</tilt>'; $kml .= ' <heading>0</heading>'; $kml .= ' </LookAt>'; $kml .= ' <styleUrl>root://styleMaps#default+nicon=0x307+h styleUrl>'; $kml .= ' <Point>'; $kml .= ' <coordinates>'.$HTTP_GET_VARS['fLon'].','.$H VARS['fLat'].'</coordinates>'; $kml .= ' </Point>'; $kml .= '</Placemark>'; $kml .= '</kml>'; $fr = @fopen('me.kml', 'w'); @fputs($fr, $kml); fclose($fr); header('Content-Type: text/plain'); print 'saved'; ?> T he above s c ript takes two parameters , fLon and fLat, from the U RL and us es them to build and s ave a KM L file. You'll probably want to c hange the name in <name>Me</name> to your name, and c hange the me.kml to s omething els e. I n order to upload the c oordinates to the s erver, we'll add this line at the end of the fnWrangleText( ) func tion: document.getElementById('iSave').src = 'http://www.yourserver.com/urlPath/saveKML.php?fLat=' + fLon; E ac h time your index.html file reloads , it'll attempt to c all the remote file and pas s it your c urrent loc ation. I f you happen to be near a Wi- Fi hots pot, your pos ition will be updated. A ll your friends and family c an add your .kml file as a N etwork L ink s et to update every 3 0 mins or s o and us e it to watc h your daily progres s . A n eas ier way of getting people to update a network link is to s et up the N etwork L ink as you'd want other people to us e it, s ave it, then point people to that file rather than the ac tual me.kml file. D oing s o will automatic ally s ubs c ribe them to the N etwork L ink without any effort. T he file will look like this : <?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://earth.google.com/kml/2.0"> <NetworkLink> <description> Follow my cycle tour across the USA. </description> <name>My Road Trip</name> <Url> <href>http://www.yourserver.com/ urlPath/me.kml</href> <refreshMode>onInterval</refreshMode> <refreshInverval>1800</refreshInverval> </Url> </NetworkLink> </kml> I f you don't have a s erver, you c an s till update your pos ition by us ing a s ervic e s uc h as G eobloggers .c om us ing the following U RL : document.getElementById('iSave').src = 'http: recordObject?objName=geoFlickrBot' + '&objKey=A56C-2256-FE23&fLat=' + fLat + '&fLon=' + fLo For your s erver to s erve .kml files , you'll need to s et up the c orrec t M I M E types : application/vnd.google-earth.kml+xml kml application/vnd.google-earth.kmz kmz U s e your favorite s earc h engine to find out how to s et up c us tom M I M E types on your web s erver. 4.12.4.3. Add other people's photos into the browser window. Finally, add this line at the end of the fnWrangleText( ) func tion. document.getElementById('iMap').src = 'http://www.geobloggers.com/mob/index.cfm?lat=' + fLa I f you have a c onnec tion to the I nternet, Firefox will load the mobile phone vers ion of G eobloggers into the other iframe. I t s hows you the neares t three photos to your c urrent loc ation along with the direc tion and dis tanc e to them. I f you are wandering around a c ity, then every time you found s ome wireles s ac c es s , you'd get updates of nearby photos to go and hunt out. I f you're s tuc k without I nternet ac c es s , brows e to http://www.geobloggers .c om/mob/ us ing your phone's web brows er and enter your pos ition via a form. 4.12.4.4. Add other people's photos into Google Earth itself. Bes ides having time- bas ed network links , you c an als o have network links that update as you move around the E arth. Try adding a new network link to G oogle E arth, but this time s et the loc ation to http://www.geobloggers .c om/fulls c reenBac kend/dataFeed.c fm. Set the V iew- Bas ed Refres h to A fter C amera Stops , and make the delay four s ec onds . When you zoom into a loc ation and then paus e, after four s ec onds G oogle E arth will s tart to load in Flic kr P hotos from G eobloggers for the area you are looking at. C ombine this with the hac k jus t des c ribed and as you move around photos taken by Flic kr us ers will appear. I f you want to s ee photos from jus t a s ingle us er add ?sUsername= [username] onto the end of the U RL . A lternatively, if you're viewing an area where you take a lot of photos yours elf, you c an add ?sExcludeUsername=[your username] to the U RL to get everyone els e's photos . Dan Catt Hack 40. The Ghost in Google Ride Finder Generate street maps f rom Google's real-time taxi-mapping service. O ne of the firs t G oogle M ap H ac ks was releas ed by G oogle its elf. T he G oogle Ride Finder is os tens ibly a mapping s ervic e to find nearby taxis and airport s huttles in major metro areas . While it's us eles s for getting a ride with thes e c entrally booked s ervic es , it really func tions as a very engaging advertis ement for thes e c ompanies . (A nd, while we're at it, don't we ac tually need the public trans it G oogle M aps H ac ks extended for live updates for s us tainable trans port alternatives ? ) T he real appeal is how G oogle Ride Finder demons trates the us e of realtime, updating s patial data. T he immediac y of the Web, c ombined with geo vis ualization, has powerful pos s ibilities . I n this hac k, that live data will be repurpos ed to reveal the s treet map "ghos t" of airport s huttles and taxis , produc ing raw data that might be c ons umed by gras s roots mapping projec ts s uc h as O penStreetM ap (http://www.opens treetmap.org/). T he G oogle Ride Finder lives at http://labs .google.c om/ridefinder. T he initial view s hown in Figure 4 - 2 6 is of N orth A meric a, with pus h pins marking the areas for whic h they have data. Figure 4-26. Ride Finder home page I f you zoom in to C hic ago, you'll get a view like Figure 4 - 2 7 . E ac h pus hpin repres ents an individual vehic le, almos t all of them taxic abs . 4.13.1. Finding the Data L ike G oogle L oc al s earc hes , G oogle Ride Finder rec eives its annotations in their geodata format. To find the loc ation of this feed, look in the J avaSc ript file http://labs .google.c om/ridefinder/data? file=ride_js , referenc ed from the H T M L s ourc e. T he U pdate Vehic le L oc ations button c alls refreshMarkers(), whic h then c alls updateMarkers(). T his func tion c ons truc ts the following U RL : var j="/ridefinder/data?marker=1&lat="+f+"&lon="+g+"&z="+m "&src="+w+"&notes="+(new Date()).getTime(); Figure 4-27. Ride Finder in Chicago I n this bit of c ode, f and g are the lat/long c enter of the map, m is the zoom level, and w is hardc oded to 3. T he notes argument is a times tamp, whic h s eems to be appended to avoid hitting any c ac he. C ons truc ting a U RL with, for example, the c enter of M anhattan and s c ale 8 , c onfirms that this is the feed for Ride Finder. http://labs.google.com/ridefinder/data?marker=1&lat=40.750 &lon=-73.996328&z=8&src=3&notes= A lthough eac h annotation within the feed c orres ponds to the loc ation of an individual vehic le, no unique identifier is inc luded to link two annotations ac ros s an update. I t's pos s ible to get near- matc hes by meas uring s patial proximity in s uc c es s ive feeds , whic h update every five minutes ac c ording to G oogle. T he interes ted reader is invited to give it a try and and s ee if you c an build a poor man's real- time traffic monitoring applic ation. 4.13.2. Accumulating the Data H ere, we're going to ac c umulate taxi pos itions over a few days and build up a s treet map of the c ity of your c hoic e. Set the latitude and longitude of the data U RL , derived from another s ourc e, s uc h as http://geoc oder.us /. Setting zoom to 8 is s uffic ient to c over a metro region. A ppend the c urrent times tamp to avoid the c ac he. P as te the following c ode into a file c alled accumulate.pl: #!/usr/bin/perl $dir = "."; $date = time; $lat = 40.750422; $lon = 73.996328; $url = " http://labs.google.com/ridefinder/data?" . "marker=1&lat=$lat&lon=$lon&z=8&src=1&notes= system("/usr/bin/wget P $dir $url"); T he variable $dir s pec ifies where you will s tore the loc ation data files . For example, ~/data will s tore them in the s ubdirec tory named data/ under your home direc tory. You want the s c ript to run every five minutes in order to c ollec t data. You c an obs es s ively watc h the c loc k and s tart the s c ript yours elf, or, under a * nix variant, you c an us e the s c heduling feature of the modern operating s ys tem. E dit your crontab with the c ommand crontab e. T his line will run the s c ript every five minutes . 0-59/5 * * * * /home/ride_finder/accumulate.pl C hange /home/ride_finder to matc h the direc tory in whic h you ins talled the accumulate.pl s c ript. 4.13.3. Plotting the Data A fter about 2 4 hours , you'll have enough data to s tart building ghos t maps . T his P erl s c ript, draw.pl, s imply s trips the lat/long from the s tandard input and plots the points as an unprojec ted map. You'll als o need the Image::Magick module from the C P A N , whic h you c an find at http://s earc h.c pan.org/~jc hris ty/P erlM agic k/. #!/usr/bin/perl use Math::Trig qw(deg2rad rad2deg asin); use Image::Magick; use POSIX qw(floor); $lat $lon $d = $w = $h = = 40.750422; = -73.996328; 20; 1500; 1500; sub latlon2xy { my ($lat,$lon) = @_; my @xy; $xy[1] = $h * ($north - $lat) / ($north - $south); $xy[0] = $w * ($lon - $west) / ($east - $west); return @xy; } $radius = 6378.1; #km $lat = deg2rad($lat); $lon = deg2rad($lon); $arc = $d / $radius; $north = rad2deg($lat + $arc); $south = rad2deg($lat - $arc); $west = rad2deg ($lon+asin(-1*sin($arc)/cos( asin(sin($lat $east = rad2deg ($lon+asin( sin($arc)/cos( asin(sin($lat)* my $img = new Image::Magick->new(size=> $w . "x" . $h, qua $img->ReadImage('xc:white'); while (<>) { @points = split "<location", $_; foreach $p (@points) { $p =~ /lat="(.*?)" lng="(.*?)"/; @xy = latlon2xy($1,$2); if ($xy[0] >= 0 && $xy[0] <= $w && $xy[1] >= 0 && $xy[1] <= $h) { $img->Set('pixel[' . floor($xy[0]) . ',' . floor($xy[1]) . '] } } } $img->Write(filename=>"out.jpg"); I n order to run the hac k, we'll as s ume you have the s c ript in the c urrent direc tory and the data you ac c umulated earlier in a s ubdirec tory c alled data/. From there, run: $ perl draw.pl data/* T he s c ript writes the res ult to an image c alled out.j pg in the c urrent direc tory. Set variables within the s c ript for the lat/long c enter of the data feed, and a dis tanc e in kilometers of your c hoos ing, whic h are us ed to c alc ulate the extents of the map, and the width and height of the image. You want the lat/long to be c los e to the s ame as you s elec ted in accumulate.pl. With lat/long trans lated to x/y c oordinates , I mageM agic k is employed to plot eac h point. A t firs t you may s ee jus t the bares t outline of the c ity, with s ome major roads and bridges perhaps . With more days of data, individual s treets will begin to form along lines of highes t dens ity, as s ugges ted by Figure 4 - 2 8 . (G P S in thes e vehic les c an be inac c urate, res ulting in a dis tribution over the ac tual s treet loc ation, pos s ibly bleeding into off- s treet s pac e and buildings .) P ec uliarities of taxi travel will bec ome apparent, with routes to the airport overemphas ized and route variations along s oc ioec onomic and dis tric ting lines . M aybe you c an s pot drivers ' favorite plac es for a c offee break. Figure 4-28. Ghost roads of New York 4.13.4. Hacking the Hack For a neat variation, build an animated G I F with I mageM agic k by grouping points by the hour, gradually revealing the s treet map ghos t. H ave fun! 4.13.5. See Also crontab tips are available at http://www.everything2 .c om/index.pl? node_id=7 6 5 4 1 2 Mikel Maron Hack 41. How Google Maps Got Me Out of a Traffic Ticket The democratization of research is demonstrated, and Google Maps serves the cause of justice by answering a basic, but disputed, f actual question. I n J anuary of this year, I was pulled over by a traffic offic er for "dis obeying a s teady red," a.k.a. running a red light. I pleaded not guilty to the c harge, and, nearly s ix months later, I went to c ourt to find out the fate of my tic ket violation. I n the end, it was nearly down to my word agains t the offic er's but G oogle M aps s aved the day! T here I was , on a benc h waiting for my name to be c alled at the downtown M anhattan D M V hearings bureau. A fter hearing s everal tes timonies from other drivers I knew this judge was n't going to be s ympathetic to my troubles . She heard driver after driver, but only one had a happy ending (from the driver's point of view). So I was worried, bec aus e being found guilty would mean a $ 1 5 0 fine, plus $ 5 0 in penalties , andwors t of allpoints on my lic ens e. I began to c ontemplate how it all happened s inc e it had been s o long. I jotted down s ome notes on a s mall piec e of paper, and then c ame the moment of truth. A fter my name was c alled, I gathered my belongings and made my way up to the s tand where the tic keting offic er joined me. T he judge s wore her in and as ked for her tes timony. T he offic er did jus t what I expec tedafter all, I had been lis tening to thos e prior tes timonies and began to des c ribe the s c ene of the violation. I n her s tory, I notic ed one fatal flaw, whic h I wanted to exploitbut I had no proof whats oever. T he offic er s tated that the s treet I was on was a one- way wes tbound s treet, and that I was turning onto an avenue that was a two- way s treet s eparated by a c onc rete divider. T he flaw was that I had ac tually been on a two- way s treet, not a one- way. A t las t, the time c ame for my tes timony, and I s tated that I had been in midturn, when an onc oming vehic le c ame toward me very quic kly, and I had dec ided not to make the turn until that SU V pas s ed me. T he J udge s topped and as ked me how there c ould be an onc oming vehic le if the s treet was only one- way. I s tated that it was ac tually a two- way s treet. T he offic er reiterated that it was a one- way. Who was the judge to believe? I was des perate for proof, s o I did the obvious : I whipped out my notebook c omputer. I was very luc ky to find an extremely bad c onnec tion via Wi- Fi. I pulled up Firefox and went to maps .google.com. I typed up the inters ec tion and zoomed in as c los e as pos s ible, as s hown in Figure 4 - 2 9 . A s you c an s ee, C athedral P arkway (a.k.a. 1 1 0 th Street) has no arrow indic ating the traffic direc tions . H owever, 1 0 9 th and 1 1 1 th do. I explained to the judge that this means that 1 1 0 th is a twoway s treet. T he traffic offic er begged to differ. She s aid perhaps an arrow was s imply mis s ing from the equation. So I c alled her bluff and s howed the judge another inters ec tion the one at T imes Square, as s hown in Figure 4 - 3 0 . Figure 4-29. Does an absence of arrows mean that Cathedral Parkway is two-way? Figure 4-30. Everyone knows 42nd Street goes both ways I as ked H er H onor if s he was familiar with 4 2 nd Street. She nodded, and I c ontinued by obs erving how all the neighboring s treets have arrows to s how the direc tion of traffic , with one exc eption: 4 2 nd Street, whic h is wellknown to be a two- way s treet. T he judge replied that, due to the offic er's poor memory, the violation would have to be dis mis s ed. T hank you, G oogle M aps : you rule! 4.14.1. See Also T his s tory was originally pos ted on G ear L ive. G ear L ive is a web magazine devoted to the high- tec h lifes tyle, with news , previews , reviews , c ommentary, and the oc c as ional tip on traffic law: http://www.gearlive.c om/index.php/news /artic le/go T he A C L U has an informative public ation c alled Know Your Rights : What To Do if You're Stopped by the Police at http://www.ac lu.org/P olic eP rac tic es /P olic eP rac tic es .c fm? I D =9 6 0 9 &c =2 5 Andru Edwards & Edwin Soto, http://www.gearlive.c om Chapter 5. Google Maps in Words and Pictures Sec tion 5 .1 . H ac ks 4 2 5 0 : I ntroduc tion H ac k 4 2 . G et M ore out of What You Read H ac k 4 3 . D on't Believe E verything You Read on a M ap H ac k 4 4 . You G ot Your A 9 L oc al in M y G oogle M aps ! H ac k 4 5 . Share P ic tures with Your C ommunity H ac k 4 6 . Brows e P hotography by Shooting L oc ation H ac k 4 7 . G eotag Your O wn P hotos on Flic kr H ac k 4 8 . Tell Your C ommunity's Story H ac k 4 9 . G enerate G eoc oded RSS from A ny G oogle M ap H ac k 5 0 . G eoblog with G oogle M aps in T hings ter 5.1. Hacks 4250: Introduction T he reas on people love maps s o muc h is that maps tell s tories about plac es , and people love s tories . M aps provide a narrative and a c ontext for unders tanding the world around us . E ven the mos t mundane maps tell a s tory; for example, a road or s ubway map's s tory is about how to get around quic kly. I n this c hapter, we're going to explore the narrative pos s ibilities inherent in G oogle M aps . We'll s ee how G oogle M aps c an be a reading aid, how s atellite images don't always tell the full s tory, and how G oogle M aps c an be mated with online photo s ervic es s uc h as Flic kr to es tablis h a geographic c ontext for the s tories that our photographs tell. Finally, we'll look at the us er- friendly end of the "geos patial web," where G oogle M aps c an be us ed to produc e and vis ualize feeds of information from other s ourc es , to weave our s tory together into the many s tories being told every day on the I nternet. Hack 42. Get More out of What You Read If maps tell stories, what about the stories that tell maps? "I lean agains t a U SA Today paper box on Was hington and C lark and think, 'Who the hell are you to make s uc h a c laim? '" T hat's the s ec ond s entenc e from the book Bike Mes s engers and the Cult of Human Power by Travis H ugh C ulley. I t is the s tory of Travis ' work as a bic yc le mes s enger in C hic ago. Why did Travis pic k that inters ec tion? D id that jus t happen to be where he was , or does it have more meaning? Where is Was hington and C lark? E nter "Was hington and C lark, C hic ago, I L " in the loc ation s earc h box and we s ee in Figure 5 - 1 that the inters ec tion is , well, in the middle of a lot of s treets . T hat helps , maybe, a little. But I don't know C hic ago, s o all it means to me is a lot of s treets . C lic king on Satellite gives us the jac kpot of Figure 5 - 2 : the inters ec tion is right s mac k in the middle of downtown. Figure 5-1. A map of Chicago showing the action in Bike Messengers and the Cult of Human Power Figure 5-2. The satellite view gives us the big (or at least elevated) picture D ifferent zoom levels give us , well, different pic tures . Figure 5 - 2 s hows an overview of the whole c ity, but when we zoom way in as in Figure 5 - 3 ,we s ee a 4 - bloc k by 3 1 /2 bloc k window of downtown C hic ago. L ooking at that, I c an almos t s mell the bus fumes . C aught in the rus h of plot, too often I 'll let the details s lide. H ollywood and V ine? Was hington and C lark? Who c ares ? I jus t want to s ee what happens next! But if that is all that matters , why s hould authors bother with plac e names ? Why not s imply write as if everything happened in the s ame grey protoplas mic s ea? C ontext matters : the plac es where things happen s hape what happens and what we think about what happens . C ontext feeds the mind. Figure 5-3. The satellite view tells another story Hack 43. Don't Believe Everything You Read on a Map Learn how the selection of imagery can be extremely subjective. I t is eas y to as s ume that maps are s omehow true and objec tive repres entations of a plac e. A fter all, mos t of our interac tions with maps have to do with prac tic al affairs s uc h as navigating the c omplex layout of a c ity. T he truth, however, is that maps both reflec t and c reate reality. T his is mos t c lear in the c hoic es of what is , and is not, put on a map. For example, c hamber of c ommerc e maps typic ally s how lots of green for parks and greenbelts , but s omehow neglec t to point out the les s des irable as pec ts of a c ommunity. O kay, you might s ay, the maps are s ubjec tive, but I c an c ount on the aerial imagery, right? I t is jus t a rec ord of how things were. A las , even there we have is s ues . T here is a huge pos s ibility for bias in the c hoic es of images that will be dis played. Figure 5 - 4 s hows part of the Blac k Roc k des ert in N evada, near the town of G erlac h. For mos t of the year this is an empty expans e where you c an either hear yours elf think or hear the people c ruis ing about trying to s et land- s peed rec ords in the armed- and- inebriated SU V - driving c ategory. H owever, for a week, plus time before and after for s et up and c lean up, this is Blac k Roc k C ity, home to the Burning M an fes tival. T his partic ular image was taken during the s etup period for the 2 0 0 3 event. Figure 5-4. A bit of desert in Nevada, late summer H ow did that happen to bec ome the c anonic al G oogle repres entation of an area around 4 0 .7 5 4 9 N , 1 1 9 .2 3 6 0 8 W? I s us pec t that it was n't pure c hanc e! Was it an ac c ident that the aerial photo in Figure 5 - 5 c entered around 3 7 . 7 1 3 5 3 2 N , 1 2 2 .3 8 6 0 7 5 W s hows the San Franc is c o 4 9 ers ' football s tadium near C andles tic k P oint State P ark in the middle of a game? O n the other hand, the aerial photo in Figure 5 - 6 c entered on 3 7 .7 5 1 3 6 7 N , - 1 2 2 .2 0 1 2 3 9 W s hows the nearby home of the O akland Raiders , another football team, to be empty and c onfigured for a bas eball game? ? T he s imples t explanation is that maps tell s tories , and s o thes e partic ular mapmakers c onfigured reality through s elec tion of imagery in order to tell a more entertaining s tory. A fter all, ac c ording to M uriel Rukeys er, "the univers e is made up of s tories , not atoms ." Some of the s tories have a c hilling mes s age. Take a look at the imagery around 1 6 0 0 P enns ylvania A venue, Was hington, D .C . You c an c ount the trees on the White H ous e grounds , but roofs are all obs c ured, as s een in Figure 5 - 7 . T he White H ous e s uffers little in c omparis on to the C apitol. C learly there is a large blobby thing at that end of the N ational M all, but it is n't c lear what it is . C ongres s is apparently more protec tive of its foliage than is the E xec utive Branc h, as we c an s ee in Figure 5 - 8 . Figure 5-5. Near Candlestick Point State Park Figure 5-6. The home of the Raider Nation in Oakland Figure 5-7. You can plan an Easter egg hunt, but don't plan to find any on the roof Figure 5-8. Congress shall make no law, assuming you can find it T he P entagon, as s hown in Figure 5 - 9 , appears to be the leas t protec tive of rooftop as s ets . Figure 5-9. For once, the Pentagon appears to have nothing to hide I n s ome parts of the c ountry, c ornfield artis ts have expres s ed their s upport for the military. T here are no obs c ured roofs in Figure 5 - 1 0 , and I bet folks in uniform feel welc ome in Bellevue, N ebras ka. (A t leas t, the ones who fly do! ) I 'm tempted to make a c omment about real national s ec urity vers us "s ec urity theater," but there are s o many s trange things happening in the world that I don't unders tand that I 'd bes t remain s ilent. A t a rec ent c onferenc e, I was introduc ed to the phras e kill chain, as in "you c an ignore him, he's not in the kill c hain." Sinc e I c an't even figure out whic h L inux des ktop is bes t, I have no c hanc e at an intelligent opinion about national s ec urity or the kill c hain. P erhaps I 'm better equipped for an apprec iation of the two images of 1 I nfinite L oop, C upertino, C A 9 5 0 1 4 . T he firs t, Figure 5 - 1 1 , is taken from G oogle's s atellite imagery, and the s ec ond, Figure 5 - 1 2 , from M ic ros oft's V irtual E arth. Was A pple bombed to rubble rec ently? O bvious ly, as of this writing, M ic ros oft's D igital E arth is us ing very old imagery of a s mall s lic e of C upertino. T his appears odd, s inc e the imagery for other parts of the Bay A rea s eems muc h more c urrent. I t's almos t as if…M ic ros oft…wants us to believe…that A pple…s imply is n't there….N o, in the end, fretting over c ons pirac y theories about how plac es are portrayed is uns atis fying. Figure 5-10. "We honor those who serve America" Figure 5-11. What Google thinks of this particular Infinite Loop Figure 5-12. Apple appears to have disappeared T hat does n't make it nec es s arily wrong, however. A fter all, we live in a world where a telephone c ompany with broadband bus ines s will intentionally bloc k traffic to telec omm workers ' union web s ites during a s trike. P erhaps it is enough to rec ognize the les s on that reality is a c ommodity, like any other, and that ac c es s to reality is s ometimes mediated through more s teps than might always be totally healthy for a free and democ ratic s oc iety. Hack 44. You Got Your A9 Local in My Google Maps! Use Greasemonkey to inject A 9's Local Images into Google's much nicer map interf ace. A 9 .c om, A mazon's s earc h c ompany, has s pec ial truc ks equipped with digital c ameras and G P S units that run around s elec ted c ities . T he truc ks take s treet- level pic tures of jus t about everything and then index that with the G P S and a geoc oding applic ation to add photographs to bus ines s lis tings . A 9 .c om "brings Yellow P ages to life." Figure 5 - 1 3 s hows the A 9 Bloc k V iew of the C ity L ights books tore in San Franc is c o. A 9 .c om is pretty neat, but the mapping interfac e is a bit weak. I f you have the G reas emonkey extens ion ins talled in the Firefox brows er, you c an ins tall A 9 +G maps , a G reas emonkey us er s c ript that will load A 9 images on top of your G oogle M aps . I ns talling G reas emonkey in Firefox is c overed in detail in "A dd G oogle M aps to A ny Web Site" [Hack #27] and "Trac k Your U P S P ac kages " [Hack #25]. Figure 5-13. City Lights bookstore, according to A9.com O nc e G reas emonkey has been ins talled in Firefox, you c an get A 9 +G maps from http://www.kokogiak.c om/webtools /greas emonkey/a9 images ingoo From that page, right- c lic k on the link to a9 gmap.us er.js and s elec t I ns tall U s er Sc ript. A n ins tallation window will pop up, as depic ted in Figure 5 - 1 4 . C lic k on O K, and with a bit of luc k you'll get a s tatus window that s ays "Suc c es s ! Refres h page to s ee c hanges ." N ow, when you s earc h for a bus ines s on the G oogle M aps web s ite in an area c overed by A 9 L oc al, you'll be able to c lic k on the ic on and, a few s ec onds later, an A 9 thumbnail will appear in your info window. T he A 9 +G maps G reas emonkey s c ript is exec uted whenever a us er is on a page in the maps .google.com domain. When the us er c lic ks on an ic on in the map, the s c ript finds the newly opened info balloon and pars es the H T M L ins ide it to find the bus ines s name and addres s , if pres ent. T he s c ript then s ends that data out to A 9 .c om, behind the s c enes . When A 9 .c om res ponds , the s c ript pars es A 9 's H T M L to dis c over an image (if one exis ts ), and gets the loc ation and U RL of the A 9 .c om image and page. Finally, the s c ript ins erts a thumbnail image of that loc ation into the G oogle M aps info window. O ne c aveat: this hac k is largely bas ed on s c reen- s c raping and pic king apart the res pec tive D oc ument O bjec t M odels on both s ites . T hat means it's fragile and eas ily broken if either A 9 or G oogle alter too muc h H T M L layout. I n the meantime, mas hing up A 9 's s treet level photos with G oogle's map interfac e means that finding bus ines s es and other loc ations is eas ier than ever. Figure 5-14. Installing a user script under Greasemonkey Alan Taylor Hack 45. Share Pictures with Your Community Use Flickrcity to set up a collaborative photo map. P utting geoloc ated photos on a map is s omething geo- hac kers have worked on for a long time. N ow, us ing Flic kr, G oogle M aps , and a little piec e of glue c alled Flic krc ity (http://antimega.c om/flic krc ity/), anyone c an do this eas ily. I s tarted work on Flic krc ity bec aus e I wanted to c reate a res taurant review s ite for H els inki that anyone c ould c ontribute to. Flic kr was the natural plac e to s tore photos and information; s ites s uc h as G eobloggers (http://www.geobloggers .c om/) were us ing Flic kr as a data s ourc e and had already c reated a s tandard for geotagging photos . Flic krc ity automatic ally filters on a tag of the name of the c ity and the tag geotagged. U s ing additional tags , or s pec ifying a partic ular us er, you c an us e Flic krc ity for a variety of purpos es . To s ee all geotagged photos in a c ity, you c an jus t go to the U RL of the Flic krc ity ins tallatione.g., for H els inki, http://antimega.c om/flic krc ity/hels inki.c ity, as s hown in Figure 5 - 1 5 . Figure 5-15. Photos geotagged in Helsinki I f you wanted to s et up a c ollaborative res taurant review s ite for H els inki, you would need to tag photos in Flic kr with, s ay, "hels inki," "food," "geotagged," and the two loc ation geotags [Hack #46]. T hen you would c ons truc t a U RL that would return thes e images with this tag query, s uc h as http://antimega.c om/flic krc ity/hels inki.c ity? tags =food. Figure 5 - 1 6 s hows what this looks like. I f you jus t wanted to s ee all of my H els inki photos , you would us e a us er query s uc h as http://antimega.c om/flic krc ity/hels inki.c ity? us er=c hris dodo, as Figure 5 1 7 demons trates . O f c ours e, you c an c ombine the two, to s how jus t my food photos , as in http://anti- mega.c om/flic krc ity/hels inki.c ity? tags =food&us er=c hris dodo. I f you're us ing the map for yours elf, us e a different tag for eac h projec t you want to c reate. I f you want to s et up a c ollaborative map, pic k a tag name that is n't being us ed in Flic kr and tell all your photographers to add that tag. O f c ours e, others may s ee it and s tart us ing the tag tooFlic krc ity gets even better with more geotagged photos . I 've s et up Flic krc ity ins tallations for a few c ities , and others have s et up even more, but you c an als o download the c ode and s et up Flic krc ity for wherever you want. To do this , you will need a web s erver with P erl, s ome P erl modules (s ee the ins tallation ins truc tions on the web page for the lis t), and a little bit of webmas ter knowledge. Figure 5-16. Photos tagged with food in Helsinki Figure 5-17. Photos taken by chrisdodo in Helsinki You will need to c hange a few things in the s c ript (mainly the name of the c ity and the default G oogle map c oordinates and zoom level), and a direc tory on the s erver to s tore c ac he files . T hen put the s c ript in a direc tory on your s erver s uitable for hous ing C G I s c ripts , make the s c ript exec utable, and it s hould work. T he s c ript relies on the Flic kr and G oogle M aps A P I s , and if either s ervic e is s low or down, there may be problems . T he firs t time you run the s c ript, it will c reate a c ac he of data from Flic kr, whic h will be s low, but it will run more quic kly after that. Chris Heathcote Hack 46. Browse Photography by Shooting Location What a lovely photograph! Where was it taken? Sinc e the ris e of digital photography, more people have been s napping more photos than ever. Web s ites s uc h as Flic kr have s prung up to help people manage and publis h their photos , and Flic kr its elf has gone one s tep further and allows its us ers to "tag" their photographs with keywords that indic ate what's being depic ted. T hes e tags c an help you figure out who and what is being depic ted, but wouldn't it be nic e s ometimes partic ularly in the c as e of thos e lovely lands c ape photos to know where they were taken? 5.6.1. Tag, You're It Fortunately, Flic kr provides an A P I that allows you to query data from its s ys tem, and we c an us e this to find images that have been geotagged. G eotagged photos on Flic kr have three s pec ial tags as s oc iated with them. Firs t, they're tagged as geotagged, whic h allows us to find them us ing the Flic kr A P I . Sec ond, they have the tags geo:lat=…and geo:long=…as s oc iated with them, whic h gives us their geographic c oordinates . Figure 5 - 1 8 s hows one s ort of map that c an be made by mas hing up the Flic ker A P I and the G oogle M aps A P I . I n order to make us e of the Flic kr A P I , you need to s ign up to Flic kr, and then get yours elf an A P I key from http://www.flic kr.c om/s ervic es /api/. O nc e you have a key, you c an query Flic kr us ing the flickr.photos.search c all from their RE ST A P I , with a U RL like: http://www.flickr.com/services/rest/?method=flickr.photos. key=[your API key]&tag_mode=all&tags=geotagged&per_page=20 T his returns an XM L doc ument matc hing the lates t photos tagged as geotagged. T he XM L looks s omething like the following: <?xml version="1.0" encoding="utf-8" ?> <rsp stat="ok"> <photos page="1" pages="8553" perpage="5" total="42 <photo id="30221122" owner="47836075@N00" secret="1 server="21" title="From Camera Server(SlabbersCam)0000/00/0 ispublic="1" isfriend="0" isfamily="0" /> <photo id="30218138" owner="78211664@N00" secret="5 server="21" title="P8010502" ispublic="1" isfamily="1" /> <photo id="30218130" owner="78211664@N00" secret="8 server="23" title="P8010498" ispublic="1" isfriend="1" isfa <photo id="30211741" owner="59597347@N00" secret="b server="21" title="Tiny Sea Cave" ispublic="1" isfriend="0" <photo id="30197466" owner="47836075@N00" secret="e server="22" title="From Camera Server(SlabbersCam)0000/00/0 ispublic="1" isfriend="0" isfamily="0" /> </photos> </rsp> Figure 5-18. A map of recent geotagged photos from Flickr By querying the A P I for eac h partic ular photo, we c an get the detailed tags for eac h one. For example, this U RL returns the details of the "T iny Sea C ave" photo above: http://www.flickr.com/services/rest/?method=flickr.photos. =30211741&api_key=[your API key] T he returned XM L looks s omething like the following, whic h we've exc erpted for brevity: <?xml version="1.0" encoding="utf-8" ?> <rsp stat="ok"> <photo id="30211741" secret="bbadd69e06" server="21" dateuploaded="1122879388" isfavorite="0" license=" <title>Tiny Sea Cave</title> <description>More of a hole worn in the rock, wit seashells washed inside.</description> <tags> <tag id="100601461" author="59597347@N00" raw="carmel">carmel</tag> <tag id="100601464" author="59597347@N00" raw <tag id="100601465" author="59597347@N00" raw="shells">shells</tag> <tag id="100601940" author="59597347@N00" raw="geo:lat=36.5443288">geolat365443288</ <tag id="100602480" author="59597347@N00" raw="geo:lon=-121.933093">geolon121933093< <tag id="100602494" author="59597347@N00" raw="geotagged">geotagged</tag> </tags> </photo> </rsp> A s you c an s ee, we have all the info we need to loc ate this photo on a map. A ll we need to do is s earc h for photos with the geotagged tag, loop over eac h photo, and reques t the full information from Flic kr. O nc e we have that, we c an us e the G oogle M aps A P I to generate the map its elf and throw down s ome markers . 5.6.2. The Catch I t s ounds eas y, but there is one s mall c atc h: you're going to be running your photo map page on your s erver, and you want to get the XM L from a different s erver. For s ec urity reas ons , mos t modern brows ers , partic ularly Firefox and Safari, won't allow you to do this . U nles s your web page is s itting on Flic kr's web s ite, you c an't load the Flic kr XM L direc tly into your J avaSc ript. What you c an do, however, is run a proxy on your own s erver, whic h will c all Flic ker's A P I for you and pas s the res ults bac k to your brows er. Sinc e the domain of your map page and your XM L proxy will be the s ame, you won't trip any brows er's s ec urity features . You'll need a web s erver s omewhere that runs s ome form of s erver- s ide c ode. Within the J avaSc ript on the map page, we'll pas s the U RL of the XM L you want to retrieve and the J avaSc ript func tion you want to handle the XM L to the proxy s c ript, and then the proxy will return a bit of exec utable J avaSc ript to your c alling page. H ere's s ome P H P, whic h I put in a file c alled pas s Thru.php on my web s erver, that does the tric k: <?php $page = ''; $fh = fopen($HTTP_GET_VARS['sURL'],'r') or die($php_errorm while (! feof($fh)) { $page .= fread($fh,1048576); } fclose($fh); $page = str_replace("\r\n", ' ', $page); $page = str_replace("\n\r", ' ', $page); $page = str_replace("\n", ' ', $page); $page = str_replace("\r", ' ', $page); $page = str_replace("'", '&lsquo', $page); $functionName = $HTTP_GET_VARS['sFunction']; header('Content-Type: text/JavaScript'); print "thisXML = '$page';"; print "$functionName;"; ?> H ere's a s nippet of J avaSc ript c ode that s hows how we us e the XM L proxy to get Flic kr metadata into our page: 1 2 3 4 5 6 7 8 9 10 11 12 var thisXML; var sFlickrAPIKey = "[your API key ]"; var sFlickrURL = 'http://www.flickr.com/services/rest search' + '&tag_mode=all&tags=geotagged&per_page=20&api_ke var sPassThruURL = 'http://www.geobloggers.com/google var newJSElement = document.createElement("script"); newJSElement.src = sPassThruURL + '?sURL=' + escape(s + '&sFunction=fnHandleFli newJSElement.type = "text/JavaScript"; document.getElementsByTagName("head")[0].appendChild( H ere's what's going on. I n lines 1 through 5 , we define thisXML as a global variable, s et up our A P I key, s et the U RL we ac tually want the data from, and then s et the U RL where our XM L proxy s its . L ine 7 s ets up a new H T M L script element, and line 8 s ets its src attribute, pas s ing the U RL we want to get, and the func tion we want to handle it when it c omes bac k. I n line 9 , we s et the type attribute of the new script element, s o that the brows er knows it's J avaSc ript. L ine 1 0 s ets everything in motion by attac hing our J avaSc ript to the doc ument's head element, c aus ing the brows er to fetc h and exec ute the c ode via our XM L proxy. T he func tion that gets c alled needs to c onvert the s tring repres entation of the XM L into an ac tual XM L doc ument, s o the func tion s tarts out like this : function fnHandleFlickr() { try { var xmlDoc = xmlParser.parseFromString(thisXML, "a } catch(er) { alert("Sorry, couldn't parse the XML returned by F } } So why are we doing it this way, ins tead of, s ay, us ing XMLHttpRequest( )? T he main advantage of getting XM L by c ons truc ting a new <script> element and then populating it from a proxy is that, by us ing a s tandard brows er feature, we c irc umvent the s ec urity limitations of better- known ways of fetc hing XM L into a brows er. I f you were to us e s uc h a proxy to return the XM L direc tly to an XMLHttpRequest() c all, it would s till have to run on the s ame s erver as the H T M L page. By c ontras t, with our method, the page on whic h we are running our G oogle M aps hac k and our XM L proxy c an be on c ompletely different s ervers on different domains ac ros s the I nternet. I f you dec ide to s et up a proxy s c ript like the one des c ribed here, you will definitely want to hardc ode part of the addres s that you're getting the XM L from in the s erver s c ript or do s ome kind of c hec king on the U RL that's pas s ed in, s o that you're not s etting up an H T T P proxy that's wide open to the entire I nternet. You s hould not run the proxy s erver c ode as is . 5.6.3. The Code T he c ode for this hac k runs to about 1 5 0 lines , s o we'll jus t review the highlights here. You c an s ee it in ac tion at http://mappinghac ks .c om/projec ts /gmaps /flic kr.html. See the c ode its elf by s elec ting V iew Sourc e in your brows er. I n es s enc e, the J avaSc ript does exac tly as we've des c ribed above, us ing the s c ript ins ertion maneuver to firs t fetc h a lis t of geoc oded photos from Flic kr. N ext, it takes the firs t photo found and as ks Flic kr for its details . T he fnHandlePhoto() func tion is c alled by the J avaSc ript returned by the proxy, and this func tion extrac ts the s pec ific geo:lat and geo:long tags from eac h image: function fnHandlePhoto() { var bDidItWork = true; var fGeoLat, fGeoLong; try { var xmlDoc = xmlParser.parseFromString(thisXML, "a // Note, it's possible geo:long could also be call // so we'll look for both versions. var aTags = xmlDoc.documentElement.getElementsByTa for (i = 0; i < aTags.length; i++) { if (aTags[i].attributes['raw'].value.length > var sTag = aTags[i].attributes['raw'].valu if (sTag.substr(0,7).toLowerCase( ) == 'ge fGeoLat = parseFloat( aTags[i].attributes['raw'].value.s if (sTag.substr(0,7).toLowerCase( ) == 'ge fGeoLong = parseFloat( aTags[i].attributes['raw'].value.s } } } catch(er) { } I n the above c ode fragment, whic h has been edited a bit for readability, the XM L s tored by the proxy in thisXML is pars ed, and then the res ulting doc ument objec t is s c anned for tag elements . T he highlighted c ode examines eac h tag element to s ee if they are prefixed with geo:lat= or geo:long= and, if s o, extrac ts the c oordinates from them as floating point values . N ext, as s uming that the c oordinates were extrac ted properly, the fnHandlePhoto( ) func tion c reates a new GMarker objec t us ing the G oogle M aps A P I , and us es other information from Flic kr about the photo to generate an H T M L info window that pops up when the marker is c lic ked. T his popup will inc lude a thumbnail of the photo, the title, the owner's s c reen name, and a link to the photo's Flic kr page. if (!isNaN(fGeoLat) && !isNaN(fGeoLong)) { var point = new GPoint(fGeoLong,fGeoLat); var marker = new GMarker(point); var sHTML = ""; var xmlInfo = xmlDoc.documentElement. getElementsByTagName("photo"); var xmlTitle = xmlDoc.documentElement.getElementsB var xmlOwner = xmlDoc.documentElement.getElementsB sHTML += '<strong>' + xmlTitle[0].firstChild.nodeValue + '</strong sHTML += xmlOwner[0].attributes['username'].val sHTML += '<a href="http://www.flickr.com/photos/' + xmlOwner[0].attributes['username'].value + ' + xmlInfo[0].attributes['id'].value + '/" targ + '<img src="http://photos' + xmlInfo[0].attributes['server'].value + '.flickr.com/' + xmlInfo[0].attributes['id'] + xmlInfo[0].attributes['secret'].value + '_s.jpg" width="75" height="75" /></a>'; GEvent.addListener(marker, "click", function( ) { marker.openInfoWindowHtml(sHTML); }); map.addOverlay(marker); T he highlighted lines above c ons truc t the H T M L for the image thumbnail, whic h as you c an s ee is a bit c omplex. A fter dis playing the marker on the map, the c ode then c ontinues to s ee if there are any photos left to be proc es s ed from the original query, and, if there are, it pic ks the next one, and repeats until they're all s hown on the map. T his is all well and good, but it is quite s low, bec aus e the brows er has to as k the proxy to look up eac h and every photo in Flic kr one at a time. O ne advantage of this approac h, however, is that you c an c us tomize the query us ing the inters ec tion of multiple tags . N ear the top of the J avaSc ript s ec tion in flickr.html, you'll s ee a line that reads as follows : var lstTags = 'geotagged'; I f you're feeling c reative, you c an alter this to s how geotagged photos of s pec ific things or plac es : var lstTags = 'geotagged,flower'; //get geotagged flowers var lstTags = 'geotagged,flower,london'; //get geotagged l 5.6.4. Hacking the Hack I n prac tic e, all thos e A P I c alls to the Flic kr s erver do take up quite a bit of the us er's time, waiting for eac h photo to s how up on the map. U s ing your Flic kr A P I key, you c ould s et up a s ys tem to c ollec t the photos you're interes ted in, and put them into your own data s tore, from whic h you c an quic kly generate the maps you want to s ee. A lternatively, you c an us e an aggregator, s uc h as G eobloggers (http://geobloggers .c om/), whic h polls Flic kr periodic ally for new geoc oded photos , and then offers an A P I to fetc h metadata about them bas ed on loc ation. T he G eobloggers A P I is doc umented at http://www.geobloggers .c om/s ervic es /. O ur G eobloggers A P I example, whic h you c an find at http://mappinghac ks .c om/projec ts /gmaps /geobloggers .html, c alls in Flic kr image data from G eobloggers , us ing the bounding area of the map as a guide as to what to load in. O ne c hoic e bit of c ode from that file, edited for readability, looks like this : // Get rid of any old pins map.clearOverlays(); // Get the map's bounding box from the Google Maps API var sNewBounds = map.getBoundsLatLng(); // Build up the new URL based on the view window we ar var newGeoBloggersURL = 'http://www.geobloggers.com/fullscreenBackend/dat + 'iMaxRecords=' + iMaxRecords + '&sSearchTyp + '&minLon=' + sNewBounds.minX + '&maxLon=' + + '&minLat=' + sNewBounds.minY + '&maxLat=' + T he U RL as s embed in newGeoBloggersURL is then pas s ed to our XM L proxy. When it c omes bac k, it's pas s ed to another func tion that generates the markers : pins = xmlDoc.documentElement.getElementsByTagName("pi for (var i = 0; i < pins.length; i++) { var point = new GPoint( parseFloat(pins[i].getAttribute("lng")), parseFloat(pins[i].getAttribute("lat"))); var html = '<strong>' + pins[i].getAttribute("title") '</strong><br />'; html = html + '<img src="' + pins[i].getAttribute("sP + '" width="75" height=" var marker = createMarker(point,html,pins[i].getAttrib map.addOverlay(marker); … } What's partic ularly c ute about this method is that G eobloggers ac tually c reates s mall thumbnails of eac h photo to us e as markers on the map, in plac e of the us ual G oogle M aps markers , as you c an s ee in Figure 5 - 1 9 . Figure 5-19. A map of local photos from Flickr, via the Geobloggers API A dditionally, s inc e the G eobloggers A P I is loc ation- c entric , when you zoom or re- c enter the map, a c lic k to the Refetc h D ata button c aus es the map to update with new photos , bas ed on the loc ation of the map. M odifying this c ode to do this automatic ally, us ing the GEvent objec t from the G oogle M aps A P I , is left as an exerc is e for the readers ee "M ake T hings H appen When the M ap M oves " [Hack #60] for more details . Dan Catt Hack 47. Geotag Your Own Photos on Flickr Maps and pictures go together like a horse and buggy. E ver s inc e Flic kr s tarted c ataloguing people's digital photography, many have been c lamouring to be able to geoloc ate photos . T he idea of geotags was propos ed by D an C att. A s des c ribed in "Brows e P hotography by Shooting L oc ation" [Hack #46], D an c reated a s ervic e c alled G eobloggers (http://www.geobloggers .c om) to aggregate the geotagged photos . O ne of Flic kr's key features is that it allows you to add tags to your photos . A tag c an be a word or group of words , s uc h as "vac ation" or "my kids ." T here are three tags you need to add to photos to be able to geoloc ate them: geo: lat=xx.xxxx, geo.lon=yy.yyyy, and geotagged. T he latitude and longitude are expres s ed in dec imal degrees . L atitudes s outh of the equator and longitudes wes t of G reenwic h are negative. A s different latitudes and longitudes appear to be different tags to Flic kr, the geotagged tag is nec es s ary to let you s earc h for geotagged photos . T here are two ways to geotag photos : manually and us ing G oogle M aps . I f you have a G P S, us e it to rec ord the latitude and longitude as you take photos by taking a photo of the G P S. You c an s et the G P S to dis play in dec imal degrees (whic h may be repres ented as hddd.ddddd° in the G P S s ettings ), however, G P Ses often dis play in degrees and minutes , as s hown in Figure 5 - 2 0 , or degrees , minutes , and s ec onds . Figure 5-20. Take a photo of the GPS to make geotagging easy I f you have G P S c oordinates in degrees , minutes , and s ec onds , try the FC C 's c onverter at http://www.fc c .gov/mb/audio/bic kel/D D D M M SS- dec imal.html. I n Flic kr, add the three tags to eac h photo, whic h is repres ented by that latitude and longitude. Taking the loc ation in the photo as an example, the tags I would add to the photo are: geo:lat=71.171067 geo:lon=25.783050 geotagged T here is , thankfully, an eas ier way. We c an us e G oogle M aps and a nifty G reas emonkey s c ript to do all the heavy lifting for us . T he hard bit is s etting up. You need to ins tall Firefox (http://www.mozilla.org/produc ts /firefox/), and then G reas emonkey (http://greas emonkey.mozdev.org/). Flic kr us er C K has written a G reas emonkey s c ript c alled GmiF. Vers ion 2 .3 of G miF c an be found at http://www.flic kr.c om/photos /c kyuan/3 0 0 1 4 8 7 5 /. I n Firefox, right- c lic k on the flickr.gmap.us er.j s link, and s elec t "I ns tall us er s c ript." T hen c lic k O K in the dialog box. N ow when you go to a Flic kr photo page, there will be an extra ic on on the photo toolbar, as s hown in Figure 5 - 2 1 . Figure 5-21. A Flickr photo page, with extra GMaps button C lic king the G M aps button adds a G oogle M ap into the page, along with s everal c hoic es as s hown in Figure 5 - 2 2 . Figure 5-22. A map embedded in the photo page D rag and zoom the map to find the point where the photo was taken. You may have to s witc h to s atellite mode to s ee where you are at higher zooms . T hen c lic k on the map in the exac t plac e where you took the photo, and a red pointer will be dis played, as in Figure 5 - 2 3 . Figure 5-23. A red geolocation pointer appears C lic k the red pointer, and a bubble will dis play a thumbnail of the photo, loc ation, and more ac tions , as s hown in Figure 5 - 2 4 . Figure 5-24. A geotagging bubble Finally, s elec t the "A dd geo tags " link. T his adds the required tags to the photo, as s hown in Figure 5 - 2 5 . Figure 5-25. The final set of tags, including geotags T he photo is now geotagged; you c an s ubmit it to G eobloggers or wait for them to find it with the automatic s earc h of photos tagged geotagged. O nc e you've pic ked up the proc es s , geotags c an be added quic kly to s ets of photos . Chris Heathcote Hack 48. Tell Your Community's Story Give a guided tour of your community with photos and a Google Map. We've all been there before; huddled around a c omputer, looking at photo after photo of a friend or family member s tanding in front of one touris t attrac tion after another. I don't know about you, but after the third pic ture I s tart to fade fas t. I t's not that the pic tures are nec es s arily boring (although they very well might be); they're jus t s o repetitive. T he laws of phys ic s require that a photo be a repres entation of a phys ic al plac e, but we s o rarely dis play photos within any c ontext of phys ic al loc ation. G oogle maps provides jus t s uc h a c ontext, and the effec t of plac ing photos on a map at the loc ation they were taken adds an extra dimens ion of information to the photo. I 'm not s ugges ting that your s lides how of H awaii with eight photos of you on the s hores of a beautiful beac h will bec ome the mos t enthralling pres entation ever, but you might hold people's attention for s ix photos rather than three. 5.8.1. The Hack C ommunity Walk (http://www.c ommunitywalk.c om/) attempts to fac ilitate the proc es s of plac ing photos on a map s howing where they were taken. T he intent of it was , s urpris ingly enough, not to s imply alleviate the boredom of vac ation s lides hows , but rather to allow people to s hare their c ommunities . I roughly define a c ommunity as a group of things that s hare s ome c ommonality in the mind of s ome pers on or group of people. A lthough a c ommunity does not nec es s arily have to exis t in a phys ic al area, it does have to involve s omething that exis ts in a phys ic al loc ation, even if that is jus t the people that are involved in the c ommunity. M any c ommunities may exis t in the s ame phys ic al area as well. I t all depends on the pers pec tive of the people involved. A bas eball fan may s ee SBC P ark in San Franc is c o as one of the many ballparks in the U nited States , as s hown in Figure 5 - 2 6 . T he manager of a hotel may s ee the ballpark as a highlight of the area around the hotel, as in Figure 5 - 2 7 . With C ommunity Walk, I wanted to give people a way to s hare thes e different pers pec tives , providing different ways to organize and dis play the various things in a c ommunity on a map. I als o wanted to allow the c reator of the map to c onfigure the map to behave exac tly as des ired. T he hotel manager may not want anyone els e to be able to edit the map of the hotel or write c omments on the various loc ations on the map, while the ballpark afic ionado may want to allow c ertain people to edit the map and everyone to add c omments about the various ballparks and bas eball teams that play in thos e parks . C ommunity Walk allows for all this and then s ome. 5.8.2. Getting Started To get s tarted with C ommunity Walk, go to http://www.c ommunitywalk.c om and enter the s treet addres s or latitude and longitude of your loc ation. T his will c reate the initial map and pop up a window to enter in nec es s ary information about the loc ation. I f the loc ation is c los e to where you want it to be, but not exac tly right, you c an move it after you s ave it by c lic king M ove on the window that pops up when you c lic k Save. Figure 5-26. A fan's-eye view Figure 5-27. The hotelier's perspective You will initially have the option of c hoos ing from ten c ategories that des c ribe the loc ation. T he default options for the c ategory are Bus ines s , E duc ation, E ntertainment, G eneral, H otels , P arks , Res idenc e, Res taurants , Shopping, and Trans portation, but thes e c an be c hanged. I n order to c hange them, though, you'll need to c reate a us er ac c ount. You c an do this by c lic king the L ogin link under the righthand panel. You c an als o log in direc tly from http://www.c ommunitywalk.c om. O nc e logged in you will be able to c onfigure everything about the map, inc luding whic h c ategories are available, whic h tabs are available to organize the loc ations on the map, who c an edit the map, whether or not us ers c an make c omments on the loc ations on the map, and s o on. Right after you log in, you will be brought to a page that lis ts all of your maps , allowing you to c onfigure, view, or edit eac h map, and if you s tarted c reating a map before logging in, that map will be available for c onfiguration automatic ally. You c an als o ac c es s this s c reen by c lic king C onfigure M ap on the bottom of the map. 5.8.3. Adding Your Own Locations N ow c omes the fun part: adding loc ations to the map. You c an do this by c lic king A dd M arkers at the bottom of the map. T his pres ents you with three options : By C lic k, By A ddres s , and By L at/L ong. E ac h of thes e offers a different way to put a loc ation on the map, although my preferred manner is By C lic k, as it allows me to quic kly add loc ations direc tly onto the map exac tly where I want them to be. O nc e a loc ation is added, you will be pres ented with the s ame pop- up window that you s aw when you firs t c reated the map. N ow you will be able to c hoos e from the c ategories you des ignated when you c onfigured the map, as well as enter the res t of the information for the loc ation. When entering the des c ription, you als o have the option of us ing s ome s pec ial wiki- like c ommands that allow you to format the text in the des c ription and inc lude links to external web s ites as well as links that c hange the s tate of the map without leaving it. A t the time of this writing, the available c ommands were as s hown in Table 5 - 1 . Table 5-1. Community Walk's wiki-like commands Command Resulting text bold("sample text") sample text italic("sample text") s ample text link("http://www.communitywalk.com", "Community Walk") CommunityWalk internal_link("3wx82-0$j.>23jWKl5%", "Madrid Hotel") Madrid Hotel I n the internal_link c ommand, the firs t parameter 3wx820$j.>23jWKl5 is a s et of direc tions for the map, telling it where to c enter, what loc ation to s how, what pic ture to s how, and s o on. T his value c an be determined by putting the map in the s tate, panning and zooming to the view that you want to s ee, with the pic tures you want to s ee on it, and then s elec ting all of the text after the # s ign in the U RL . I f the U RL in the addres s bar were 2 3 jWKl5 % ">http://www.c ommunitywalk.c om/group? id=3 2 8 #3 wx8 2 - 0 $ j.>2 3 jWKl5 % , the internal_link s tate parameter for that view of the map would be 3wx82-0$j.>23jWKl5%. A t any point you c an go bac k and edit the information for any loc ation by s imply s elec ting that loc ation and c lic king E dit in the window that pops up. You c an als o move the loc ation or delete it by c lic king M ove or D elete, res pec tively. T hes e links will not be available when s omeone is s imply viewing the map. 5.8.4. Adding Photos to the Map O nc e the loc ation has been c reated, you c an add photos to the loc ation by c lic king A dd P hotos from the window that pops up when you s elec t the loc ation (a us er viewing the map will s ee a link for "N o P hotos "). T his will open a window that will allow you to upload photos . T he photos will be automatic ally res ized if they are too big and will be dis played in the order they were uploaded. You c an c hange the order by c lic king Reorder after the photos are dis played and dragging them into their new order. For eac h photo, you c an enter a title and s hort des c ription. T he des c ription c an als o c ontain the s ame c ommands des c ribed for the main des c ription. P ers onally, I us ually don't have my photos named very well on my c omputer. So I prefer to s imply organize the photos that I want to us e for a s pec ific loc ation into a folder on my c omputer, upload all the photos in the folder, dis regarding the order, and then reorder the photos and enter the title and des c ription from the res ulting view, where I c an s ee whic h photo I am dealing with. E ac h loc ation that has photos uploaded to it will have a s mall c amera ic on next to it on the righthand panel. A dditionally, if the map is c onfigured to allow c omments then the righthand panel will have a c omments ic on that will c hange c olor depending on how long ago a c omment was added to the loc ation. L as tly, in addition to allowing for c omments to be left on a map, C ommunity Walk allows people to s hare eac h loc ation they c reate with the c ommunity (or keep them private), is fully integrated with http://del.ic io.us /, and will s oon have an A P I for ac c es s ing all of the s hared loc ation information. T he goal of C ommunity Walk is really to bring people within a c ommunity together in a s pac e that lets them s hare their experienc es . A s enabling as the I nternet is , it almos t s eems to be pulling us away from the phys ic al world around us . H opefully, by adding a dimens ion of the phys ic al world to the I nternet, C ommunity Walk will allow people to better interac t with the c ommunities around them, bringing us bac k into that phys ic al world jus t a bit. Jared Cos ulich Hack 49. Generate Geocoded RSS from Any Google Map Don't tell anyone, but the Semantic Web really is cool. O ne thing that bugs me about G oogle M aps is that, s inc e the A P I is entirely J avaSc ript, the annotation layer in a hac k is only available vis ually and is not mac hine pars eable. I t's unders tandable that G oogle didn't pus h any partic ular geodata file format, as thes e will emerge, but it's frus trating that right now s o muc h c ool data is being c reated as lone s ilos , in an inac c es s ible and un- remixable way. Yet the data is there, in the J avaSc ript and D oc ument O bjec t M odel objec ts c reated by the G oogle M aps A P I . I t s hould be pos s ible to muc k around in there and res c ue that data from its lonely and is olated exis tenc e. T his hac k des c ribes a Firefox J avaSc ript Bookmarklet that pulls point annotation information from many G oogle M ap hac ks and produc es geoc oded RSS. 5.9.1. The Hack T he firs t s tep is to find the GMap objec t in memory, whic h is the key to the G oogle M aps objec t s truc ture. E very page that s hows a G oogle M ap (under the offic ial A P I ) mus t have a line that looks like this : var map = new GMap(document.getElementById("map")); T he bookmarklet as s umes the GMap objec t is a global variable. I f the page c reates the GMap objec t within a func tion, the bookmark will fail. U s er- c reated global variables and methods c an be ac c es s ed by iterating through the global objec t this. Without a J avaSc ript func tion to query an objec t for its us er c reated c las s , the bookmarklet c alls getCenterLatLng( ) on eac h global objec t within a TRy/catch bloc k. I f this c all does not generate an error, the GMap objec t has been found and things c an move forward. T he other as s umption is that overlays are GMarker objec ts that res pond to c lic k events by c alling openInfoWindowHtml(). T his is probably the mos t c ommon way of c ons truc ting a G oogle M ap. Sinc e there is no A P I method to lis t overlays , a J avaSc ript D ata D umper, s uc h as the one at http://www.mattkrus e.c om/J avaSc ript/datadumper/, c an be very us eful to inves tigate the s truc ture of the GMap objec t and find the overlays , without following through the A P I 's obfus c ated c ode. We c an s tart by c reating a bas ic G oogle M ap with overlays and info windows , ac c ording to the doc umentation. N ext, we load in datadumper.j s , s et DumperMaxDepth=2, and c all DumperPopup(map). Setting DumperMaxDepth to a s mall value is c ruc ial, s inc e the G M aps objec t has s elf referenc es and will s end the D umper into an infinite loop. T he dump reveals an array within the GMap objec t c alled overlays. C alling DumperPopup(map["overlays"]) s hows a lis t of objec ts , eac h c ontaining a point property. E ac h GPoint objec t has an x and y value, whic h on ins pec tion are the lat/long loc ation of the overlay. Roc kin'! But what about the overlay c ontent? T hat H T M L exis ts within an anonymous func tion pas s ed to the GEvent.addListener method. T hat func tion is plac ed in the _e_ _click array and is already c ompiled. T he only way to get at that c ontent is to c all the func tion. T he tric k is to c apture the c all to openInfoWindowHtml by c opying the exis ting method at GMarker.prototype.openInfoWindowHtml and replac ing it with our own func tion, whic h c aptures the H T M L argument when reques ted, and otherwis e c alls the original bac ked- up method. Finally, the RSS is produc ed by iterating through the overlays array, grabbing the x and y from the point, exec uting call( ) on the _e_ _click func tion, and wrapping it up within an RSS item element. T he geoc oded RSS is then written to a new window. 5.9.2. The Code T he H T M L below (and online at http://brainoff.c om/gmaps /gmaps .bklet.html) produc es a bookmarklet from this s c ript, whic h c an be c opied to your Firefox toolbar. When viewing a G oogle M ap, c lic k the bookmarklet, and if the map has been produc ed ac c ording to the as s umptions , RSS will be generated. I t's not pos s ible to c hange the c ontent type of a doc ument from J avaSc ript, s o Firefox will render the RSS as H T M L . V iew the s ourc e to s ee the XM L . <html> <head> <script language="Javascript"> gmapref = false; /* Search through Global Objects for the GMap*/ for (objName in this) { obj = this[objName]; try { obj.getCenterLatLng(); gmapref = obj; break; } catch (e) {} } if (gmapref) { /* Capture calls to openInfoWindowHtml, and grab the m GMarker.prototype._openInfoWindowHtml=GMarker.prototyp openInfoWindowHtml; GMarker.prototype.openInfoWindowHtml=function(a){ if (document.capture) { document.desc = a; } else { this._openInfoWindowHtml(a); } }; /* Generate RSS by iterating through overlays, looking capturing info window HTML */ var rss='<?xml version=\'1.0\'?>\n<rss version=\'2.0\' =\'http://www.w3.org/2003/01/geo/wgs84_pos#\'>\n<c var i; for (i=0; i<map['overlays'].length; i++) { try { item = '\t<item>\n\t\t<geo:lat>' + map['overlay + '</geo:lat><geo:long>' + map['overlays'] + '</geo:long>\n\t\t<description><![CDATA[ document.capture = true; document.desc = ''; map['overlays'][i]['_e_ _click'][0].call( ); item = item + document.desc; document.capture = false; item = item + ']]></description>\n\t</item>\n' rss = rss + item; } catch(e) { document.capture = false; } } rss = rss + '</channel></rss>'; /* Write out RSS to a new window */ var w = window.open('about:blank'); w.document.open( ); w.document.writeln(rss); w.document.close( ); } void(0); </script> <script> function buildbookmarklet( ) { var s = document.getElementsByTagName("script"); var script = s[0].innerHTML; script = script.replace(/\n/g, ""); var b = document.getElementById("bookmarklet"); b.innerHTML = "<a href=\"JavaScript:" + script + "\ 0} </script> </head> <body onLoad="buildbookmarklet( )"> <div id="bookmarklet"> </div> </body> </html> Mikel Maron Hack 50. Geoblog with Google Maps in Thingster Share your f avorite places with f riends. I n this hac k, I dis c us s our T hings ter G eoblogging s ervic e and s ome of the details of how I integrated G oogle M aps . We provide T hings ter free of c harge at http://www.things ter.org/, and it is open s ourc e and open data lic ens ed as well. You're welc ome to log in, c reate an ac c ount, and play with it; you're als o welc ome to run your own c opy or jus t take any ideas you like and build your own equivalent. M y own interes t in plac e- tagging c ame from a very s imple des ire: I wanted to be able to s hare information about my favorite plac es with my friends . T he fac t that there are not 1 0 ,0 0 0 c ompanies already doing this has always c ompletely mys tified me. I t s eemed like a perfec tly logic al bus ines s plan if you were s o mindedc ertainly better than, s ay, "pets .c om." I t is pretty obvious that the blogging paradigm is the right way to hang P os t- I t notes in s pac e. P eople already us e blogs in almos t exac tly this way: you own your own blog, you publis h in a formal publis hing framework, and blogs export this wonderful RSS format that is mac hine- readable. Blogs have already been extended to blog pic tures , s ongs , and even video: blogging by loc ation is the next logic al s tep. T he c hallenge in blogging about plac es is that our blogging tools or c ontent management s ys tems need to s upport s ome kind of s atis fying, fas t, and c ompelling map interfac e. T hes e tools need to be as eas y to us e as ordinary blogging tools . A c lever novic e s hould be able to walk up to a mapping s ervic e, c reate an ac c ount, and pos t her firs t geotagged pos t in under a minute. 5.10.1. Enter Thingster I n 2 0 0 4 , Ben Rus s ell and I firs t c onc eived T hings ter as an "anything tool," where one c ould blog about any kind of thing. M aps were the firs t c lear interes t and my good friends Tom L ongs on and Brad D egraf quic kly jumped on board to help play with the idea. We thought that if c ommunity driven maps exis ted, then we c ould s tart to s hare information about our c ommunities more intelligently, and that this might even c hange the way we engage and interac t as c itizens . T his is the s ort of big if that always s eems to be a warning of s everal months of s leeples s nights hac king. L et me point out that thos e of you who haven't had to s uffer in the dark ages before G oogle M aps s imply have no apprec iation of how hard it was to build a c ompelling web mapping s ervic e. I t was uphill with s nows torms both ways and we had to arrive before we left. We had tried s everal other mapping s olutions that were available in the open s ourc e c ommunity and I even pers onally did try to build my own maps erver (whic h is available at http://maps .c ivic ac tions .net). T he labour, time, and ultimate performanc e of rolling our own is c ompletely humbling. We rec ognized jus t how high the bar is s et in what us ers expec t from a web mapping s ervic e. Today G oogle M aps provides us with that las t mis s ing piec e, and not only is T hings ter finally able to artic ulate its vis ion, but s everal other exc iting projec ts , s uc h as http://ning.c om, http://platial.c om, and http://tagzania.c om are als o rapidly beginning to explore the pos s ibilities of eas y ac c es s to a c ompelling web mapping s ervic e. 5.10.2. Adding Maps to Blogs I n the development of my own approac h it bec ame obvious that there are s everal key things that map- bas ed c ontent management s ys tems s hould do: 1. T hey s hould us e tags in a way s imilar to the notable http://del.ic io.us projec t. O rganizing plac e information s eems to be s o diffic ult otherwis e. 2. "P os t to M ap" is c ruc ial. P eople want to interac t with a map when they make a pos t, not try to enter a s treet addres s or a longitude/latitude pair by hand. 3. T here s hould be an opportunity to pos t a c omment with regards to a previous ly plac ed pos t. Rather than ending up with a c loud of pos ts around a res taurant or a s wimming hole, it is important to let people us e dis c overy firs t to prevent c lutter. 4. T here mus t be extens ive pivots . O ne s hould be able to examine a loc ation and s ee all the c omments about that plac e. O r to then look at an author of a partic ular c omment and s ee other pos ts that author might have made about other loc ations . M apping s eems to often imply relations hips to the other people who have that s ame interes t; it makes s ens e to find ways to c reate s ynergy. 5. T he mapping s ervic e has to be fas t and lightweight overall. G oogle M aps more than delivers on this . 5.10.3. Practice C onnec ting G oogle M aps to a blogging tool requires c onnec ting both an input s ide and an output s ide. You want to both c apture G oogle M aps pos ition information for new pos ts , and you want to plot pos ts to G oogle M aps when you are viewing the blog. O n the input s ide, I c onnec ted the G oogle M aps navigation to the form input box. A s you drag G oogle M aps around, it ins tantly updates the us er input form box s o that when the us er finally s ubmits the pos t, the pos t has the map loc ation that they have s ugges ted. T his c ode was quite a s mall bit of J avaSc ript, and it looked s omething like this : var map = null; map = new GMap(mapdiv); map.addControl(new GSmallMapControl()); map.centerAndZoom(new GPoint(-123,45), 6); // REGISTER CHANGES INTO FORM IF FORM EXISTS GEvent.addListener(map, "moveend", function() { var center = map.getCenterLatLng(); var latLngStr = center.y + ' ' + center.x; if( parent.document.form && parent.document.form.locatio parent.document.form.locationinput.value = latLngStr; } }); O n the output s ide, when I want to plot the points in my c ontent management s ys tem to G oogle M aps , I reques t an RSS feed of the partic ular c hannel that the us er wants to plot and s imply plot thos e points . T hat c ode is s lightly larger bec aus e it has to fetc h an XM L doc ument from the s erver (the RSS feed), walk through it, and pos t thos e pos ts into G oogle M aps . You c an us e the GXmlHttp c las s from the G oogle M aps A P I as a means of fetc hing this data on the fly, without having to worry about brows er c ompatibility is s ues . O nc e I have one of my RSS feeds with s ome geo- data in it, I ins truc t G oogle M aps to plot eac h of the points : // ITERATE ITEMS - BUILD MAP WHEN NEEDED var var var var var latmin = 0; latmax = 0; lonmin = 0; lonmax = 0; visited = 0; for(var content = data.firstChild; content != null; conten content.nextSibling ) { if( content.nodeName != 'item' ) { continue; } // get some stuff var title = getfield(content,"dc:title"); var link = getfield(content,"dc:link"); var description = getfield(content,"dc:description var location = getfield(content,"th:location"); if(!location || location.length < 2) { continue; } var var var if( strs = location.split(" "); a = strs[0]; b = strs[1]; a.indexOf('(')>=0) { continue; } var lat = 0; var lon = 0; try { lat = parseFloat( a ); lon = parseFloat( b ); } catch(e) { continue; } a = "" + lat; b = "" + lon; if( a == 'undefined' || a == "NaN" ) continue; if( b == 'undefined' || b == "NaN" ) continue; if( lon == 0 && lat == 0 ) { continue; } a = 1234; // bounds builder if( visited == 0 ) { latmin = latmax = lat; lonmin = lonmax = lon; } else { if( latmin > lat ) latmin if( latmax < lat ) latmax if( lonmin > lon ) lonmin if( lonmax < lon ) lonmax } = = = = lat; lat; lon; lon; var point = new GPoint(lon,lat); var marker = new GMarker(point); var html = title; GEvent.addListener(marker,"click",function() { marker.openInfoWindowHtml(html); } ); map.addOverlay(marker); visited++; } var latc = latmin + (latmax - latmin) / 2; var lonc = lonmin + (lonmax - lonmin) / 2; // should pick zoom better some year map.centerAndZoom(new GPoint(lonc,latc), 13); } 5.10.4. How Do You Actually Use Thingster? I n T hings ter, you firs t c reate an ac c ount and log in us ing the regis ter page at http://things ter.org/regis ter. O nc e you are in your home page, you c an s elec t "pos t" to c reate a new pos t. T he pos t form allows image upload and has an integrated map, as s hown in Figure 5 - 2 8 . Figure 5-28. Thingster image upload with integrated map When you are done pos ting, return to your home page, where you c an s ee a c ompilation of your pos ts and pic tures on a map, as depic ted in Figure 5 - 2 9 . Figure 5-29. Thingster's compilation of your posts and pictures on a map H aving G oogle M aps in T hings ter lets us explore a number of tas ty implic ations we originally thought might exis t. Better maps affec t what we s ee, the c hoic es we make, the reperc us s ions of thos e dec is ions , and perhaps even the s hape of our s oc ieties . O ur goal in providing this s ervic e is to explore s uc h ideas . Ans elm Hook Chapter 6. API Tips and Tricks Sec tion 6 .1 . H ac ks 5 1 6 1 : I ntroduc tion H ac k 5 1 . M ake a Fulls c reen M ap the Right Way H ac k 5 2 . P ut a M ap and H T M L into Your I nfo Windows H ac k 5 3 . A dd Flas h A pplets to Your G oogle M aps H ac k 5 4 . A dd a N ic er I nfo Window to Your M ap with T L abel H ac k 5 5 . P ut P hotographs on Your G oogle M aps H ac k 5 6 . P in Your O wn M aps to G oogle M aps with T P hoto H ac k 5 7 . D o a L oc al Zoom with G xM agnifier H ac k 5 8 . Find the Right Zoom L evel H ac k 5 9 . Show L ots of StuffQ uic kly H ac k 6 0 . M ake T hings H appen When the M ap M oves H ac k 6 1 . U s e the Right D eveloper's Key A utomatic ally 6.1. Hacks 5161: Introduction T he offic ial G oogle M aps A P I makes a lot of things eas y. H ere are s ome hac ks that pus h the A P I in new direc tions and extend the A P I with external libraries . Tric ks s uc h as filling your whole 2 1 - inc h flat panel dis play with a map, c us tomizing your info windows with an embedded map the way the driving direc tions work, and integrating Flas h with your maps . You c an even add c us tom labels and photographs on top of your G oogle M aps . P erhaps this tec hnique reac hes the height of eleganc e (abs urdity? ) when us ed to c ompare the s ize of Burning M an with N ew York's C entral P ark. T he c hapter ends with s everal tric ks to allow you to us e one developer's key for multiple domains and direc tories . D o you really want to manage multiple keys bec aus e you have the domain http://mydomain.c om and you s erve the s ame pages from it and http://www.mydomain.c om? I didn't think s o! Hack 51. Make a Fullscreen Map the Right Way Map too big? Map too small? Flex those pixels into shape! I magine you're the proud new owner of a big, s hiny 2 1 - inc h flatpanel dis play, and you s urf to your favorite G oogle M aps web s iteonly to find it s till c onfines you to a tiny little 3 - inc h- s quare map. I t's an embarras s ment, to s ay the leas t. L ikewis e, think about thos e poor fellows with s mall monitors who are s c rolling until their fingers fall off to get around your gigantic 1 6 0 0 x 1 2 0 0 pixel map. Suc h s ites ought to c ome with warning labels about c laus trophobia. A good G oogle M ap s tretc hes its elf to fit c omfortably on your s c reen. I n this hac k we'll inves tigate a s imple two- s tep approac h to make your map always take up the whole window, then build on the tec hnique to inc lude a fixed right- s ide panel, s imilar to the maps .google.com web s ite. We'll als o point out s ome tric ks to help you avoid c ommon pitfalls that uns us pec ting web developers s tumble into when trying to make auto- s izing maps . 6.2.1. Making a Map Take Up the Full Screen T he firs t s tep is to inc lude the following s tyle dec laration in the head s ec tion of your page. I f your map div is named s omething other than map, you'll need to replac e #map with the appropriate name (e.g., #mymap). <style type="text/css"> html, body, #map { width: 100%; height: 100%; } html { overflow: hidden; } body { margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; } </style> T he width and height dec larations c aus e the map c ontainer to fill the entire doc ument body, and the body to take up all the available window s pac e. M ake s ure you don't have any inline width or height attributes on your map element that c ould override thes e. T he overflow:hidden line hides any s c rollbars the brows er would otherwis e dis play, and the margin and padding lines get rid of the white border that is s hown by default around a doc ument. T his leaves us with a map c ontainer that s tretc hes to fit all the available window s pac e in the brows er (minus that res erved for the toolbars , s tatus bar, etc .). T he G oogle map automatic ally takes up this whole c ontainer when you ins tantiate it, and mos t web developers s top here, thinking all is well. H owever, s omewhat les s obvious is the fac t that the map does n't detec t when its c ontainer has been res izedat leas t, not as of vers ion 1 of the A P I . Res izing a map that is n't aware when its c ontainer s ize c hanges c an produc e s ome mis leading effec ts , whic h you c an s ee by going to http://www.googlemappers .c om/artic les /fulls c reenmap/bad.htm. When you enlarge the brows er window, you'll s ee more of the map revealed and might be tempted to think it is s tretc hing to fit your window. But what you are ac tually s eeing is the "off- s c reen" portion of the maps urrounding tiles that have been preloaded, but aren't s uppos ed to be s howing on your s c reen. I f you open the web page in a very s mall brows er window and then enlarge it enough, you'll run out of off- s c reen tiles and will s tart to s ee the gray bac kground s hown in Figure 6 - 1 . A dditionally, double- c lic king the map will make it pan the point you c lic ked to the old c enter of the window, bas ed on its dimens ions at the time it was c reated. Figure 6-1. A full-screen map done the wrong way To make your map res ize and re- c enter properly, you need to let it know when its c ontainer has res ized. To do this , we make us e of an undoc umented G oogle M aps A P I method c alled map.onResize(), c alling it whenever the window dimens ions c hange. I nc lude the following J avaSc ript c ode, after you c reate your map objec t: if (window.attachEvent) { window.attachEvent("onresize", function( ) {this.map.o window.attachEvent("onload", function( ) {this.map.onR } else if (window.addEventListener) { window.addEventListener("resize", function( ) {this.map.onResize( )} , false); window.addEventListener("load", function( ) {this.map. false); } T his is the final s tep needed to obtain a properly working fulls c reen map. You c an s ee the c omplete implementation of thes e two c ode s nippets at http://www.googlemappers .c om/artic les /fulls c reenmap/default.htm You may want to c hec k there for the mos t up- to- date example of the fulls c reen map. 6.2.2. Adding a Side Panel to the Map I t's eas y to add a fixed- width panel alongs ide an auto- s izing map. H ere we s how the c ode needed for a fulls c reen map with a panel 3 0 0 pixels wide doc ked to the right s ide of the s c reen. Replac e the s tyle dec laration us ed in the head s ec tion with the following one: <style type="text/css"> html, body { width: 100%; height: 100%; } html { overflow: hidden; } body { margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; } #map { margin-right: 302px; height: 100% } #rightpanel { position: absolute; right: 0px; top: 0px; width: 300px; height: 100%; overflow: auto; border-left: 2px solid black; padding: 0px 5px 0px 10px; } </style> T he map's right margin is s et to the width of the panel, plus another 2 pixels to ac c ount for its left border. T he overflow:auto attribute in the right panel c aus es it to s how s c rollbars if the c ontent is too big to fit in the panel. T he border and padding are added jus t to make things look c leaner. I t's important that the padding-top and padding-bottom attributes for the right panel be 0px, or the panel's s c rollbar will extend underneath the window's s tatus bar, as s hown in Figure 6 - 2 . T his has to do with a bottom margin the G oogle M ap A P I internals add below the map, whic h unintentionally makes the brows er think the window c ontent extends s lightly below the s c reen. Finally, in the body s ec tion dec lare your s ide panel right after your map div. <div id="rightpanel"></div> Figure 6-2. The unfortunate effects of including top and bottom side panel padding T hat's all there is to it! You c an fill the s ide panel with any information you'd like. You c an s ee an up- to- date example at http://www.googlemappers .c om/artic les /s idepanel/default.htm, whic h is depic ted in Figure 6 - 3 . Figure 6-3. A properly configured side panel Richard Kagerer Hack 52. Put a Map and HTML into Your Info Windows A dd more context to your inf o windows by including a map and HTML. T here are times you want to inc lude both a map and s ome text in the s ame info window. With a little hac kery you c an get the s ort of effec t demoed at http://mappinghac ks .c om/projec ts /gmaps /map_in_box.html and s hown in Figure 6 - 4 . Figure 6-4. A map and text in the same info window Within the G oogle M aps A P I there is an info window c las s that enables you to c lic k on a point or overlay and get additional information about whatever it was that you c lic ked on. A c c ording to the A P I doc umentation, there are really only two types of methods that c reate info windows . T he firs t type is thos e that take s ome kind of H T M L in one of their arguments , namely openInfoWindow(), openInfoWindowHtml( ), and openInfoWindowXslt( ). T he s ec ond type is really jus t a s ingle method that takes no H T M L as input and produc es a blow- up map of s ome point ins ide of the info window, but nothing els e. T his method is showMapBlowup(). T here are als o times when we need both a map and text in the s ame window. H owever, when we look at the full prototype for the showMapBlowup() method, namely showMapBlowup(point, zoomLevel?, mapType?, pixelOffset?, onOpenFn?, onCloseFn?), we s ee there is no way to ins ert text into a map blowup. H ow do we get a map and text into an info window? When we look at the openInfoWindowHtml( ), we s ee that it has the prototype openInfoWindowHtml(marker, htmlStr, pixelOffset?, onOpenFn?, onCloseFn?), where htmlStr is any s tring of H T M L . Well, s inc e we are us ing a div element to c reate the main map, why not try putting a div element into the htmlStr? A s it turns out, that works almos t wonderfully: GEvent.addListener(testmarker, "click", function ( ) { var text = '<p style="text-align: left">'; text += '<div id="minimap" style="width: 200px; height: 2 text += 'Here is some text.<br>'; text += 'This is a link to <a href= "http://maps.google.com/">Google Maps</a>'; testmarker.openInfoWindowHtml(text); var minimap = new GMap(document.getElementById(minimap)); minimap.centerAndZoom(pt,1); minimap.addControl(new GSmallMapControl( )); }); map.addOverlay(testmarker); H ere pt is a previous ly defined point, and testmarker is a marker that we have to plac e s omewhere. N ote that, if you like, you c an add your own c ontrols to the blow- up map and put it into a different mode (s atellite or hybrid). H owever, there is a problem with all this . I f we c los e the info window and then reopen it, we find that the map is gone! We haven't been able to figure out why this happens , but it turns out that there is a workaround: var count = 0; GEvent.addListener(testmarker, "click", function () { var text = '<p style="text-align: left">'; var whichmini = "minimap" + count; text += '<div id="'; text += whichmini + '" style="width: 200px; height: 2 text += 'Here is some text.<br>'; text += 'This is a link to <a href= "http://maps.google.com/">Google Maps</a> <br>'; text += 'The current value of the infoWindow map testmarker.openInfoWindowHtml(text); var minimap = new GMap(document.getElementById(w minimap.centerAndZoom(pt,1); minimap.addControl(new GSmallMapControl( )); count++; }); map.addOverlay(testmarker); What we have done here is add in a c ounter. E ac h time we open the info window, the c ounter is inc remented by one. So if we put this c ounter into the id for the div element, then eac h time that we open the infoWindow, we will be opening a new div element. N ote that we need to referenc e this new name in the c ons truc tor for the mini- map as well. 6.3.1. See Also P art of the c redit for this s hould go to april@ s yc lo.c om, who c ame up with the idea of putting a div element ins ide of the H T M L in an info window. I c ame up with the c ode that added the c ounter and made it work more than onc e. See the thread at http://groups beta.google.c om/group/G oogle- M aps A P I /brows e_frm/thread/ab3 0 7 5 a8 e9 1 f8 ec f/ for more details . John T. Guthrie Hack 53. Add Flash Applets to Your Google Maps Spice up your Google Map inf o windows with Macromedia Flash animation, and even Java applets. I ntegrating M ac romedia Flas h with a G oogle M ap is a s nazzy way to enhanc e the multimedia experienc e of your web page. A lthough the examples given here are toys , no doubt the intrepid reader c an find U s eful U s es for this s ort of integration in the real world. 6.4.1. Flash in the Info Window A s a firs t s tep, we'll embed a s mall Flas h animation I 've c reated c alled Flas hBit.s wf into the pop- up window of a marker. T he animation is jus t s ome text with a blue ball that bounc es ac ros s it when c lic ked, as s een in Figure 6 - 5 . We're going to us e the openInfoWindowHtml( ) method of the GMarker c las s to add the required H T M L to our doc ument. T he s tring we'll be pas s ing is s tored in a variable c alled flashHtml. flashHtml = '<object classid="clsid:d27cdb6e-ae6d-' + '11cf-96b8-444553540000" ' + 'codebase="http://fpdownload.macromedia.com/pub/' + 'shockwave/cabs/flash/swflash.cab#version=7,0,0,0" ' + + + + + + + + + + + + + + + 'width="128" height="53" id="FlashBit" align="middle '<param name="allowScriptAccess" value="sameDomain" '<param name="movie" value="FlashBit.swf" />' '<param name="quality" value="high" />' '<param name="bgcolor" value="#ffffff" />' '<param name="wmode" value="transparent" />' '<embed src="FlashBit.swf" quality="high" ' 'bgcolor="#ffffff" width="128" height="53" ' 'name="FlashBit" align="middle" ' 'allowScriptAccess="sameDomain" ' 'type="application/x-shockwave-flash" ' 'wmode="transparent" ' 'pluginspage="http://www.macromedia.com/go' '/getflashplayer" />' '</object></center>'; Figure 6-5. Flash animation in a Google Maps info window A lthough the c ode above may look a little c onvoluted, it's really nothing more than a typic al Flas h objec t dec laration. T he object tag is us ed by I nternet E xplorer on Windows platforms , while N ets c ape and I nternet E xplorer for the M ac both us e the embed tag ins tead. M ore information on why you need both tags c an be found in M ac romedia's knowledge bas e at http://www.mac romedia.c om/c fus ion/knowledgebas e/index.c fm? id=tn_4 1 5 0 . T he mos t important parameters are movie and src, whic h s hould both point to the Flas h SWF file. I t's als o important to s et the wmode parameter to TRansparent in both the objec t and embed tags . O therwis e, the Flas h objec t will overlap the map c ontrols when the us er s c rolls the info window under them, as s een in Figure 6 - 6 . T he following s traightforward c ode c reates our map. A marker c alled flashMarker is added to the map and, when c lic ked, it will c all the onFlashMarkerClick() func tion: var map = new GMap(document.getElementById("map")); map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); map.centerAndZoom(new GPoint(-122.07, 37.44), 4); var flashMarker = new GMarker(new GPoint(-122.07, 37.433)) map.addOverlay(flashMarker) GEvent.addListener(flashMarker,'click', onFlashMarkerClick Figure 6-6. Overlap caused by not including the wmode parameter U nfortunately, there's a s light bug in that the Flas h applet c an "jump" out of the window after being c lic ked if it is ins ide the very firs t info window that is opened. You c an s ee the problem by going to http://www.googlemappers .c om/artic les /embedapplets /default.htm and c lic king "Show me the bug." H owever, I 've found that if the map has to be s c rolled to s how the info window, the bug does n't oc c ur. So in the onFlashMarkerClick() handler, I 've put in a s mall hac k that s c rolls the map away from the marker the firs t time openInfoWindowHtml() is c alled. T his way, the G oogle M ap A P I internals will s c roll the map bac k to the marker before opening the info window, and the bug won't oc c ur. var flashFixed = false; function onFlashMarkerClick() { html = '<center><div style="width:200px; font-size:10p + '<br/>Click below to poke the Flash object.</div html = html + flashHtml; if (!flashFixed) { flashFixed = true; // only need to do this once map.centerAndZoom(new GPoint(-122.07, 37.43), 4); } // Now open the real one on top flashMarker.openInfoWindowHtml(html); } 6.4.2. Communication Between Flash and Your Google Map I ntegrating Flas h and G oogle M aps bec omes muc h more interes ting when you get the two talking to eac h other. You c an make us e of the Flas h fscommand( ) method to invoke any J avaSc ript func tion on the page, and us e the SetVariable( ) method in your J avaSc ript c ode to pas s data bac k into your Flas h applet. A c omplete tutorial is available in a Flas h Tec hN ote at http://www.mac romedia.c om/c fus ion/knowledgebas e/index.c fm? id=tn_1 5 6 8 3 #jtfc . You c an als o take a look at my s c uba- diving log at http://www.leapbeyond.c om/ric /s c uba/ to s ee an example of an applic ation that tightly integrates a Flas h web s ite with a G oogle M ap. J us t go into the logbook a few pages and hit one of the map ic ons to get s tarted. 6.4.3. Beyond Flash T he tec hnique des c ribed c an work with other types of objec ts in addition to Flas h files . For example, you c an embed a J ava applet into the info window. Figure 6 - 7 s hows how I us ed Robert J eppes en's D urius J ava applet (available at http://www.durius .c om/) to embed a G oogle logo that ripples with a watery effec t when you pas s the mous e over it. Figure 6-7. A Java applet embedded in a Google Map info window T he s ec ond marker is added after c reating your map: var appletMarker = new GMarker(new GPoint(-122.082667, 37. map.addOverlay(appletMarker); GEvent.addListener(appletMarker,'click', onAppletMarkerCli H ere's the c lic k handler: function onAppletMarkerClick() { html = '<center><div style="width:200px; font-size:10p + '<br/>Move your mouse around the image below ' + 'to poke the Java applet.</div>' + '<div style="width:200px; font-size:8pt"><br/>' + '<em>Note: Clicking it will leave this page</em> // In the html string, create a div containing the app html = html + '<div id="applet" style="width:128px; height:53px; ' <applet archive="DuriusWaterPic.jar" ' + ' width="128px" height="53px" align="bottom" ' code="DuriusWaterPic.class">' + ' <param name="cabbase" value="DuriusWat ' <param name="image" value="GoogleLogo. ' <param name="dotsize" value="3" />' + ' <param name="dim" value="2" />' + ' <param name="noise" value="0" />' + ' <param name="mouse" value="1" />' + ' <param name="delay" value="10" />' + ' <param name="orientation" value="v" /> ' <param name="bg" value="233423" />' + ' <param name="reg" value="43752326" />' ' </applet>' + '</div></center>'; appletMarker.openInfoWindowHtml(html); } You c an s ee all of thes e examples at http://www.googlemappers .c om/artic les /embedapplets /default.htm Richard Kagerer Hack 54. Add a Nicer Info Window to Your Map with TLabel Callouts, inf o windowsanything that can f it on a web pagecan f it on a map. T he early G oogle M aps hac ks s hare a s imilar afflic tion: they s uffer from red pus hpin s yndrome. Sometimes the pus hpins are green. You c an c reate c us tom ic ons , but they are a bit of a c hallenge, and then you jus t get a different little s ymbol. What you (might) want is the ability to c us tomize the map with unique info windows , images , c allouts , and anything els e that s trikes your fanc y. Tom M angan c reated the T L abel extens ion to allow you to embed any D O M objec t (anything that c an appear on a web page) on a G oogle M ap. Figure 6 - 8 s hows Tom's c anonic al example from the T L abel page at http://gmaps .tommangan.us /tlabel.html, with a G oogle s atellite image of two U .S. A ir Forc e SR- 7 1 Blac kbirds and a U - 2 s py plane at the Blac kbird A ir P ark, in P almdale, C A . (For the c urious , this is at 3 4 .6 0 2 9 7 5 N , 1 1 8 .0 8 5 9 2 6 W.) Figure 6-8. SR-71s at the Blackbird Air Park, with TLabel annotations C allouts identify eac h plane. T he numbers are links to s ites that have more information on eac h plane. T here is als o a thumbnail image that was taken from ground level. T he image has a tool tip that reads "C lic k for larger." Surpris ingly, c lic king on that link leads to a larger image of that thumbnail. 6.5.1. Using TLabel T he T L abel page is at http://gmaps .tommangan.us /tlabel.html. T here is a link to a J avaSc ript file, c urrently http://gmaps .tommangan.us /tlabel.1 9 .js , but c hec k for the c urrent vers ion. C opy that file onto your own s erver and inc lude it after you inc lude the G oogle M aps A P I . <script src="http://maps.google.com/maps?file=api&v=1&key =AOJVHiMoLlyAv…x3sA" type="text/javascript"></script <script src="tlabel.10.js" type="text/javascript"></script N ow, c reate s ome objec ts ! You c ontrol the T L abel objec t by c reating a new objec t and then s etting the properties . T here is a demo of s ome T L abel tric ks at http://mappinghac ks .c om/projec ts /gmaps /brc _tlabel.html. H ere is c ode to c reate a label, as s hown in Figure 6 - 9 : var label = new TLabel(); label.id = 'mail_box'; label.anchorLatLng = new GPoint (-119.226396, 40.768080); label.anchorPoint = 'bottomLeft'; label.content = 'Mail Box'; label.percentOpacity = 85; map.addTLabel(label); Figure 6-9. Black Rock City, annotated with TLabels Firs t, the c ode dec lares the variable named label to hold the newly c reated T L abel objec t. N ext, we s et the id of the T L abel. T he id is vital! I t mus t be unique. I t is eas y, and c atas trophic , to end up with a duplic ate label (where catas trophic means it does n't work). T he anchorLatLng is a GPoint objec t, i.e., the loc ation where this objec t is anc hored to the earth. T he anchorPoint defines whic h part of the c ontent will touc h the anc hor lat and long. I n this c as e, bottomLeft means that the bottom- left c orner of our marker hits the point in the anchorLatLng. T he c hoic es are topLeft, topCenter, topRight, midRight, bottomRight, bottomCenter, bottomLeft, midLeft, or center. T he default is topLeft. T he content c an be anything that c an fit on a web page! I n this c as e, we us e the words "M ail Box." Table 6 - 1 s ummarizes thes e properties . O nc e you have c reated the T L abel objec t and s et the properties , there are four us eful methods : add the objec t to your map with map.addTLabel(label), remove it with map.removeTLabel(label), move it around with label.setPosition(GPoint), or c hange its opac ity (1 0 0 % means you c an't s ee through it at all) with label.setOpacity(percentage). Table 6-1. Useful properties of the TLabel object Property id Description Spec ifies an I D for the label objec t. T his I D is required and mus t be unique for eac h label you embed. T he I D is expos ed to the D O M , s o you c an dynamic ally adjus t the label's s tyle if you c hoos e. anchorLatLng anchorPoint T he longitude and latitude where the anchorPoint will be pinned to the map. Takes a GPoint objec t. T he point on your embedded objec t that will be pinned to anchorLatLng. anchorPoint ac c epts the following values : topLeft, topCenter, topRight, midRight, bottomRight, bottomCenter, bottomLeft, midLeft, and center. T he default is topLeft. content T he XH T M L c ode defining the element you wis h to embed. A number between 0 and 1 0 0 inc lus ive, percentOpacity determining the opac ity of the image. D efault is 1 0 0 , i.e., c ompletely opaque. You c an replac e the c ontent with s omething more elaborate. T his implements an onMouseOver event; s o moving the mous e over the image pops up more information (i.e., a tool tip). label.content = '<img src="images/blank.png" alt="" style="width: 12px; height: 20px;" onmouseover="showFlo onmousemove="floatCoords(\'sInfo\',event);" onmouseout="hideFloat(\'sInfo\');" />'; I t is all a ques tion of c ontrolling what is in the content variable. You c an put the whole thing into one s tring or s plit it ac ros s lines . I f you s plit it, you need to remember to terminate eac h line of a multiline s ec tion with a quote or you'll get an "unterminated s tring literal" mes s age. C hec k out Tom's s ite at http://gmaps .tommangan.us / for more nifty hac ks . written with as s is tance from Tom Mangan Hack 55. Put Photographs on Your Google Maps Treat photographs as map layers and add them to your Google maps. While figuring out how to lay my own images into the G oogle M aps interfac e, I ended up with s ome pretty us eful J avaSc ript, s o I bundled it up as a tightly integrated extens ion to the offic ial A P I . T he res ult is T P hoto. T P hoto allows you to embed alternate aerial photographs ins ide your G oogle M aps . T he added photos pan and zoom along with the main map view, without interfering with any c lic ks on the map. Figure 6 - 1 0 s hows an example of an aerial photo of G room L ake from 1 9 5 9 overlaid over the G oogle Satellite imagery. Figure 6-10. Groom Lake, 1959 G room L ake. D reamland Res ort. Watertown. T he Ranc h. For s uc h a s ec retive plac e, people c ertainly know it by a lot of names ! T he image in Figure 6 - 1 0 c omes from my A rea 5 1 page at http://gmaps .tommangan.us /groom_lake.html. Figure 6 - 1 1 s hows a 1 9 6 8 image over the G oogle Satellite imagery. You c an add the ability to overlay photos onto your own G oogle M aps by ins talling the T P hoto extens ion. D ownload the T P hoto library from http://gmaps .tommangan.us /tphoto.html/. T he c urrent vers ion is tphoto.16.j s , available at http://gmaps .tommangan.us /tphoto.1 6 .js . P lac e it on your s erver and inc lude it after you inc lude the G oogle M aps A P I in your J avaSc ript. You c ould inc lude it direc tly from the tommangan.us s erver, but it is on very rare oc c as ions not available, s o I rec ommend you download the file to your own s erver and link it as s hown here: <script src="http://maps.google.com/maps?file=api&v=1&key= type="text/javascript"></script> <script src="tphoto.16.js" type="text/javascript"></script T here are two ways to us e T P hoto. I n the firs t method, you s upply the lat/long of the top left and bottom right c orners of your image. I n the s ec ond method, you s upply a s ingle lat/long anc hor point, the bas e zoom level, and the dimens ions of your image. T he firs t method looks like: var groom1959 = new TPhoto(); groom1959.id = 'groom1959'; groom1959.src = 'images/groom1959.jpg'; photo.percentOpacity = 50; groom1959.anchorTopLeft = new GPoint(-115.823107,37.248368 groom1959.anchorBottomRight = new GPoint(-115.801649,37.23 map.addTPhoto(photo); Figure 6-11. Area 51 in 1968, over Google Satellite imagery H ere is one way to c reate a button that will s how and hide the overlaid image. T his would appear in an H T M L form button. <input type="button" value="show 1959" id="show1959" onCli T he button c alls the showImage() J avas c ript method. T he variable show s erves as a toggle. I t s tarts at 0 (i.e., don't s how the image) and flips s tate eac h time the button is c lic ked. E ither the addTPhoto method or the removeTphoto method will be c alled depending on the value of show. T he text dis played on the button is als o toggled from "s how 1 9 5 9 " to "hide 1 9 5 9 ." var show = 0; function showImage() { show = 1-show; if (show == 1) { map.addTPhoto(groom1959); document.getElementById('show1959').value } else { map.removeTPhoto(groom1959); document.getElementById('show1959').value } } T he s ec ond approac h takes different parameters : photo = new TPhoto(); photo.id = '[id]'; photo.src = '[src]'; photo.size = new GSize(width,height); photo.baseZoom = [zoomLevel]; photo.percentOpacity = [percent]; photo.anchorPx = new GPoint(x,y); photo.anchorLatLng = new GPoint(lng,lat); map.addTPhoto(photo); T here are only a few methods you need to us e with T P hoto. TPhoto() T he c ons truc tor, whic h c reates a new photo ins tanc e. Takes no parameters . T he extens ion adds two methods to the G M ap objec t: addTPhoto (photo) A dds the given photo to the map. removeTPhoto (photo) Removes the given photo from the map. setOpacity (percentOpacity) D efines the des ired opac ity of the embedded image. percentOpacity is a number from 0 to 1 0 0 , inc lus ive. Setting opac ity allows you to s ee through the overlaid image to the bas e layer. I t allows you to do things like c ompare then and now imagery as s hown in Figures 6 - 1 2 and 6 - 1 3 . T hes e are aerial views c omparing the overlaid 1 9 9 4 U SG S photo over the G oogle aerial imagery. T he firs t image s hows the G oogle A erial bas e layer view with the 1 9 9 4 photo overlaying it and s et to 2 0 % opac ity. You c an s ee through the older image to how things are now (where now is when the image was taken). T he right view is at 1 0 0 % opac ity. I n the left image you c an s ee buildings that didn't exis t in 1 9 9 4 . T he two Blac kbirds are a c ons tant. Figure 6 - 1 3 is an image of the Blac kbird A irpark in P almdale, C alifornia from the Blac kbird Sighting page at http://gmaps .tommangan.us /blac kbirds .html. T he Blac kbirds map was my firs t G oogle M aps projec t. Soon after the A P I was releas ed, I found mys elf in need of a projec t that would enable me to go about breaking maps . A s it happened, I had jus t read about Robb M agley's s earc h for the c ras h s ite of one of the Blac kbirds and thought it would be fun to find out where all of them are now. T his is the kind of applic ation that G oogle M aps has made pos s ible! Tom Mangan Figure 6-12. Blackbirds at 20% opacity Hack 56. Pin Your Own Maps to Google Maps with TPhoto Georef erence your own maps and then pin them anywhere. T he firs t time I vis ited N ew York C ity from the Bay A rea, I was exc ited to s ee everything, all at onc e. I figured that M anhatten is s mall, about 1 0 1 /2 miles from tip to tip, and the boroughs are jus t a bit larger. H ow long c ould it take to go 1 0 miles ? A temporary N ew Yorker friend told me, "You c an think of M anhattan as being the whole Bay A rea. Sure you c an drive from P alo A lto to San Franc is c o, ac ros s to O akland and down the E as t Bay to San J os e, but would you? M anhattan is phys ic ally s maller, but in terms of travel times it is s imilar." We c an us e T P hoto [Hack #55] to take an image of one plac e and c enter it in another. A t http://www.mappinghac ks .c om/projec ts /gmaps /brc _ref.html you s ee the G oogle aerial photo of the s ite of the Burning M an fes tival in the Blac k Roc k des ert of N evada. I f you c lic k "s how plan," you'll get the 2 0 0 5 Burning M an c ity plan overlaid on the G oogle M ap as s hown in Figure 6 - 1 4 . Figure 6-13. Blackbirds at 100% opacity But you don't have to overlay the c ity plan on the G oogle M ap in the proper plac e! You c an s c roll the map to another area and then c lic k on a point to overlay the c ity map on that point. Figure 6 - 1 5 s hows a hypothetic al Burning A pple fes tival c entered on 7 9 th Street in the middle of C entral P ark. I t is interes ting that M anhattan is oriented nearly the s ame way as the P laya, from s outhwes t to northeas t, and the Fes tival c overs about two- thirds of the width of M anhattan. T he M etropolitan M us eum of A rt ends up more or les s by the L arge Sc ale Sound ins tallations . T he dis tanc e from C enter C amp to the perimeter fenc e is about 2 7 c ity bloc ks from 7 2 nd Street to 9 9 th Street. A nd moving out a few zoom levels leaves us in awe at how tremendous ly big and dens e an experienc e it is to be in N ew York. Taking it home, way home to Sebas topol, and c entering on O 'Reilly, gives us the res ults in Figure 6 - 1 6 . T his was produc ed with the s ingle- point method of T P hoto [Hack #55]. T his makes T P hoto work as a s imple georeferenc ing tool. G eoreferenc ing is the ac t of mapping the pixel s pac e of an image to a c oordinate s ys tem that is pegged to the earth's s urfac e. Figure 6-14. Black Rock City in its proper place You need to provide the image s ize, zoom level, and a s ingle point. But we c an c hange the properties of a TImage objec t dynamic ally. A s an example, let's georeferenc e the Blac k Roc k C ity 2 0 0 5 P lan. You c an download the 6 5 KB P D F image from http://www.burningman.c om/preparation/maps /0 5 _maps /. Firs t c onvert the P D F to a J P E G . You c an do this in any imageproc es s ing tool. I f you have I mageM agic k ins talled, this c ommand works : convert brc_2005.pdf brc_2005.jpg N ext, you need to find the pixel c oordinates of a rec ognizable point. I us ed the G I M P to edit the image. P hotos hop would als o work. O pen the image, then zoom in and plac e the c urs or right over the M an. I get x=9 1 7 , y=9 6 3 . A ls o note the height and width of the image: 1 8 3 3 x 2 2 7 4 . Finally, you need to rotate the image s o that N orth is up. I us ed the rotate tool to align the grids with the N orth arrow. I t was a - 3 7 degree rotation. T his is the c ore c ode that overlays the image: var brc = new TPhoto(); brc.id = 'brc'; brc.src = 'images/brc_2005_rotate.jpg'; brc.size = new GSize(2032, 2432); brc.baseZoom = 1; brc.percentOpacity = 40; brc.anchorPx = new GPoint(1110, 948); brc.anchorLatLng = new GPoint(-119.23616409301758,40.75427 Figure 6-15. Black Rock City centered on Central Park T his loads the image images /brc_2005_rotate.j pg and c enters it s o that the x,y pixel c oordinate maps to the pas s ed lat/long. You c an adjus t the Gsize (s pec ified in pixels ) and baseZoom s o that the dis played image takes up the right amount of s pac e. T his happens automatic ally with the two- point us e of T P hoto. You c an c hange the opac ity of the overlaid image [Hack #55]. T his H T M L defines two buttons that inc reas e and dec reas e the photo opac ity when they are c lic ked: <input type="button" value="opacity +" id="opacityup" onClick="changeOpacity(10);"> <input type="button" value="opacity -" id="opacitydown" onClick="changeOpacity(-10);"> When the buttons are c lic ked, either +10 or 10 is pas s ed to the changeOpacity method: Figure 6-16. Black Rock City centered on O'Reilly Media function changeOpacity (z) { var temp = brc.percentOpacity; temp += z; if (temp > 100) { temp = 100; } if (temp < 0) { temp = 0; } map.removeTPhoto(brc); brc.percentOpacity = temp; map.addTPhoto(brc); document.getElementById('opacity').value = brc.per } T his routine attempts to inc reas e or dec reas e the opac ity by the pas s ed +1 0 or - 1 0 and then c hec ks that the opac ity is not greater than 1 0 0 or les s than 0 . A s s uming it is within range, it removes the photo from the ac tive map, s ets the opac ity to the new value, and then redis plays the image and updates the dis played opac ity. T he showImage method is c alled when the us er c lic ks "s how plan," and is even more s imple: function showImage() { show = 1-show; if (show == 1) { map.addTPhoto(brc); document.getElementById('showplan').value } else { map.removeTPhoto(brc); document.getElementById('showplan').value } } T he variable show s erves as a toggle. I t is initially s et to 0, and then the line show=1-show toggles it between 1 and 0. When it is 1 the photo is dis played and when it is 0 the photo is hidden. Hack 57. Do a Local Zoom with GxMagnifier Context is key: GxMagnif ier lets you choose the appropriate context. T he zoom feature on G oogle M aps is nic e, exc ept when you want to s ee a zoomed out view s o that you have s ome c ontext and yet s till s ee detail. T he normal c artographic ans wer to that c onundrum would be that you are out of luc k. L uc ky for us , this is no ordinary c artographic environment! 6.8.1. The Hack G xM agnifier is a free add- in c ontrol for G oogle M aps that c reates a moveable, magnified window on top of your map. Figure 6 - 1 7 s hows G xM agnifier in ac tion. Figure 6-17. GxMagnifier's "Hello World" D oes this look like an ordinary G oogle M ap to you? C lic k the magnifier ic on in the top- left c orner of the map. N ow, wherever you go on the map, you get a magnified view. T his feature c an be us ed with a mere two lines of c ode. L ike a lot of J avaSc ript libraries , you firs t load it: <script src="GxMagnifier.1.js" type="text/javascript"></sc T hen, add the c ontrol in your c ode: map.addControl(new GxMagnifierControl()); N ote that we're pas s ing a c us tom c ontrol objec t to the s tandard map.addControl A P I c all. T his is all you need to do to get the bas ic magnifier c ontrol. T his is only the mos t bas ic example of what G xM agnifier c an do! T he full doc umentation, with c omplete referenc e to the A P I c an be found here: http://www.googlemappers .c om/libraries /gxmagnifier/doc s /default. 6.8.2. Doing More with GxMagnifier I n our s imple example we ins tantiated the GxMagnifierControl objec t within our map.addControl() c all: map.addControl(new GxMagnifierControl()); T his is a dead s imple approac h, but it does n't allow us to c ontrol the GxMagnifierControl later on. G xM agnifier c an do more for us ! T he next examples will s tart with this bas ic framework, with the c ruc ial lines highlighted. O f c ours e, you'll need to us e your own developer's key. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>GxMagnifier Example Framework</title> <script src="http://maps.google.com/ maps?file=api&v=1&key=ilovemykidsmandms" type="text/javasc <script src="GxMagnifier.1.js" type="text/javasc </head> <body> <div id="map" style="width: 300px; height: 300px <script type="text/javascript"> //<![CDATA[ if (GBrowserIsCompatible( )) { var map = new GMap(document.getElementById("ma map.centerAndZoom(new GPoint(-122.4618, 37.790 // Create the magnifier var magControl = new GxMagnifierControl( ); map.addControl(magControl); // Get reference to the associated GxMagnifier var mag = magControl.GxMagnifier; // …rest } //]]> </script> </body> </html> of the example goes here… T hat looks like a long example, but it is s imilar to the G oogle M aps "H ello World" example, with the addition of thes e lines : var magControl = new GxMagnifierControl(); map.addControl(magControl); var mag = magControl.GxMagnifier; T his defines the variable magControl, whic h we c an us e to s et attributes , and then adds the c ontrol to the map. T he GxMagnifierControl c las s is jus t a wrapper, as mos t of the time we'll be ac c es s ing its related GxMagnifier objec t by reading the GxMagnifierControl.GxMagnifier property into the variable mag. What c an you do with magControl now that you have it? M any things ! 6.8.2.1. Zooming. G xM agnifier automatic ally adjus ts its zoom level as your main map is zoomed. H ere we make it magnify by 3 zoom levels , ins tead of the default 2 . mag.setMagnification(3); You c an als o s et a negative zoom level, whic h is us eful in c onjunc tion with docking, as des c ribed below. 6.8.2.2. Resizing. By default, the magnified viewport is one third the s ize of your main map. You c an c hange its dimens ions . mag.setSize(new GSize(150, 80)); 6.8.2.3. Capturing the cick. You may not want your magnifier to zoom in on the map when the us er c lic ks it. H ere we override the c lic k event to tell us where we c lic ked and then c los e the magnifier window. You c an us e GEvent.bind( ) for more s ophis tic ated handling. mag.disableDefaultClickHandler( ); GEvent.addListener(mag, "click", function(point){ alert("You clicked " + point.toString( )); this.hide( ); // note, "this" is the GxMagnifier insta }); 6.8.2.4. Moving the button. H ere we plac e the magnifying glas s button 1 0 pixels from the top right c orner. N ote that GxMagnifierControl.setDefaultPosition( ) has to be c alled before adding the c ontrol to the map. var magControl = new GxMagnifierControl( ); magControl.setDefaultPosition(new GxControlPositionHack(1, map.addControl(magControl); 6.8.2.5. Automatically panning. T he magnifier c an s c roll the map when it gets moved near an edge. N ote the panning region extends inward from the edges of the main map by half the s ize of the magnifier window. mag.enableAutoPan(); 6.8.2.6. Docking. You c an free the magnifier from the map's c ontainer and put it anywhere on the page. We do this by c reating a GxMagnifier ins tanc e direc tly and telling it to us e our own H T M L div element. H ere's a fulls c reen map, with the magnifier doc ked to the bottom right c orner. T he example deviates a bit from our typic al ones . I ns ide the head element, we define s ome c us tom C SS s tyles for the page, the map, and our magnifier dis play: <!-- Set up the containers, and make a "fullscreen" window <style type="text/css"> html, body {width: 100%; height: 100%} body {margin-top: 0px; margin-right: 0px; margin-left 0px} #map {position:absolute; width:100%; height:100%} #magnifier {position:absolute; right:0px; bottom:0px; wi 200px; border:2px solid; border-bottom-style:outset} </style> I n the body, we add H T M L div elements for the map and the magnifier: <div id="map"></div> <div id="magnifier"></div> A nd, finally, here's the J avaSc ript: // Create the magnifier var div = document.getElementById("magnifier"); div.style.zIndex = 10; // make it stay on top var mag = new GxMagnifier(map, null, div); mag.map.setMapType(G_SATELLITE_TYPE) // Monitor the window resize event and let the map know wh // This isn't required for GxMagnifier, but it is required // a correct fullscreen Google Map. if (window.attachEvent) { window.attachEvent("onresize", function( ) {this.map.onR } else { window.addEventListener("resize", function( ) {this.map. false); } N ote the line: mag.map.setMapType(G_SATELLITE_TYPE) T he doc ked map in the c orner s hows the s atellite imagery that c orres ponds to the point of the mous e, as s hown in Figure 6 - 1 8 . You c an find out more about this feature at http://www.googlemappers .c om/libraries /gxmagnifier/doc s /exampl Figure 6-18. Magnifier docked with a satellite view 6.8.2.7. Multiple magnifiers and negative zoom. You c an inc lude multiple G xM agnifiers on your map. Figure 6 - 1 9 expands on the previous example on doc king, and us es a negative magnific ation fac tor to c reate a doc ked "birds eye view" of where you are on the map. See it in ac tion at http://www.googlemappers .c om/libraries /gxmagnifier/doc s /exampl I n c as e you're c urious , I got the idea of trying to make a magnifier c ontrol for G oogle M aps after watc hing a c onc ept video that s hows a s imilar feature in mapping tec hnology demons trated under Windows L onghorn (a.k.a. V is ta). Figure 6-19. An orientation map and a magnified map 6.8.3. See Also G xM agnifier is not s upported by G oogle or part of its offic ial A P I , and it is beta s oftware, s o there may be s ome bugs . I f you run into anything, report it in the G oogle- M aps - A P I forum. I try to keep an eye on mes s ages there, but c hanc es are one of the other members will be able to res pond with a fix fas ter than I c an. T he G xM agnifier doc umentation page has muc h more detail and lives at http://www.googlemappers .c om/libraries /gxmagnifier/doc s T he G oogle M appers c ommunity is a good plac e to find out more about c us tom G oogle M aps A P I extens ions : http://www.googlemappers .c om/. Richard Kagerer Hack 58. Find the Right Zoom Level You've got some points to show on a map. How do you pick the right zoom level to show them all at once? T he G oogle M aps A P I is powerful but, as tends to be the c as e for s uc h toolkits , has s ome omis s ions and inc onvenienc es . For example, in many real- world mapping problems , it's c ommon to have a s et of points or lines that we wis h to dis play on a map. Typic ally, we c hoos e the outer four c orners , or extents , of the map to matc h the bounding box of the data, whic h is given by the minimum and maximum x and y c oordinates in our data s et. By s elec ting the map extents to matc h the bounding box of the data, we c an guarantee that everything we want to s how s hould be vis ible in the map dis play. T he bounding box of a data s et is us ually very eas y to c alc ulate. O ne way to do s o is to s imply iterate through the data s et, looking for the larges t and s malles t c oordinates in both dimens ions . T he problem is that the G oogle M aps A P I does n't give us any way to s et the map extents bas ed on a bounding box. I ns tead, the A P I exports a centerAndZoom( ) method that ac c epts a c enter point of the map, expres s ed as a latitude and longitude pair, and a zoom level. G oogle doc uments the zoom level as an integer, and the examples in their doc umentation all us e 4 as the zoom level, but no definition of the zoom levels thems elves is given. E xperimentation s hows that they c orres pond with the tic ks on the zoom level c ontrol. O ur ques tion is then very s imple: given a bounding box, how does one determine an appropriate c enter and zoom level, s o that our data is guaranteed to appear on the s c reen, regardles s of s c reen geometry? 6.9.1. The Brute Force Method O ne approac h is to look at the c urrent map geometry and s ee if the s c reen will hold the bounding box and keep zooming in or out as needed. T he zoom levels are approximately powers of two, s o it's prac tic al to us e a s ort of brute- forc e method, and jus t multiply or divide the c urrent level by two, and s ee if it s till fits . T he following J avaSc ript does jus t that: function computeZoom(minX, minY, maxX, maxY) { var zl; var bounds = map.getBoundsLatLng(); var cz = map.getZoomLevel(); var mapWidth = Math.abs(bounds.maxX - bounds.minX); var mapHeight = Math.abs(bounds.maxY - bounds.minY); var myWidth = Math.abs(maxX - minX); var myHeight = Math.abs(maxY minY); var changeZoom = myWidth > mapWidth ? 1 : -1; // Just rip through until we find the lowest that will h // For certain geometries (around hemisphere boundaries) for(zl=map.getZoomLeve( );zl> 2&&zl<17; zl += changeZoom) width = width * Math.pow(2, changeZoom); height = height * Math.pow(2, changeZoom); if ((width < lon) || (height < lat)) return zl - 1; } return zl; } T his makes s etting that c enter point and zoom level very s imple: centerLat = (minLat + maxLat) / 2; centerLon = (minLon + maxLon) / 2; var zl = computeZoom(minLon, minLat, maxLon, maxLat); map.centerAndZoom(new GPoint(centerLon, centerLat), zl); 6.9.2. The Analytic Method H owever, we c an s implify this approac h even further. E mpiric ally, we note that at zoom level 1 7 , the res olution of the map is 1 .4 6 0 2 5 degrees of longitude per pixel. Similarly, we c an obs erve that this res olution halves for eac h s ubs equent zoom level, and that this s eems to be invariant for the x axis of the map. For the y axis of the map, this property applies to lower zoom levels of the map, but not the higher zoom levels , bec aus e ins tead of wrapping the map, blank s pac e is s hown above and below the poles . N evertheles s , as a firs t approximation, we c an c alc ulate what the res olution of our map ought to be, given the dis play geometry of the map in pixels and a bounding box, to get a map that c overs the whole box. We c an exploit this relations hip by taking the logarithm of the ratio of 1 .4 6 0 2 5 to our des ired res olution to the bas e 2 , and then s ubtrac ting this value from 1 7 . T he following J avaSc ript performs this operation: function calculateZoom2 (minX, maxX, minY, maxY) { var mapElement = document.getElementById("map"); var degLonPerPixel = Math.abs(maxX minX) / parseInt(m var degLatPerPixel = Math.abs(maxYminY) / parseInt(map var resolution = Math.max( degLonPerPixel, degLatPerPi return Math.ceil( 17 - Math.log(1.46025 / resolution) } Sinc e the J avaSc ript Math.log( ) returns the logarithm to the bas e e, we us e the mathematic al relations hip loga(x) = logb(x) / logb(a) in the c ode example above to obtain the logarithm to the bas e 2 . Similarly, we us e Math.ceil() to find the s malles t integer greater than or equal to the res ult, to ens ure that the res ulting map is at leas t as large as our bounding box. A s for the differenc e in res olutions between the x and y axes for the higher zoom level, we obs erve empiric ally that the maximum res olution for the y axis at any zoom level is s maller than the res olution of the x axis at zoom level 1 5 . A t zoom level 1 5 , the entire world is s till s hown north to s outh, s o this won't be a problem either. T he main advantage of this method is that, unlike the brute forc e method, it c an be applied on the s erver s ide as well as the c lient s ide. T he c orres ponding bit of P erl c ode from a C G I s c ript might look like this : my $zoom = int( 17 log(1.46025 / $resolution) / log(2) ) T his approac h requires a little bit les s c ode than the brute- forc e method, and it feels a lot more elegant. T he dis advantage, of c ours e, is that it relies on hardc oded c ons tants that c ould break if G oogle dec ides to c hange the s emantic s of its zoom levels without warning, though this s eems unlikely at the moment. 6.9.3. The Undocumented API Method O f c ours e, G oogle probably needs its own method to determine the right zoom level right? A s it happens , the 1 .0 vers ion of G oogle M aps A P I does provide s uc h a method, albeit an undoc umented one. T he following c ode makes us e of this undoc umented method: var center = new GPoint( (minX + maxX) / 2, (minY + maxY) var span = new GSize( maxX - minX, minX minY ); var zoom = map.spec.getLowestZoomLevel(center, span, map.v map.centerAndZoom(center, zoom); T his method may be the s imples t of all, but it relies on two pres ently undoc umented features of the G oogle M aps A P I : the map.spec.getLowestZoomLevel( ) method and the map.viewSize property. U s ing them runs an even higher ris k than the other two methods that your c ode will break at s ome point, s hould G oogle alter its A P I . H owever, we won't be at all s urpris ed if G oogle dec ides to doc ument this method, or methods like it in future releas es . Read more about this is s ue on the G oogle G roups thread at http://xrl.us /getL owes tZoomL evel. O ne final thought: all thes e methods try to find the optimal matc h between the s upplied bounding box and a c orres ponding zoom level. I f your bounding box area s hould happen to matc h a zoom level exac tly, this might not be what you want, bec aus e the outliers of your data s et will be dis played at the very edge of the map. For this reas on, it might be s mart to expand the width and height of your bounding box by, s ay, 1 0 % , to ens ure that not only is everything dis played on the map, but everything is dis played well within the map. Robert Lipe Hack 59. Show Lots of StuffQuickly Lots of Google Maps overlays means lots of time spent waiting f or them to draw on the mapunless you're smart. When dealing with nontrivial numbers of overlays to draw on a G oogle M apas in more than a hundred or s o markers or vertic es in a polylinethe drawing time required for a GMap objec t bec omes really notic able. T he inc lination is to want to s how markers as quic kly as pos s ible, s o that the us er gets immediate feedbac k on what's going on, but it's been dis c overed that if you buffer the objec ts and then manually trigger the redraw, it is muc h fas ter. 6.10.1. The Code We c an ac c omplis h this buffering by adding a c us tom method of our own to the G oogle M aps A P I , whic h we'll c all addOverlays( ). By as s igning it to the GMap c las s prototype, it bec omes available on any GMap objec ts we c reate. T he c ode looks like this : // This is a bit of a trick for the 1.0 API. The 'addoverl // is agonizingly slow, so we buffer up the markers in the // array and then deliver them to GMAP in one shot. GMap.prototype.addOverlays=function(a) { var b=this; for (i=0;i<a.length;i++) { try { this.overlays.push(a[i]); a[i].initialize(this); a[i].redraw(true); } catch(ex) { alert('err: ' + i + ', ' + ex.toSt } } this.reOrderOverlays(); } T he addOverlays() method c an be us ed direc tly in your c ode or inc luded via a script element in your H T M L , after you inc lude the G oogle M aps library. U s ing this tec hnique is really eas yins tead of c alling map.addOverlay( ) for eac h marker or polyline we c reate, we'll pus h eac h overlay onto an array, and then pas s the array to map.addOverlays( ). H ere's a fragment of a s imple G P X reader that dis plays waypoint data us ing this idea: var wpts = GPX.documentElement.getElementsByTagName("wpt" var markers = []; for (var k = 0; k < wpts.length; k++) { var point = new GPoint(trkPts[k].getAttribute("lon") trkPts[k].getAttribute("lat") var marker = new Gmarker(point); // … we could do things with the marker here, // like set a custom icon or configure an info windo markers.push( marker ); } // Now let gmap have the waypoints all in one chunk. map.addOverlays(points); I n a s imilar fas hion, if you have multiple c ontiguous lines to draw, it's s marter to c ompres s them all into a s ingle polyline, rather than as k the GMap objec t to render eac h one s eparately: // Coalesce each GPX trk/trkseg/trkpts section into a sing // Each trkseg is a different object so that the lines don // glommed together. var tracks = GPX.documentElement.getElementsByTagName("trk var trkpts = [], polylines = []; for (var i = 0; i < tracks.length; i++) { var trkSeg = tracks[i].getElementsByTagName("trkseg"); for (var j = 0; j < trkSeg.length; j++) { var trkPts = trkSeg[j].getElementsByTagName("trkpt"); for (var k = 0; k < trkPts.length; k++) { trkpts.push(new GPoint(trkPts[k].getAttribute("lon") trkPts[k].getAttribute("lat") } polylines.push(new GPolyline(trkpts, trkcolor, 5)); trkpts = []; } } map.addOverlays(polylines); I n tes ting one G P X file with 1 ,7 0 0 trac kpoints , us ing this tec hnique reduc ed the time required to dis play from 4 8 s ec onds to 6 s ec onds . Be c areful not to get c arried away with this idea, as lines will be drawn between every point in a s ingle GPolyline. I f your intent is to pres erve breaks in the drawn line, be s ure to pres erve them as multiple GPolyline objec ts . A dditional optimizations are pos s ible. For example, are all thos e trac k- points really nec es s ary? Tools s uc h as G P SBabel's arc filter c an s implify the polyline, while retaining its bas ic s hape. D ifferent GPolyline objec ts with different amounts of detail c ould be c hos en bas ed on the c urrent zoom level. A s a rule, the les s data G oogle M aps is obliged to work with, the fas ter it will perform. 6.10.2. See Also G P SBabel lives at http://www.gps babel.org/. "V iew Your G P S Trac klogs in G oogle M aps " [Hack #37] implements a line s implific ation algorithm in Ruby and in J avaSc ript. "H ow Big I s T hat, E xac tly? " [Hack #28] als o us es a line s implific ation algorithm to s peed up the drawing of s tate and c ountry s hapes . Robert Lipe Hack 60. Make Things Happen When the Map Moves You can make your maps more interactive by responding to userinitiated events. Balanc ing what to s how and what not to s how on a G oogle M ap c an be tric ky. O n one hand, for performanc reas ons , you want to res tric t the overlays dis played on the map to jus t the ones that would appear within the c urrent view. O n the other, if the us er s hould pan or zoom the map, you might want the map's c ontents to c hange in res pons e. Fortunately, the G oogle M aps A P I offers a way to make this happen automatic ally. 6.11.1. The Hack P oor C lio's Side- by- Side G oogle M aps at http://james edmunds .c om/poorc lio/googlemap1 1 .c fm offers a terrific example of how G oogle M aps hac ks c an res pond to us er ac tions . T he s ite, built by J ames E dmunds , s hows two G oogle M aps of the s ame loc ation s ide by s ide. O n the left, the regular map mode is s hown, while the map on the right s hows the s ame map in s atellite mode. Figure 6 - 2 0 s hows the s ide- by- s ide view of the area around 3 0 th Street Station in P hiladelphia, with the rail yards extending away to the north. Figure 6-20. Two views of Philadelphia's 30th Street Station, side by side What's novel about this s ite is that if you drag the map on the left with your mous e, double- c lic k to rec enter it, or zoom in or out, the s atellite view on the right rec enters and zooms to matc h. U ntil G oogle introduc ed hybrid mode maps , this was effec tively one of the only ways to c ompare the s atellite and map views . T he s ec ret to how it works lies in the G oogle M aps E vent A PI. 6.11.2. The Code I f you've written or looked at J avaSc ript c ode that us es the G oogle M aps A P I to c aus e info windows to pop up when the us er c lic ks on a marker, then you've probably s een a method c all that looks like this : GEvent.addListener(marker, "click", function( ) { marker.openInfoWindowHtml(html); }); T his method us es the GEvent c las s to regis ter a c lic k event on a marker objec t. When the marker is c lic ked, the anonymous func tion gets c alled, and the info window is opened. A s it happens , the G oogle M aps A P I offers s everal other events for trac king and res ponding to us er interac tions . H ere's a s nippet of c ode from the P oor C lio's Side- by- Side page: function onMapMove( ) { smap.centerAndZoom(map.getCenterLatLng( ), smap.getZoo updateStatus( ); } function onMapZoom(oldZoom, newZoom) { smap.centerAndZoom(map.getCenterLatLng( ), newZoom); updateStatus( ); } GEvent.addListener(map, 'move', onMapMove); GEvent.addListener(map, 'zoom', onMapZoom); updateStatus( ); T hes e dozen or s o lines of J avaSc ript c ode handle virtually all of the us er interac tions needed to keep the two maps in s ync . T he firs t thing to note about this c ode is that, unlike mos t G oogle M aps A P I examples , you'll s ee two GMap objec ts in this c ode, one c alled map in the J avaSc ript, and the other c alled smap. Well, why not? T he firs t of the two func tions s hown above, onMapMove( ), takes the GPoint objec t repres enting the latitude and longitude of the c enter of the regular map, and the integer repres enting the c urrent zoom level of the regular map, and pas s es them to the centerAndZoom( ) method of the s atellite map. When this happens , the s atellite map automatic ally zooms and rec enters to matc h the c enter point and zoom level of the regular map. T he onMapZoom( ) func tion does bas ic ally the s ame thing, but it takes two arguments , repres enting the old and new zoom levels of the regular map, and us es the new zoom level of the regular map as the new zoom level of the s atellite map. T he two c alls to GEvent.addListener( ) hook thes e func tions into the move and zoom events on the regular map, res pec tively, s o that when the us er c hanges the view of the regular map, the s atellite map follows . T he c alls to updateStatus( ) inters pers ed through the c ode above c aus e the latitude, longitude, and zoom level dis play below the two maps to keep in s ync as well. T he c ode looks like this : function updateStatus() { var point = map.getCenterLatLng(); var status = "<b>Current zoom level:</b> " + map.getZoomLevel() " <b>Map center location:</b> " + Math.round(point.x * 100000) / 100000 + "&deg;, " Math.round(point.y * 100000) / 100000 + "&deg;"; document.getElementById("status").innerHTML = status; } T he us e of Math.round(), c oupled with multiplic ation and divis ion by a c ons tant power of ten, is a s tandard tric k for rounding a floating- point number to a given number of dec imal plac es . T he c all to document.getElementById( ) fetc hes the H T M L D oc ument O bjec t M odel element c ontaining the s tatus mes s age, and the as s ignment to the innerHTML property updates the H T M L ins ide with the lates t c enter point and zoom. T his s ame kind of tec hnique c an hypothetic ally be us ed to have a "L ink to this V iew" U RL trac k the c urrent view, although P oor C lio's does n't do it that way. A s s uming that you had an H T M L <a> element with an id attribute s et to linkHere, you c ould do s omething like the following to update the U RL in the HRef attribute: document.getElementById("linkHere").setAttribute( "href", "http://some.server.net/gmaps?ll =" + point.x + "+" + point.y + "&z=" + zoom ); T here's one other tric k that the P oor C lio's s ite us es to keep the maps in s ync . Bec aus e the s atellite half of this page does n't have zoom and pan c ontrols , the only way to move the s atellite map independently is to drag it with the mous e. T he s ite us es this line of J avaSc ript to keep s uc h a thing from happening. smap.disableDragging(); T he other way to s olve the problem of the maps potentially getting out of s ync , of c ours e, would be to make the event handlers a bit more generic and then add two more c alls to addEventListener( ) to make the regular map follow movements on the s atellite map as well. 6.11.3. The GEvent API T he key thing to note about the G E vent A P I is that all its methods are s tatic , whic h is to s ay that they're c alled on the c las s its elf, and not on an ins tanc e of the c las s . T his means you s ay: GEvent.addListener( … ); // RIGHT …as oppos ed to the following, whic h you s hould definitely not us e: var event = new GEvent(); // WRONG event.addListener( … ); // WRONG We mention this bec aus e it may run c ontrary to your expec tations , as mos t of the other c las s es in the G oogle M aps A P I require you to ins tantiate an objec t of that c las s before c alling methods on it. T he G E vent A P I s houldn't be mis taken for the J avaSc ript event A P I , whic h works rather s imilarly, with its onClick, onMouseOver, onChange methods , and s o on. I n general, you'll want to us e G E vent handlers for G oogle M aps A P I objec ts , and c ontinue to us e J avaSc ript event handlers for everything els e. I n partic ular, as of this writing, there is n't anything like an onMouseOver event for G oogle M aps marker objec ts , and more's the pity. P erhaps G oogle will fix this in a future vers ion of its A P I . 6.11.4. Hacking the Hack M os t G oogle M aps hac ks out there rely on an U pdate M ap button (or the equivalent) to update the overlays on a map after the us er zooms or pans . T his definitely works , but it's not the mos t elegant s olution for refres hing the map's c ontents , bec aus e it relies on the us er to do s omething that c ould be done automatic ally in J avaSc ript. H owever, before you run out and add event handlers to your G oogle M ap, c ons ider the following: the G oogle M aps A P I does n't guarantee exac tly when the regis tered event handlers will be c alled, jus t that they will be c alled at s ome point. I f you try dragging the regular map around on the P oor C lio's s ite, you'll notic e that there's s ometimes a bit of lag, but (as s uming you don't drag too quic kly) the s atellite map otherwis e follows along pretty faithfully. T his means that the move event on the regular map is getting triggered every s o many s ec onds or millis ec onds throughout the drag. I f your intention is to have one map trac k another, this is definitely what you want to have happen. O n the other hand, if you're us ing the event handler to trigger a download of fres h data off the network, you probably don't want to have multiple overlapping data reques ts s lowing everything down while the us er is s till trying to drag the map. Firs t, this means you want to us e the moveend event with the G M ap objec t, and not the move event. H owever, if you really want to be on the s afe s ide, you might do well to c ombine this with a s emaphore and a delay, in c as e the us er does a bit of fine adjus tment to rec enter or zoom the map to exac tly what they want to s ee. H ere's what the c ode might look like: var updateRequested = 0; GEvent.addListener( map, "moveend", function() { updateRequested++; window.setTimeout( beginUpdate, 2500 ) }); function beginUpdate () { if (--updateRequested > 0) return; // *now* check map.getCenterLatLng() etc. // then launch a new GXmlHttp request // and do the update handling when the request is comp } T he us e of the global updateRequested variable ac ts as a s emaphore to keep multiple events from triggering multiple network updates that would then s tomp all over eac h other. When a moveend event is triggered, updateRequested is inc remented from zero to one, and the network update is s c heduled to begin 2 ,5 0 0 millis ec onds (i.e., 2 .5 s ec onds ) later. I n the meantime, further moveend events will inc rement updateRequested by 1 eac h time. When beginUpdate( ) gets c alled 2 .5 s ec onds after the firs t moveend event, it will dec rement updateRequested by 1 , and then c hec k to s ee if the s emaphore is s till greater than zero. I f it is , then s ubs equent movements of the map mus t have oc c urred in the meantime, and the update is therefore deferred. Finally, the las t beginUpdate( ) will trigger 2 .5 s ec onds after las t moveend event, at whic h point the us er has s topped moving the map around, the updateRequested s emaphore will be dec remented bac k to zero and, then and only then, the update will oc c ur. C hoos ing the right delay s o that network updates are s mooth and non- overlapping, but s o that the us er experienc e is n't too terribly degraded, is probably a matter that merits s ome experimentation. Hack 61. Use the Right Developer's Key Automatically What to do when your web site lives at two domains that resolve to the same server. A dding a G oogle M ap to our web page [Hack #10] s olved all our problems . Right? N ot quite. T he map works perfec tly when we us e http://geoc oder.us , but the D N S for the G eoc oder s ite, like that of many s ites , is c onfigured to treat http://www.geoc oder.us / as a s ynonym for http://geoc oder.us /. T he two domains res olve to the s ame s erver, whic h means that the s ame page will be s erved up to people as king for either domain. T his works fine, until you put the G oogle M aps A P I key into the mix. When you have the s ame G oogle M aps hac k on two different U RL s , even though they point to the s ame plac e, you get the mes s age "T he G oogle M aps A P I key us ed on this web s ite was regis tered for a different web s ite. You c an generate a new key for this web s ite at http://www.google.c om/apis /maps /." O ne c an be forgiven the odd c huc kle at the irony of http://maps .google.c om/apis /maps /, as s hown in Figure 6 - 2 1 . Figure 6-21. Getting the developer key right is a tricky thing H ow does G oogle know what s erver and direc tory your reques t is c oming from? For G oogle M aps to work you need to inc lude the G oogle M aps J avaSc ript library into your page as s hown in this example: <script src="http://maps.google.com/maps?file=api&v=1&key= type="text/javascript"> </script> A us er will load your page by fetc hing it from your s erver. H is web brows er will then look through that page and identify images , s c ripts , plug- ins , and anything els e that was not in the page and s o needs to be loaded. When the brows er s ees the script element, it attempts to load the s c ript s pec ified in the U RL lis ted in the src attribute. When a brows er as ks for information from a web s erver, it als o s ends information, inc luding the name of the s erver and the page that referred the us er to get the s c ript. G oogle M aps is probably us ing the H T T P referer that is automatic ally s ent to the s erver by your brows er. T here are two general ways to s olve this problem. E ither you maintain more than one developer key and s omehow pic k the right one to us e when you load the G oogle M aps library, or you forc e people to always us e the U RL that is as s oc iated with your developer key by s ilently fixing bad U RL s . 6.12.1. Pick the Right Key in Perl I f you generate the page from a s c ript, s uc h as with P H P, P ython, or P erl, you c an maintain a lis t of s erver names and direc tories and the matc hing developer keys and then dynamic ally generate the script element to load the G oogle M aps library. T his is a P erl example that s ets the c orrec t developer's key bas ed on the HTTP_HOST that was us ed to c all the s c ript. I 've s hortened the developer's keys and replac ed the ac tual domain names with plac eholders . #!/usr/bin/perl # These are the keys for www.testingrange.com/pix, www.chi and www.journalsonline.com/pix my $key_tr = "ABQIAAAAJhHGNa8WG19AE1v8p0OkZxQpjl…4EDQ"; my $key_jo = "ABQIAAAAJhHGNa8WG19AE1v8p0OkZxSB9G…nOFw"; my $key_cd = "ABQIAAAAJhHGNa8WG19AE1v8p0OkZxQCuE…rtNA"; # which server are we? my $http_host = $ENV{HTTP_HOST}; my $key = ''; # set the key to match the host $key = $key_tr if ($http_host =~ /first-domain/); $key = $key_jo if ($http_host =~ /second-domain/); $key = $key_cd if ($http_host =~ /third-domain/); print "Content-type: text/html\n\n"; print qq( <!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"> <head> <script src="http://maps.google.com/maps?file=ap type="text/javascript"></script><--> </head> <body> <div id="map" style="width: 500px; height: 400px <script type="text/javascript"> //<![CDATA[ var map = new GMap(document.getElementById("map" map.addControl(new GSmallMapControl() map.centerAndZoom(new GPoint(-122.8288, 38.4025) //]]> </script> </body> </html> ); T his s c ript s ets variables for the developer keys for eac h of our domains , then s ets the variable $key to one of thos e values depending on the hos t- name that was us ed to c all this s c ript. I f we have firs t-domain.com, s econd-domain.com, and thirddomain.com all pointing to the s ame web page, then this s c ript will s et the c orrec t developer's key. I n real life, I would us e a template. I n this example, the H ello World map is in the s c ript and is printed out with the print qq( ) c ommand. T he qq( ) operator in P erl automatic ally does variable interpolation, whic h means the variable $key will be replac ed with the c orrec t developer's key. <script src="http://maps.google.com/maps?file=api&v=1&key= type ="text/javascript"></script><--> T his example as s umes c ompletely different s erver names . T he more c ommon c as e is to have http://www.mydomain.c om and http://mydomain.c om both work. A s s uming you've s et the keys c orrec tly, thes e lines will do that. $key = $key_plain if ($http_host !~ /^www/); $key = $key_www if ($http_host =~ /www/); T hes e lines s ay to us e the value of $key_plain if the HTTP_HOST does not s tart with www, and us e the value of $key_www if the hos t does s tart with www. T he important point is to us e the right key. I f you have s c ripts in different direc tories , you'll want to take a look at the variables $ENV{SCRIPT_NAME} and $ENV{REQUEST_URI}. T hes e variables c ontain the full path and page. You'll need to s trip off the page name s o you c an c ompare the hos t and direc tory. T here is more than one way to do it! 6.12.2. Use JavaScript to Accomplish the Same Goal You c an get the s ame effec t dynamic ally with J avaSc ript. T his is the H ello World map with a bit of J avaSc ript that looks to its own href to determine whic h U RL it was loaded as , and then loads the map library by dynamic ally s elec ting the right developer's key. I n this example, I 've s hortened the full developer's keys bec aus e you c an't us e my keys , and they are jus t too ugly to be printed in a book. <!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"> <head> <script type="text/javascript"> // These are var key_tr = var key_jo = var key_cd = the keys for the servers "ABQI…"; "ABQI…"; "ABQI…"; // Three nearly identical code blocks. // First define a regular expression that var reg_tr = new RegExp("testingrange"); // Test the regular expression against th // page, which is available in window.loc // if it contains our pattern then use it if( reg_tr.test(window.location.href) ) { loadScript(key_tr); } //same as above for next server var reg_jo = new RegExp("journalsonline") if( reg_jo.test(window.location.href) ) { loadScript(key_jo); } //same as above for yet another server var reg_cd = new RegExp("chilidog"); if( reg_cd.test(window.location.href) ) { loadScript(key_cd); } // build the script tag in the variable s // write it into the document function loadScript(key) { var src ='<' + 'script src=' + '"' + 'http://maps.google.com/maps?file=api ' type="text/javascript"><'+'/script> document.write(src); } //]]> </script> </head> <body> Which server is this? <div id="map" style="width: 500px; height: 400px <script type="text/javascript"> //<![CDATA[ var map = new GMap(document.getElementById("map" map.addControl(new GSmallMapControl()); map.centerAndZoom(new GPoint(-122.8288, 38.4025) //]]> </script> </body> </html> T he differenc e from the original H ello World is the s c ript bloc k in the header. I t defines variables for the different developer's keys , and then pic ks the right key bas ed on the c urrent U RL , whic h is available to J avaSc ript in the variable window.location.href. T here is a lot in c ommon between the J avaSc ript and P erl approac hes . T hey both pic k from a s et of developer's keys . T he next approac h lets you us e a s ingle key, but it c hanges the U RL that the us er s ees . 6.12.3. Using Apache's mod_rewrite to Share Keys I f you are us ing the A pac he web s erver you may be able to us e the mod_rewrite module to quietly fix your U RL s s o that they matc h your developer key. I n this example, we will us e mod_rewrite to s ilently add www. to the front of any c alls to http://mappinghac ks .c om. T his tec hnique as s umes that your A pac he is s et up to allow .htacces s to override the FileInfo s etting. A pac he has a lot of options , inc luding options that c an be s et on per direc tory bas is . T he mos t c ommon way to s et them is the A pac he c onfiguration file (often /etc/httpd/conf/httpd.conf) or in a file c alled .htacces s in the direc tory where you keep your web pages . T he .htacces s file will only work if the A pac he c onfiguration file is s et up to allow it to work. I n your httpd.conf file, there will be at leas t one <Directory> s ec tion. N ote that A pac he c onfiguration is Byzantine in its c omplexity, s o forgive my s implific ations . T here needs to be a line in the <Directory> s ec tion that s tarts with AllowOverride and s pec ifies either All, whic h means the .htacces s file c an c ontrol all as pec ts of A pac he's ac c es s to that direc tory, or FileInfo, whic h allows the .htacces s file to c ontrol file things , inc luding us e of the mod_rewrite module. 6.12.4. Edit .htaccess to Rewrite Requests I generated a key for http://www.mappinghac ks .c om/projec ts /gmaps . But I 'd like people to be able to us e http://mappinghac ks .c om/projec ts /gmaps as well. H ere is an example of a mod_rewrite rule that will redirec t reques ts from http://mappinghac ks .c om/projec ts /gmaps to http://www.mappinghac ks .c om/projec ts /gmaps . C reate a new .htacces s file, or edit the exis ting one, to add thes e three lines . RewriteEngine on RewriteCond "%{HTTP_HOST}" "!^www" [NC] RewriteRule "(.*)" "http://www.%{HTTP_HOST}%{REQUEST_URI}" T he firs t line turns on mod_rewrite. T he s ec ond line looks at the HTTP_HOST field, whic h s hould be the s erver name from the U RI , mappinghacks.com or www.mappinghac ks .c om. I t does a regular expres s ion matc h agains t the pattern ! ^www. Bang (!) means negation, or not, the c aret (^) means to matc h at the s tart of the s tring, and [NC] s ays to ignore c as e (i.e., N o C as e). T he RewriteRule tells A pac he what to do if the Rewrite C ondition is met. So this s ays "if the H T T P hos t does n't s tart with www replac e the whole U RI with http://www. plus the H T T P hos t, plus the filename, and any parameters that were originally pas s ed." To make it s impler, it jus t s ays "make s ure the U RL s tarts with www." 6.12.5. See Also A pac he U RL Rewriting G uides : A pac he Vers ion 1 .3 : http://httpd.apac he.org/doc s /1 .3 /mis c /rewriteguid A pac he Vers ion 2 .0 : http://httpd.apac he.org/doc s /2 .0 /mis c /rewriteguid T hes e are almos t c onvers ational guides to mod_rewrite. From the 2 .0 vers ion: "With mod_rewrite you either s hoot yours elf in the foot the firs t time and never us e it again or love it for the res t of your life bec aus e of its power." Chapter 7. Extreme Google Maps Hacks 7.1. Hacks 6270: Introduction So far, we've s een the power and eas e with whic h G oogle M aps c an s how nearly anything on a map, from your vac ation photos to a hypothetic al nuc lear explos ion. N ow it's time for us to take G oogle M aps hac ks to the next level by adding whole new feature s ets and A P I s . I n this c hapter, we'll s upplement the mis s ing features of G oogle M aps in various ways , by turning s treet addres s es into map c oordinates , generating dynamic ic ons us ing G oogle's polyline s ervic e, adding new c ontrols to bring in bac kground imagery from around the 'N et, and even c reating our own c us tom bac kground tiles ! T hes e hac ks go far above and beyond anything that even G oogle c ould have imagined or intended for G oogle M aps that's why we c all them "E xtreme G oogle M aps H ac ks ." Hack 62. Find the Latitude and Longitude of a Street Address The Google Maps A PI won't do it f or you, but there are other ways to f ind the coordinates of a given street address. A s we've s een all through this book, G oogle M aps makes it eas y to make c us tom maps of anything for whic h you have a latitude and a longitude. H owever, people don't tend to think of plac es in terms of geographic c oordinates ; more often, people c ommonly know and refer to plac es by a s treet or mailing addres s . I n order to find and s how thes e plac es on a map, we need to be able to turn a given addres s into the c orres ponding latitude/longitude c oordinates . T he proc es s of turning addres s es into map c oordinates is generally referred to as geocoding. U nfortunately, for all the great things that the G oogle M aps A P I offers , the very c ommon tas k of geoc oding s treet addres s es s imply is n't among them. A lthough the G oogle M aps webU I will s how you the loc ation of an addres s , often with great ac c urac y, the problem is that G oogle does n't own this data and has been unable to negotiate permis s ion with its data providers to offer addres s lookups as a s ervic e in the A P I . Furthermore, s c reens c raping the G oogle M aps res ults page is s tric tly a no- no, ac c ording to the Terms of U s e. I f you want to s tay legitand not ris k angry takedown letters from you- know- whohow c an you get the lat/long c oordinates for a given s treet addres s ? 7.2.1. The Hack Fortunately, within the U nited States , the C ens us Bureau c ollec ts s treet addres s information as part of its c ons titutionally as s igned duties of enumerating the populac e of the c ountry every ten years . What's more, the C ens us Bureau publis hes this information in the public domain, in the form of the T I G E R/L ine data s et. T his data is freely available from the C ens us Bureau web s ite at http://www.c ens us .gov/geo/www/tiger/. A s of 2 0 0 4 , updated vers ions are publis hed twic e a year. T he problem is that the T I G E R/L ine data s et is c ompos ed of 3 ,2 3 3 s eparate ZI P files , one for eac h c ounty in the entire U nited States . T he entire data s et is 4 .3 G B c ompres s ed and runs to almos t 1 6 G B unc ompres s ed. T hat's a lot of data to s truggle with if you jus t want to look up a few lous y addres s es . T his is where Geocoder.us c omes in. G eoc oder.us offers a web s ervic e (http://geoc oder.us /) for geoc oding U .S. s treet addres s es from T I G E R/L ine data. A c tually, s everal s tyles of web s ervic e are offered, inc luding SO A P, XM L- RP C , and RE ST. A ll of thes e s ervic es have but one goal, whic h is to take a s treet addres s or inters ec tion in the U .S. and turn it into latitude and longitude c oordinates that c an be dis played on a map. Figure 7 - 1 s hows the working demo applic ation of the G eoc oder.us s ervic e at http://geoc oder.us /demo.c gi. T he latitude and longitude returned from the lookup c an be trivially turned into a marker on a map, us ing the G oogle M aps A P I . You c an us e this U RL to tes t out the s ervic e manually, but if you want to do addres s lookups in your program, you s hould definitely us e the web s ervic e interfac es ins tead. 7.2.2. The Code 7.2.2.1. XML-RPC. T he eas ies t way we know for ac c es s ing the G eoc oder.us web s ervic e is to us e the XM L- RP C interfac e from within P erl. T he outline of the c ode looks like this : use XMLRPC::Lite; my $result = XMLRPC::Lite -> proxy( 'http://rpc.geocoder.us/service/xmlrpc' ) -> geocode( '1005 Gravenstein Hwy, Sebastopol, CA 95472' -> result; Figure 7-1. The geocoder.us site at work E ither a properly formatted U .S. s treet addres s or an inters ec tion of the form "H ollywood Blvd & V ine St, H ollywood, C A " will be ac c epted by the web s ervic e. You mus t s upply either a c ity and s tate or a ZI P C ode, though providing both does n't us ually hurt. I f the lookup s uc c eeds , then the $result variable will c ontain a referenc e to an array. E ac h item in the array is a has h, or as s oc iative array, that c ontains key/value pairs des c ribing the res ults of the lookup. T he following outlines the s truc ture of the data returned by the XM L- RP C reques t: $result = [ { 'number' => '1005', 'prefix' => '' 'street' => 'Gravenstein', 'type' => 'Hwy', 'suffix' => 'N', 'city' => 'Sebastopol', 'state' => 'CA', 'zip' => '95472', 'lat' => '38.411908', 'long' => '-122.842232', } ]; A s you c an s ee, the G eoc oder.us web s ervic e attempts to break an addres s into its c omponents and then normalizes thos e c omponents before doing the lookup, and then returns the normalized c omponents along with the c oordinates . H ere's a bit of c ode that prints the latitude/longitude pairs returned: if ($result) { for my $address (@$result) { if ($address->{lat}) { print "Address found: $address->{lat} $address } else { print "Couldn't locate the address!\n"; } } } else { print "Couldn't parse the address!\n"; } T he $result variable s hould be tes ted for truth before ac c es s ing its c ontents , bec aus e the s ervic e will return an undefined value if the addres s c an't be pars ed. I f the addres s can be pars ed, but no matc h is found in the databas e, the res ult will be an array c ontaining a s ingle has h, with an empty s tring in plac e of the latitude and longitude values . Finally, if the addres s given matc hes multiple addres s es in the databas e, the array will c ontain a s eparate has h for eac h matc h found. T he XMLRPC::Lite P erl module is part of the SOAP::Lite dis tribution. I f you don't have either module ins talled on your s ys tem, download them from the C P A N at http://s earc h.c pan.org/ or us e the C P A N s hell to ins tall them as follows : # perl -MCPAN -e 'install XMLRPC::Lite' XM L- RP C c lient libraries are als o available for virtually every programming language out there, s o you s houldn't have too muc h trouble finding one for your language of c hoic e. 7.2.2.2. REST. I f, for whatever reas on, you prefer not to us e XM L- RP C , you c an always us e the G eoc oder.us RE ST s ervic e, by s ending an HTTP GET reques t to http://rpc.geocoder.us/service/rest/geocode? address=[your address here]. (D on't forget to U RI - es c ape the addres s e.g., turn whites pac e to %20before pas s ing it to your H T T P c lient, if your c lient library does n't do it for you. T he URI:: Escape module from the C P A N c an help with this .) T he RE ST interfac e returns an RD F/XM L doc ument with geo:Point elements for eac h addres s matc h. H ere's an example: <rdf:RDF xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns <geo:Point rdf:nodeID="aid34279220"> <dc:description>1005 Gravenstein Hwy N, Sebastopol description> <geo:long>-122.842232</geo:long> <geo:lat>38.411908</geo:lat> </geo:Point> </rdf:RDF> M ultiple geo:Point elements will be returned in the doc ument if multiple matc hes for the reques ted addres s are found. H ere's a bit of P erl c ode that makes us e of the RE ST s ervic e. You will need the XML::Simple, LWP::Simple, and URI::Escape modules from the C P A N . use use use use XML::Simple; LWP::Simple; URI::Escape; strict; sub geocode_rest { my $xml = get( "http://rpc.geocoder.us/service/rest/ge uri_escape( $address ); if ($xml) { my $result = eval { XMLin( $xml, ForceArray => ['g if ($result) { my $points = $result->{'geo:Point'}; for my $point (@$points) { my $lat = $point->{'geo:lat'}; my $lon = $point->{'geo:long'}; if ($lat and $lon) { ### Success! Do something with the coo } else { ### Couldn't find a match for the addr } } } else { ### Couldn't parse the XML, so the service spi ### out an error message, meaning it couldn't } else { ### The HTTP GET failed, indicating a network erro } } 7.2.2.3. SOAP. T he SO A P interfac e to the G eoc oder.us web s ervic e is probably the mos t diffic ult to us e, entirely owing to the s ubtle c omplexities of SO A P its elf. H owever, if you're a J ava or C # us er, it might ac tually be eas ier for you to us e SO A P than the other web s ervic e interfac es , bec aus e you c an us ually autogenerate res ult c las s es from the WSD L des c ription. A c c ordingly, you may be pleas ed to know that a WSD L file exis ts for the G eoc oder.us SO A P interfac e at http://geoc oder.us /dis t/eg/c lients /G eoC oder.ws dl. 7.2.3. The Caveats I n princ iple, you s hould be able to ac c es s the G eoc oder.us web s ervic es direc tly from the brows er by us ing J avaSc ript, but in prac tic e, the brows er s ec urity model of the better web brows ers out there will prevent you from us ing J avaSc ript to ac c es s I nternet domains as ide from the one that your page originates from. O ne way around this , whic h many s ites are c urrently us ing, is to s et up a s erver- s ide s c ript that ac c es s es the G eoc oder.us s ite, as s hown above. You c an then us e the GXmlHttp c las s from the G oogle M aps A P I to reques t addres s lookups via your s ite's geoc oding proxy, and get the res ults bac k in J avaSc ript as either XM L or plain text, depending on your preferenc es . O ne c aveat you s hould be aware of is that the T I G E R/L ine data s et is les s c omplete and/or les s ac c urate in s ome areas than the c ommerc ial data s ourc es that G oogle M aps us es to loc ate addres s es . T he flip s ide, of c ours e, is that T I G E R/L ine is freely available. I t's a trade- off! I n general, res idential addres s es are more likely to be ac c urate than addres s es in indus trial areas or c ommerc ial offic e parks . A ls o, you need to examine the terms and c onditions of s ervic e for G eoc oder. us at http://geoc oder.us /terms .s html, before us ing their s ervic e. I n partic ular, us e of the free web s ervic es for forprofit c ommerc ial ends is s tric tly prohibited. I f you are a c ommerc ial us er, you will need to s ubs c ribe to the c ommerc ial s ervic e ins tead. T he final c aveat is that the G eoc oder.us web s ervic es are throttled by I P addres s , to keep the s ervic e from being hammered by a s ingle us er. A s of this writing, a delay of 1 5 s ec onds between reques ts is in plac e, but L oc ative Tec hnologies , the maintainers of the G eoc oder.us s ervic e, res erves the right to adjus t this upwards or downwards as nec es s ary. I f the s ervic e s eems unduly s low, it's probably bec aus e your reques ts aren't s pac ed more than 1 5 s ec onds apart. O f c ours e, c ommerc ial ac c ount us ers don't s uffer this res tric tion. I f the throttling or the expens e are a problem for you, you c an always s et up your own loc al G eoc oder.us databas e, by downloading the Geo::Coder::US module and its prerequis ites from the C P A N . T he doc umentation for the Geo::Coder::US::Import module, whic h c omes with the dis tribution, c ontains all the ins truc tions you need for getting the T I G E R/L ine data from the C ens us Bureau, and us ing it to build your own loc al databas e. A lthough the G eoc oder.us databas e for the whole c ountry runs to almos t 8 0 0 M B, you c an s implify things for yours elf by c ons truc ting a databas e c ompos ed only of the c ounties you're interes ted in. 7.2.4. Geocoding Addresses Outside the U.S. G eoc oding s treet addres s es outs ide the U .S. for free is c ons iderably harder, bec aus e the data s ets s imply aren't freely available. (D enmark is one notable exc eption.) I n C anada, you may be able to us e the G eoc oder.c a web s ite at http://geoc oder.c a/, but that s ervic e is bas ed on government data that its elf is not freely available. For E urope, J apan, and the res t of the world, you may have to purc has e ac c es s to a c ommerc ial data s et in order to geoc ode addres s es in your c ountry. T he alternative is to petition your government's legis lators to c hange its geos patial data ac c es s polic ies , s o that c itizens in your c ountry c an ac c es s information whos e c ollec tion has already been s ubs idized with your tax money! 7.2.5. See Also I f you plan to us e the G eoc oder.us web s ervic es , you s hould definitely read the developer doc umentation at http://geoc oder.us /help/, as well as the terms and c onditions of s ervic e at http://geoc oder.us /terms .s html. I f you want to s et up your own U .S. addres s geoc oder, you c an s tart by getting the Geo::Coder::US bac kend c ode from http://s earc h.c pan.org/~s derle/G eo- C oder- U S/, or by us ing the C P A N s hell to ins tall the module and its prerequis ites automatic ally. Be s ure to read the doc umentation for the Geo::Coder::US::Import module. T he Geo::StreetAddress::US module c ontains all of the rules for how s treet addres s es are pars ed. We always welc ome patc hes to this module, to help improve our hit rate! T he C ens us Bureau's T I G E R/L ine data s et lives on the Webat http://www.c ens us .gov/geo/www/tiger/. Hack 63. Read and Write Markers from a MySQL Database Keep track of almost anything with Google Maps and a relational database. A dding a map of s omething new to G oogle M aps is good fun, but there is a lot of data already in SQ L databas es that is jus t begging to be mapped. T his tutorial des c ribes the way the Subfinder applic ation, at http://www.maps erver.c om/googlemaps /s ubfinder.php, is integrated with a M ySQ L databas e us ing P H P. T he Subfinder is its elf an extens ion of the Who L oc ations s ite at http://www.maps erver.c om/googlemaps /wholoc ations 2 .php, whic h is des c ribed in a tutorial at http://www.maps erver.c om/googlemaps /tutorial.html. Figure 7 - 2 s hows a map of the s ites that any fan of T he Who mus t know about. T here are eas ier ways to get points on a G oogle M ap, but to integrate with a M ySQ L databas e you will need: 1. A n A pac he web s erver running P H P and M ySQ L . (O ther web s erver s oftware with P H P and M ySQ L will probably do as well.) 2. A table in your databas e with lat, long, and description c olumns . 3. Some bas ic H T M L and P H P knowledge. We are going to us e P H P to dynamic ally c reate an H T M L doc ument with the appropriate G oogle M aps J avaSc ript c ode. O ne of the func tions s hown in this s ample is the option for us ers to add their own loc ations , with additional attributes , into the databas e. T he value of one of the attribute determines the type of marker plac ed. Figure 7-2. A map for Who fans 7.3.1. Structuring Your Database T he databas e c an be rec reated with this s nippet of SQ L : CREATE TABLE subfinder ( id int(11) NOT NULL auto_increment, lat decimal(10,6) NOT NULL default '0.000000', lon decimal(10,6) NOT NULL default '0.000000', desc varchar(255) NOT NULL default '', url varchar(255) NOT NULL default '', marker char(1) NOT NULL default '', PRIMARY KEY (id) ) TYPE=MyISAM; I f you s ave this into the file create_s ubfinder.s ql, you c an c reate a new databas e and this table with the following c ommands : $ mysqladmin create sub_db $ mysql sub_db < create_subfinder.sql A s you c an s ee, there are fields for the latitude and longitude values , a des c ription, U RL (whic h will of c ours e be dis played as a link), and a marker field. T he value of the marker field will determine the type of marker plac ed. T his applic ation, whic h lis ts s ubmarines vis ible on the G oogle M aps photos , makes a dis tinc tion between s ubmarines that are in ac tive duty (A), mus eum s hips (M), plac es where s ubmarines have s unk (S), and plac es where important events have taken plac e (E). T he appropriate letter is dis played in the marker. 7.3.2. The Code T his s ys tem us es two P H P files to do its work. T he main file, s ubfinder.php, is us ed to read the data from the databas e and dis play it on the map. T he s ec ond file, s ubfinder_load_db.php, is c alled by the firs t to write data into the databas e. A s tandard H T M L form is us ed for this . T he s ubfinder.php file imports the G oogle M aps A P I , and s ets up the map in the us ual way. T he following bit of J avaSc ript c reates the c us tom markers : subfinder.php: setting up the custom markers <script type="text/javascript"> //<![CDATA[ var baseIcon = new GIcon(); baseIcon.shadow = "http://www.map-server.com/img/shadow50. baseIcon.iconSize = new GSize(20, 34); baseIcon.shadowSize = new GSize(37, 34); baseIcon.iconAnchor = new GPoint(9, 34); baseIcon.infoWindowAnchor = new GPoint(9, 2); baseIcon.infoShadowAnchor = new GPoint(18, 25); // Creates a marker whose info window displays the given n function createMarker(point, text, markerstyle) { var icon = new GIcon(baseIcon); icon.image = "http://www.map-server.com/img/marker" + ma var marker = new GMarker(point, icon); // Show this markers index in the info window when it is var html = text; GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); }); return marker; } I n the c ode above, I 've c opied the P N G image us ed by the offic ial G oogle s ample to my own s erver for this . I then made four different P N G files , one for eac h letter us ed (A , E , M , S). T his letter is being pas s ed on through the markerstyle variable. N ext, the map is defined, s ome c ontrols are added, and the initial map view is s et through the map.centerAndZoom func tion. A relatively new addition to the G oogle M aps A P I (undoc umented at the time of this writing) is the GScaleControl c las s , whic h adds a s c ale bar in the lower- left c orner: var map = new GMap(document.getElementById("map")); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); map.addControl(new GScaleControl()); map.centerAndZoom(new GPoint(0, 0), 16); N ext, we us e s ome P H P c ode to read the information from the databas e, pars e it, and write it into the doc ument. I 've us ed an external c onfiguration file (conf.php) to dec lare the variables that hold the s erver, us ername, and pas s word for my databas e c onnec tion. A link to the databas e is s et up and a query is pas s ed to it. <?php include_once("conf.php"); $link = mysql_connect($dbserver, $username, $password or die("Could not connect: " . mysql_error()); mysql_select_db("dbmapserver",$link) or die ("Can\'t use dbmapserver : " . mysql_error() $result = mysql_query("SELECT * FROM subfinder",$link if (!$result) { echo "no results"; } T he res ult of this query is then put into an array. For every element in the array, the func tion createMarker (whic h was defined above) is c alled with the lat, long, and des c ription of that point. N ote that this will generate the c ode for the brows er to interpret. I f you look at the s ourc e c ode of the page in your brows er, you'll s ee the res ult of this P H P c ode. while($row = mysql_fetch_array($result)) { if ($row['marker'] == 'A') $marker_type = 'Active'; if ($row['marker'] == 'M') $marker_type = 'Museum'; if ($row['marker'] == 'S') $marker_type = 'Sunk'; if ($row['marker'] == 'E') $marker_type = 'Event'; $info_text = "<b>" . $marker_type . "</b><br>" . $row['desc'] . "<br><br><a href=" . $row[url] . " target=_blank>Link</a>"; echo "var point = new GPoint(" . $row['lon'] . "," . $row['lat'] . ");\n"; echo "var marker = createMarker(point, '" . $info_text . "','" . $row['marker'] . " echo "map.addOverlay(marker);\n"; echo "\n"; } mysql_close($link); ?> T he next piec e of c ode from s ubfinder.php s ets up the H T M L form to add new information to the databas e: GEvent.addListener(map, 'click', function(overlay, point) if (overlay) { //map.removeOverlay(overlay); } else if (point) { var form; form = '<form name="form1" method="post" action="subfi form += '<table border="0"><tr><td>Lat:</td>'; form += '<td align="left"><input name="new_lat" type=t value=" + point.y + '"></td>'; form += '<td rowspan="4">'; form += '<input name="new_marker" type="radio" value="A" checked="1"> Active'; form += '<br><input name="new_marker" type="radio" val form += '<br><input name="new_marker" type="radio" val form += '<br><input name="new_marker" type="radio" value="E">Event</td></tr>'; form += '<tr><td>Lon:</td>'; form += '<td align="left">'; form += '<input name="new_lon" type="text" id="new_lon + point.x + '"></td></tr>'; form += '<tr><td>Text:</td>'; form += '<td align="left">'; form += '<input name="new_desc" type="text" id="new_de form += '</td></tr>'; form += '<tr><td>URL:</td><td align="left">'; form += '<input name="new_url" type="text" id="new_url form += '</td></tr>'; form += '<tr></td><td align="left">'; form += '<input type="submit" name="Submit" value="Sub form += '</table></form>'; output.innerHTML = form if (map.getZoomLevel() >= zoomToLevel) { map.centerAndZoom(point, zoomToLevel); } map.addOverlay(new GMarker(point)); } }); //]]> </script> <div id="output"></div> T he bloc k that c ontains all the H T M L is generated when the us er c lic ks s omewhere on the map to add a loc ation, whic h s ets up a form to allow the us er to add more information. T his form is s tored in output.innerHTML. T he point.x and point.y variables are being s upplied by the lis tener. T he P H P file that gets c alled by the form in s ubfinder.php is a lot s impler. T he c ode, s tored in s ubfinder_load_db.php, is jus t your bas ic "take the parameters and s tuff them in the databas e" c ode: <?php include_once("conf.php"); echo "<html><head><link href=\"/style/hans.css\" rel=\"sty "text/css\">"; echo "</head><body>"; echo "Lat: " . $new_lat . "<br>"; echo "Lon: " . $new_lon . "<br>"; echo "Text: " . $new_desc . "<br>"; echo "URL: " . $new_url . "<br>"; echo "Marker: " . $new_marker . "<br>"; echo "Will now be added to the database…"; $new_desc = addslashes($new_desc); $link = mysql_connect($dbserver, $username, $password) or die("Could not connect: " . mysql_error()); mysql_select_db("dbmapserver",$link) or die ("Can\'t use dbmapserver : " . mysql_error()); $sql = "INSERT INTO subfinder "; $sql = $sql . "VALUES('','" .$new_lat."','".$new_lon."','".$new_desc."','".$new_ur .$new_marker ."')"; $result = mysql_query($sql ,$link); if (!$result) { echo "<p>Due to an error (" . mysql_error() . ")<br>, yo . "not be loaded into the database. Please return to " . "<a href=\"subfinder.php\">Subfinder</a>."; } else { echo "<p>Your entry has been loaded into the database. " . "Please return to <a href=\"subfinder.php\">SubFinde } echo "</body></html>"; ?> O nc e again, the conf.php with the ac c es s variables is read. O ne important thing to note here is the addslashes() func tion. A s we mentioned earlier, J avaSc ript c an be quite fus s y about quotes and s pec ial c harac ters . I f there are any of thos e c harac ters in the texts you want to dis play in the info windows , it may res ult in either the map not being drawn at all, or jus t your markers not being drawn. T he addslashes() func tion properly es c apes thos e c harac ters before putting the text into the databas e s o that your us ers don't have to worry about that thems elves . 7.3.3. See Also Red G eographic s M ap- Server page: http://www.maps erver.c om/ Hans van der Maarel Hack 64. Build Custom Icons on the Fly Using libraries that extend the Google Maps A PI in various ways, you can quickly achieve powerf ul results. T he XM aps library is a s et of extens ions to the G oogle M aps A P I . A s of this writing, the library builds on the G oogle M aps A P I to add many c apabilities that the A P I its elf does not provide. A s of this writing, the additional features provided by XM aps inc lude filled polygons , text along polylines , and c us tom ic ons and markers . For this hac k, we will s ee how to eas ily c reate new ic ons by making us e of the XIcon and XMarker c las s es from XM aps . T he XM aps library lives on the Web at http://xmaps .bus mons ter.c om/. 7.4.1. The Hack T he XIcon c las s is s imilar to G oogle's GIcon c las s , but it automates s ome of the s teps nec es s ary to c reate ic ons , making it s impler to make new ic ons on the fly. You c ould do the s ame thing that the XIcon c las s does by us ing a s erver- s ide s c ript, but here we are us ing s omething that does not require any extra s erver hors epower or bandwidth from you. XIcon objec ts are limited in that they are a filled c onc ave polygon (e.g., the outline of a c ar, lion, or c irc le), but you have the advantage of being able to s pec ify the c olor, s ize, opac ity, and any text on it on the fly. T he GIcon c las s makes us e of a s et of pre- rendered P N G images s tored on a s erver s omewhere. T he default GIcon us es three images from G oogle Ride Finder to c reate its res ulting image: the reddis h- orange marker image, a nearly trans parent vers ion of that s ame image (for c lic k detec tion on I E ), and a mos tly trans parent s hadow image. Figure 7 - 3 s hows the parts of this pre- rendered ic on. Figure 7-3. Google Maps pushpin icon parts: (a) the pushpin image, (b) the shadow, (c) the click target for IE, and (d) the resulting icon I ns tead of us ing pre- rendered images , an XIcon's images are c reated on the fly by us ing the exis ting (but unoffic ial) s ervic e that G oogle M aps already us es to draw polylines . U s ing this s ervic e, we c an ac tually draw images of any c olor and opac ity. By s pec ifying the outline of the ic on s hape, the XIcon c las s c an c reate the nec es s ary images for you (inc luding the s hadow image). For example, if we wanted to c reate a rounded box ic on, we c ould c ome up with a lis t of points for the outline, give them to XIcon, and get the s et of images s hown in Figure 7 - 4 for the ic on. Figure 7-4. Custom XMaps icon parts: (a) the box outline, (b) the filled box, (c) the shadow, (d) the click target, and (e) the final rounded box icon Bec aus e we are c reating an additional image in the s et of images us ed for the ic on, we c annot us e the exis ting GMarker c las s in the G oogle M aps A P I , whic h c an only us e the images in a GIcon. I ns tead, we us e the XMarker c las s , whic h c an handle either GIcon or XIcon objec ts . XMarker gives us an additional ability that GMarker does not provide, namely the ability to plac e text or other H T M L on top of the ic on. When we c reate our ic on, we will s pec ify the bounds of any c ontent that might be dis played on top of the ic on, and an XMarker will us e thes e bounds to plac e text or a generic H T M L D O M element on top of the ic on. 7.4.2. The Code Suppos e, for example, that we wanted to c reate a web s ite all about the Bermuda Triangle. What better ic on to us e for our map than a c us tom- made triangle pointing at our map! I 'll as s ume you are familiar with the general layout of a G oogle M aps page. T he fragments of c ode here require that there is an exis ting GMap objec t already c reated and as s igned to a J avaSc ript variable c alled map. T he firs t thing we'll have to do is inc lude the XM aps library along with the G oogle M aps A P I J avaSc ript files . H ere's the c ode that s hould appear at the beginning of our page. N ote that you will want to replac e the A P I key with one for your s ite, and you will want to make s ure you are us ing the mos t rec ent vers ion of the XM aps library from http://xmaps .bus mons ter.c om/. <script src="http://maps.google.com/maps?file=api&v=1&key= type="text/javascript"></script> <script src="http://xmaps.busmonster.com/script/xmaps.1b.j type="text/javascript"></script> N ext, let's define the ic on's s hape. H ere I 've s pec ified a triangle approximately 3 0 pixels to a s ide. var triShape = { iconAnchor: new GPoint(15, 26), infoWindowAnchor: new GPoint(15, 0), shadow: true, contentAnchor: new GPoint(0, 0), contentSize: new GSize(31, 20), points: [0,0, 15,26, 30,0] }; A s you'll s ee, we c an s c ale this later, s o the initial s ize does not matter too muc h. T he s hape des c ription is c ontained in a s imple as s oc iative array, with the following properties : iconAnchor T his is the pixel of the ic on's image, whic h s hould be tied to the point on the map. I n this c as e, it is the bottom middle pixel (the triangle's bottom point). infoWindowAnchor T his is the pixel on the ic on's image, whic h s hould be tied to the bottom point of the info window. shadow T his determines if the ic on will have a s hadow or not (the s hadow is c reated for us automatic ally). contentAnchor T T his is the top left pixel on the ic on's image that s hould be us ed for any H T M L c ontent on top of the ic on (e.g., text). contentSize T his is the s ize, in pixels , of the box in whic h H T M L c ontent is allowed. points T his is an array of x/y pairs that define the s hape of the ic on. I n this c as e, we have the c orners of an ups idedown triangle. You c an s ee the purpos e of s ome of thes e properties in Figure 7 5. N ow we are ready to give our s hape a name. We do this s o that XM aps c an c ac he the U RL s that are us ed to generate thes e s hapes for better performanc e. XIcon.shapes['triangle'] = triShape; O ur s hape is now regis tered with the Xmaps A P I , and we are ready to us e it. When we c reate an XIcon, we have a number of s tyle properties we c an s pec ify. E ac h of thes e has defaults , s o you will not always have to s pec ify all of them, but I will do s o here to s how you an example of eac h property: Figure 7-5. Triangle icon properties var triStyle = { scale: 1.5, outlineColor: '#ffffff', outlineWeight: 2, fillColor: '#7f00ff', fillOpacity: 0.5 }; O nc e again, the ic on's s tyle is defined with a s imple as s oc iative array. H ere's what eac h property does : scale Spec ifies how big we want our ic on. Sinc e I s pec ified 1 .5 , we will end up with a triangle with approximately 3 0 * 1 .5 = 4 5 pixels per s ide. outlineColor Spec ifies the c olor for the outline of the ic on. H ere, we are us ing a white outline. outlineWeight Spec ifies the width, in pixels , of the ic on's outline. fillColor Spec ifies the c olor of the interior of the ic on. fillOpacity Spec ifies the opac ity of the interior of the ic on; mus t be in the range 0 to 1 . We are ready to c reate our ic on. T he c all to the c ons truc tor looks like this : var triIcon = new XIcon('triangle', triStyle); N ow we have an ic on we c an us e with any XMarker. H ere, we'll plot one: var bermudaTriangle = new GPoint(-70.532227, 25.878994); var iconText = "?"; var hoverText = "The Bermuda Triangle"; var triMarker = new XMarker(bermudaTriangle, triIcon, icon map.addOverlay(triMarker); T he XMarker c ons truc tor takes a point and a few optional arguments . We pas s the ic on we c reated as well as s ome text to be dis played on the ic on and when the mous e hovers over the ic on. T he XM aps A P I allows us to pas s the XMarker objec t direc tly to map.addOverlay( ), jus t as if it were an ordinary GMarker. A nd we're done! With a minimum of effort, we have a new marker with a c us tom ic on that has its own s hadow, is s c aled and c olored like we want, and has the c lic kable region s pec ified by the ic on outline. To s ee the res ults , brows e over to http://xmaps .bus mons ter.c om/triangle.html and c hec k it out. We c an follow thes e s ame s teps to c reate lots of reus able ic ons . To give you a head s tart, XM aps c omes with a few handy premade ic ons , inc luding the rounded box you s aw in Figure 7 - 4 . You c an play around with the web pages lis ted below to s ee more examples of c us tom ic ons with XM aps . 7.4.3. See Also T he XM aps L ibrary at http://xmaps .bus mons ter.c om/ has links to the newes t vers ion of the library, full doc umentation, and many examples . T he Bermuda Triangle example at http://xmaps .bus mons ter.c om/triangle.html s hows a c ompleted vers ion of our c ode fragments from above. T he I c on C olor Shades example at http://xmaps .bus mons ter.c om/s hades .html s hows different ic ons of different c olors . T he Bermuda Triangle entry at http://en.wikipedia.org/wiki/Bermuda_triangle in Wikipedia has plenty of information about how and where to get los t at s ea! Chris Smoak Hack 65. Add More Imagery with a WMS Interface What's a pretty f ace like you doing on the geospatial web? T he G oogle M aps s ervic e is c ool, the us er interfac e is wonderful, the A P I is a joy, and the maps are pretty, but there is more to the world of mapping than what fits on one c ompany's mas s ive s erver farm. 7.5.1. The Hack T he O pen G eos patial C ons ortium (O G C ) has defined a number of interoperability s tandards for web mapping applic ations . T he s imples t to unders tand is the Web M apping Servic e (WM S) s pec ific ation. I n G oogle M aps terms , you would as k a WM S s erver for a tile that c ontains s omething like a G oogle M ap or Satellite image. T he key is that the WM S is not limited to the data that G oogle M aps maintains . T here are WM S s ervers with things from L ands at imagery to topographic (elevation) data to habitat data. WM S reques ts are normally made by programs , but you c an as s emble a reques t by hand. I f you put this U RL into your brows er: http://wms.jpl.nasa.gov/wms.cgi?request=GetMap&layers =global_mosaic_base&srs=EPSG:4326&bbox=-87.90,24.38,-76 &FORMAT=image/png&width=600&height=400&styles=pseudo you will get the image of Florida s hown in Figure 7 - 6 . Figure 7-6. Florida as shown by a WMS request T his looks a lot like a G oogle M aps tile. E ven without unders tanding the format of a WM S reques t, you c an look at that U RL and get s ome information. For example, it has a bbox (or bounding box) that c overs the area from 8 7 .9 W to 7 6 .6 5 W and 2 4 .3 8 N to 3 0 .0 1 N , whic h happens to be mos t of Florida. You c an make a reques t to a WM S s erver for a map that c overs a c ertain area. But what is a map? WM S returns a ras ter (an image) for the s elec ted area and for s elec ted features . WM S Servers report what their c apabilities are, what s orts of information they c ontain, and WM S c lients c an then s elec t the layers they want to s how. D avid Knight has written a J avaSc ript extens ion library that you c an ins ert into your own G oogle M aps page to let you brows e through tiles from a WM S s erver us ing the G oogle M aps us er interfac e. For an example of this , vis it the G lobal C oordinate page at http://globalc oordinate.c om/. Figure 7 - 7 s hows L ands at imagery of South Florida within a G oogle M aps interfac e. T he G lobal C oordinate page als o demons trates near real- time updating of the map from RSS feeds . Figure 7-7. Florida from a WMS Server 7.5.2. The Code We've c reated a s imple example of a WM S- enabled G oogle M ap at http://mappinghac ks .c om/projec ts /gmaps /wms .html. Sure you have the s tandard map and s atellite views , but it inc ludes a little extra kic k in the data layer department. I t als o inc ludes L ands at and V M A P 0 data for the whole world and elevation and landc over layers for the U nited States . I t will produc e a dis play like Figure 7 - 8 . A s s uming you have c reated the H ello World map [Hack #10], you c an add thes e WM S layers with this c ode: <script src="http://www.globalcoordinate.com/jscript/WMSTi type="text/javascript"></script> T his inc ludes D avid's library. You c an look at it by pointing your brows er to this U RL : http://www.globalc oordinate.c om/js c ript/WM ST iles .js . U s ing the WM S tiles library is fairly s traightforward. I n the following J avaSc ript example, the mapSpecs variable holds an array of objec ts that is us ed to load parameters needed for the WM S fetc h and dis play. Figure 7-8. WMS layers on a Google Map var mapSpecs = []; createMapSpecs(); _SATELLITE_TYPE.getLinkText = function() { return "GoogleSat"; } mapSpecs.push(_GOOGLE_MAP_TYPE); mapSpecs.push(_SATELLITE_TYPE); Firs t, we c reate a new WM S map s pec ific ation and then pus h it onto mapSpecs. To c reate a layer, pas s the bas e WM S U RL and the name that you want dis played on your map. T here are four layers here: L ands at, V M A P 0 , N ational E levation D atas et (N E D ), and N ational L andc over D atas et. T hes e four layers c ome from three different s ervers . T he G eos patial web is alive, and with a few lines of c ode you c an add more, different, and s ometimes better layers to your G oogle M aps applic ations ! wmsSpec =new _WMSMapSpec ("http://wms.jpl.nasa.gov/wms.cgi =GetMap&layers=global_mosaic_base&srs=EPSG:4326","Lands mapSpecs.push(wmsSpec); wmsSpec =new _WMSMapSpec ("http://geocoder.us/surfer/wms.c =wms\&version\=1.1.1\&request=GetMap&layers=vmap0&srs =EPSG:4326", "vmap0"); mapSpecs.push(wmsSpec); wmsSpec =new _WMSMapSpec ("http://gisdata.usgs.net/servlet/com.esri.wms.Esrimap? =USGS_WMS_NED&request=GetMap&layers=US_NED_Shaded_Relie =EPSG:4326","Elevation NED"); mapSpecs.push(wmsSpec); wmsSpec =new _WMSMapSpec ("http://gisdata.usgs.net/servlet/com.esri.wms.Esrimap? =USGS_WMS_NLCD&request=GetMap&layers=US_NLCD&srs=EPSG:4 mapSpecs.push(wmsSpec); N ext, we pas s the array of mapSpecs to the GMap c ons truc tor and s et normal attributes with the A P I c alls . var map = new GMap(document.getElementById("map"),mapSpecs map.setMapType( _SATELLITE_TYPE ); map.addControl(new GLargeMapControl()); map.addControl(new GScaleControl()); T his puts the map layer c hoic es on the map. Without this , the only way to s elec t between M ap, Satellite, L ands at, V M A P 0 , N E D , and L andc over would be with c us tom navigations ay a button that triggers J avaSc ript to s et the appropriate map type. (M ap "type" is G oogle- s peak for "ras ter layer".) map.addControl(new GMapTypeControl()); map.centerAndZoom(new GPoint(-120, 38), 4); 7.5.3. The Virtues of Additional Map Layers D ifferent layers make more s ens e for different us es , and at different zoom levels . T he San Franc is c o Bay area looks s ort of patc hy in the G oogle Satellite image in Figure 7 - 9 . Figure 7-9. Google Satellite image of the Bay Areapretty choppy I n Figure 7 - 1 0 , the L ands at imagery is s moother and more informative at this s c ale. Figure 7-10. The Landsat image looks nice at this scale T he N ational E levation D atas et c overing the Bay A rea, s hown in Figure 7 - 1 1 is jus t beautiful. Figure 7-11. The National Elevation Dataset for the Bay Area A t a larger level, the N E D and L andc over images are us eful in unders tanding the natural his tory of the U nited States , as s hown in Figures 7 - 1 2 and 7 - 1 3 , res pec tively. Figure 7-12. U.S. Landcover Figure 7-13. U.S. National Elevation Dataset 7.5.4. Finding and Using Other WMS Servers We c an find WM S s ervers that have a lot of different data! A nd all thos e WM S s ervers are kind enough to tell us what information they have available. I onic Software provides the A s kT heSpider s ervic e at http://as kthes pider.c om/ to s erve as a c entral s earc h engine for the G eos patial Web. E ac h res ult from A s kT heSpider inc ludes the links to the G etC apabilities page for eac h s erver. You c an als o s earc h for "WM S Servers " on G oogle and be provided with a lot of c hoic es . To s ee whic h layers a WM S s erver has available, is s ue a GetCapabilities reques t. T his is an H T T P GET c all to a U RL , probably a s c ript, on the WM S s erver. For example, as k the WM S s erver at the J et P ropuls ion L aboratory (J P L ) what it c an deliver. L oad http://wms .jpl.nas a.gov/wms .c gi? reques t=G etC apabilities into your brows er, and an XM L file is returned. D epending on your brows er, the c apabilities will be dis played, or you may be given the opportunity to s ave the page to your loc al drive. Tec hnic ally, a proper c apabilities reques t needs the service and version parameters ; for example: http://wms.jpl.nasa.gov/wms.cgi?request=GetCapabilities&se =WMS&version=1.0.0 H owever, many WM S s ervers are forgiving about this . T he c apabilities doc ument from the J P L WM S s erver is a 1 ,6 9 6 line XM L doc ument that inc ludes lots of detail to s pec ify what is available. T he c apabilities doc ument will c ontain one or more Layer elements . H ere is part of one of the s horter Layer s ec tions from the J P L c apability doc ument: <Layer queryable="0"> <Name>us_colordem</Name> <Title>Digital Elevation Map of the United States, second resolution, hue mapped</Title> <Abstract> The DTED Level 3 US elevation, mapped to a co full spectrum. This result is not achievable by using SLD, so it different layer. </Abstract> <LatLonBoundingBox minx="-127" miny="23" maxx="-66" <Style> <Name>default</Name> <Title>Default Color Elevation</Title> </Style> <ScaleHint min="45" max="5000" /> <MinScaleDenominator>20000</MinScaleDenominator> </Layer> E ven with no more doc umentation on WM S, you c an gues s that this is the D igital E levation M ap of the U nited States , and you know that it has data for latitudes from 2 3 N to 5 0 N , and 1 2 7 W to 6 6 Wi.e., the c ontinental U nited States . T he original long reques t that generated an image of Florida s tarts to make more s ens e when you look at the full XM L GetCapabilities doc ument. E very element in the U RL is defined by the C apabilities doc ument. http://wms.jpl.nasa.gov/wms.cgi?request=GetMap&layers =global_mosaic_base&srs=EPSG:4326&bbox= -87.90,24.38,76.65,30.01&FORMAT=image/png&width=600&hei T he bas e U RL is defined in the OnlineResource element. T he available layers are in the Layer elements . T he s patial reference s ys tem, or SRS, c orres ponds to the exac t c artographic projec tion of the layer and is often defined by E uropean P etroleum Survey G roup, or E P SG , c odes (there is a long s tory behind this ). T hes e c odes are s ometimes referred to as s patial reference identifiers , or SRI D s . A n SRI D defines the s pec ific as s umptions that are being made about the s hape of the earth, how you mark loc ation, and where zero is . I n this c as e, E P SG 4 3 2 6 refers to the latitude/longitude geographic c oordinate s ys tem, referenc ed to the WG S- 8 4 s tandard ellips oid and datum. I f you have the P RO J .4 c artographic projec tions library (http://proj.maptools .org), you c an examine the lis t of E P SG c odes s tored in /us r/s hare/proj /eps g. I f you have P os tG I S (http://pos tgis .refrac tions .net/) ins talled you c an s ee what SRI D 4 3 2 6 means by looking in the spatial_ref_sys s ys tem table. I f you don't have P os tG I Sor don't want to botheryou c an mos tly as s ume that everything us es E P SG c ode 4 3 2 6 . T his is n't always true, but it is true often enough to be a us eful s implifying as s umption. = > select * from spatial_ref_sys where srid=4326; GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_198 257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.01745329 +proj=longlat +ellps=WGS84 +datum=WGS84 T he bounding box us ed in the bbox parameter defines the minimum and maximum latitude and longitude that will be inc luded in the returned map. T he format parameter is the image format to us e (P N G , J P G , P N G , P D F), the height and width are the number of pixels in the returned image, and the styles parameter is defined in the L ayers s ec tion and means whatever that partic ular s erver s ays that it means . With this knowledge, we c an make almos t any WM S s erver a s ourc e for imagery that will appear in a G oogle M aps interfac e on our own maps . We need to figure out the bas e U RL to generate maps from a partic ular WM S s erver. H ere is the GetCapabilities line for the J P L WM S s erver c ompared with the _WMSMapSpec that is needed by D avid's J avaSc ript: http://wms.jpl.nasa.gov/wms.cgi?request=GetCapabilities http://wms.jpl.nasa.gov/wms.cgi?request=GetMap&layers=glob base&srs=EPSG:4326 To get a map you replac e GetCapabilities with GetMap. T hen you mus t s pec ify the name of one or more layers . T hes e are from the Name element within the Layers s ec tion of the doc ument returned by the GetCapabilities reques t. You als o need to s pec ify the Spatial Referenc e Sys tem, whic h is in the SRS element within the Layer element. 7.5.5. See Also O pen G eos patial C ons ortium's D irec tory of Servic es at http://www.ogc network.org/. I nc ludes links to the WM S C ookbook at http://www.opengeos patial.org/res ourc es /? page=c ookbooks , as well as other doc uments , links to s ample applic ations , and s upport mailing lis ts . A nother WM S C ookbook maintained by A llan D oyle, the Kevin Bac on of the O pen G eos patial world: http://www.intl- interfac es .c om/c ookbook/WM S/. Hack 66. Add Your Own Custom Map This time, it's personal. Well, as everyone els e has written in this book, thos e G oogle M aps s ure are pretty. T hen again, there is always room for improvement right? A nd s ometimes G oogle's maps jus t don't highlight the right information. To really s pic e things up, you may want to add your own map…a map that looks the way you want it to look. T his off- A P I hac k s hows you how to add your own c us tom map. I n "Serve C us tom M ap I magery" [Hack #67], you'll get a s c ript to s erve c us tom map tiles , and finally in "A utomatic ally C ut and N ame C us tom M ap T iles " [Hack #68], there is a s c ript to quic kly make the thous ands of little images you will need to dis play your map. T here are plenty of c ool reas ons to add your own map images . I n c reating the N Y C Subway G oogle M ap hac k (http://www.onnyturf.c om/s ubwaymap.php), I felt that G oogle's polylines were not elegant enough, and they were hard to s ee on top of G oogle's orange/green default map. To make the s ubway lines eas ier to s ee agains t the s treets c ape and to make the lines look nic er, I dec ided to add a c us tom map type that I illus trated, as you c an s ee from Figure 7 - 1 4 . A nother great us e of adding your own map is us ing it as a s emitrans parent overlay on the other map images . Figure 7 - 1 5 s hows the s treet map layered on top of the s atellite map, with a s emi- trans parent s etting allowing you to s ee the relations hip between the two. You c an do this s ort of thing with your own c us tom map too. C reating this trans parenc y effec t is outs ide the s c ope of this tutorial. You c an learn how to add trans parenc y by looking at the s ourc e of the example above, whic h c an be found at http://www.kokogiak.c om/gmaps - trans parenc ies .html. You will need to know thes e bas ic s on adding a c us tom map in order to add trans parenc y in that way. Figure 7-14. Custom map for NYC subway map hack 7.6.1. Four Steps to Add a Custom Map T here are four s imple things you will need to do to add your own map. C reate a new map type. Tell the map where it c an find the images for your new type. C us tomize your map's type button. A dd your new map c ontrol to G oogle M aps ' lis t of map types . 7.6.2. Create a New Map Type T he G oogle M ap c omes with three default maps , whic h you are probably already familiar with, namely, map, s atellite, and hybrid. T hes e are known in G oogle M aps as map types , and they are ac c es s ed from an array c alled mapTypes, whic h is a property of our GMap objec t. To add your own map, we need to c reate a new map type and then add it to this array. Figure 7-15. Transparent road map overlaying the satellite map E ac h map type G oogle provides has many properties . We need to make our c us tom map type jus t like thes e. But we really don't want to have to build a whole map type from s c ratc h, s etting all the properties anew. We c an s ave a lot of time by duplic ating an exis ting map type and s witc hing jus t a few of the values to s uit our needs . For the N Y C Subway G oogle M ap hac k, I made my map type matc h G oogle's default map type. T his default map is the firs t map s tored in the mapTypes array. So we are jus t going to c opy that firs t map type and s tore it in a variable temporarily for editing (here it is named yourMapType, but you c an name this variable what ever you like). T here is one s pec ial thing we need to be aware of here; s inc e J avaSc ript as s igns objec t values by referenc e, we c an't jus t dupe the map type objec t like this : yourMapType = map.mapTypes[0]; We need to make s ure we c opy all the properties of the map type objec t, s o we have a s pec ial little func tion we are going to inc lude and c all to c opy all the properties of the default map type: function copy_obj(o) { var c = new Object(); for (var e in o) c[e] = o[e]; return c; } U s ing our copy_obj func tion, we c an now duplic ate the default map type: yourMapType = copy_obj(map.mapTypes[0]); N ow we c hange a few of the properties to c us tomize our map type. 7.6.3. Set the Path to Your Map Images E ac h G oogle map type is made up of thous ands of image tiles . When you s ee a G oogle map in a window, you are really s eeing about 1 2 tiles at a time, depending on your s c reen s ize, as s ugges ted by Figure 7 - 1 6 . A s you drag the map around in the window, your brows er downloads the tiles it needs in order to s how more of the map. T his happens in the bac kground and is one of the more innovative features of G oogle M aps . E ac h map type has a path to its as s oc iated image tiles . T his property is c alled baseURL. T he default maps point to G oogle's s erver. To load our own image tiles , we need this path to point at our own s erver. We ac tually don't point right at a direc tory of images . T he map s ends values to the s erver and as ks for an image in return. So we us e a P H P s c ript to s erve up the tiles bas ed on the values the map s ends (this image s erving s c ript is dis c us s ed in more detail later in "Serve C us tom M ap I magery" [Hack #67]). We s et the baseURL to point at this s c ript. yourMapType.baseUrl = "http://www.yoursite.com/googlemap/i You'll notic e we inc lude a ? at the end of our path. T he G oogle M aps applic ation adds C G I parameters at the end of the path when reques ting images , s o the ? is nec es s ary for pos ting thos e values . With that path c onfigured, our images will load when our c us tom map type is s elec ted. 7.6.4. Customize Your Map's Button Name A lthough the G oogle M ap A P I does not automatic ally add the map types buttons that appear in the upper- right c orner of their map, mos t people add them us ing the A P I addControl method. I f you c all this method in your map, a button will automatic ally be generated for your map type too, as you c an s ee on the Subway map s hown in Figure 7 - 1 7 . Figure 7-16. Google Maps tile grid H owever, that button did not jus t magic ally get the name "Subway." We s et the name of our map type's button by s etting the getLinkText property. T he G oogle M ap applic ation c alls it as a func tion, s o we want to return the name we want to give it, like s o: yourMapType.getLinkText = function() { return 'SUBWAY'; } You'll note that getLinkText is s et to a func tion. T his means you c an have that func tion return different values depending on external c onditions . N ic e and s imple eh? So that's all we have to do to make a c us tom map type. N ow we add it to the array mapTypes. 7.6.5. Add Your Map to the List of Map Types We will add our map to the end of the mapTypes array, and then, bec aus e we love our map more than any other map in the world, we s et it to be the default map when our map page firs t loads . To add our c us tom map to the lis t, we jus t add the map type objec t that we have been working on to the end of the array. We us e the A P I 's setMapType( ) method to make our c us tom map type load firs t. Figure 7-17. Subway map type button map.mapTypes[map.mapTypes.length] = yourMapType; map.setMapType(map.mapTypes[map.mapTypes.length-1]); Finally let's put it all in the c ontext of the res t of our typic al map initializing func tion. T his func tion is c alled from onLoad attribute of the body element in our H T M L : function onLoad() { //Create a new map and load it to the map at the html map = new GMap(document.getElementById('map')); // Copy Object Function function copy_obj(o) {var c = new Object(); for (var o[e]; } return c;} //Copy mapType yourMapType = copy_obj(map.mapTypes[0]); // Set Path to Our Custom Map Image Tiles yourMapType.baseUrl = "http://www.yoursite.com/googl php?"; // Map Display name in the auto-generated maplink in corner. yourMapType.getLinkText = function() { return 'SUBWA // Register the new mapType with the running google map.mapTypes[map.mapTypes.length] = yourMapType; //Set the onload view to our new map map.setMapType(map.mapTypes[map.mapTypes.length-1]); //Add Map Type buttons in the upper right corner map.addControl(new GMapTypeControl()); //Add Small zoom controls map.addControl(new GSmallZoomControl()); } E ven though we added our map to the lis t of map types , we s till need to s erve up the images when reques ted [Hack #67]. 7.6.6. See Also "A dd M ore I magery with a WM S I nterfac e" [Hack #65] "Serve C us tom M ap I magery" [Hack #67] "A utomatic ally C ut and N ame C us tom M ap T iles " [Hack #68] Will James Hack 67. Serve Custom Map Imagery You can serve your own custom tiles to Google Maps with a simple script. I f you've c reated a c us tom map layer [Hack #66], you need a way to s erve reques ts for tiles . T his hac k des c ribes a P H P s c ript to s erve G oogle M aps c ompatible imagery. E very time you drag the map around in the window, the G oogle M ap applic ation reques ts whatever tiles it needs in order to s how more of the map. I t does this by pas s ing three values to the s erver for eac h tile it needs : an X c oordinate value, a Y c oordinate value, and a Zoom value. For eac h tile it needs , the map applic ation s ends a s et of thes e three values . O ur image s erving s c ript us es the three values s ent by the G oogle M ap applic ation to dynamic ally c reate paths to the appropriate image required to fill in a s pac e in the map window. O ur s c ript is kept in a file named index.php. I t as s umes that tiles have been c reated and named by the naming s tandards des c ribed in "A utomatic ally C ut and N ame C us tom M ap T iles " [Hack #68]. With a little fanc y footwork we c an als o us e our s c ript to s end generic filler tiles to the map when we don't have c us tom tiles for a reques ted area. I n the mos t c ommon c as e, you will probably want to c reate a c us tom map that c overs a s mall area, and not the whole globe. T herefore you will probably need to us e s ome filler tiles where your map does not c over an area or zoom level. We c an us e our image s erving s c ript to determine when we don't have an appropriate c us tom tile and need to s end a filler tile. I f you dec ide that you do need to make tiles for the whole planet, be s ure to read "H ow Big I s the World? " [Hack #16] firs t! To unders tand this s c ript, we'll s tart with the whole thing and then break it down. H ere is the full s c ript that goes in our file index.php: <?php define("NO_DATA", "./no_data.gif"); define("ZOOM_IN", "./zoom_in.gif"); define("ZOOM_OUT", "./zoom_out.gif"); $x = $_GET["x"]; $y = $_GET["y"]; $z = $_GET["zoom"]; $filename = "./nycmaps/${x}_${y}_${z}.gif"; if ( $z < 2 ) { $content = file_get_contents( ZOOM_OUT ); }else if ( $z > 5 ){ $content = file_get_contents( ZOOM_IN ); }else if ( is_numeric($x) && is_numeric($y) && is_n && file_exists( $filename ) ){ $content = file_get_contents( $filename }else{ $content = file_get_contents( NO_DATA ); } header("Content-type: image/gif"); echo $content; ?> O K, there it is . N ow let's break it down. T he firs t three lines define our filler tiles . We have one for eac h of three c onditions . I f we are in an area for whic h we have data, but not at the c urrent zoom level, we us e the zoom_in.gif and zoom_out.gif images . I f we have no data, we s end the no_data.gif image. <?php define("ZOOM_IN", "./maptiles/zoom_in.gif"); define("ZOOM_OUT", "./maptiles/zoom_out.gif"); define("NO_DATA", "./maptiles/no_data.gif"); You'll notic e that above we als o s et the path to thes e tiles to a direc tory c alled maptiles /. T his is where we will put all our image tiles . T his direc tory s its ins ide the images / folder, where this s c ript als o res ides , as es tablis hed in "A dd Your O wn C us tom M ap" [Hack #66]. N ext we get the x, y, and zoom values from the map and s tore them in s imilarly named variables . $x = $_GET["x"]; $y = $_GET["y"]; $z = $_GET["zoom"]; U s ing thes e three values , we c reate a path to a tile file, here a G I F, and we s tore it in the variable $filename. You'll note that the x, y, and zoom (z) values are part of the tile name. T his is the bas ic s truc ture we us e to name all our tiles . T his is how we differentiate the hundreds or thous ands of c us tom tiles we likely end up with when c reating a c us tom map. N ow that's a lot of c us tom names , but don't worry about it too muc h, bec aus e later we'll automate the c utting and naming of your tiles . $filename = "./maptiles/${x}_${y}_${z}.gif"; N ow we have a path appropriate to the data s ent, but that does not mean the tile ac tually exis ts . $filename, whatever its value, is jus t a fourth image option, in addition to NO_DATA, ZOOM_IN, and ZOOM_OUT. Before we s end any image bac k to the brows er, we want to c hec k if the reques t is within our zoom range and map area. T his next c hunk of the s c ript us es s everal if/else s tatements to filter though the pos s ibilities and determine the appropriate image. T he winner will be s tored in variable $content. T he s pec ific c hec ks we make are explained by the in- line c omments : // if the zoom level requested is too close, we send image // say zoom out if ( $z < 2 ) { $content = file_get_contents( ZOOM_OUT ); // if the zoom level requested is too far out, we send ima // say zoom in } else if ( $z > 5 ){ $content = file_get_contents( ZOOM_IN ); // here we make sure values were sent for x, y, and zoom, // the image tile actually exists. if it all checks out we // the file we defined in $filename } else if ( is_numeric($x) && is_numeric($y) && is_numeric && file_exists( $filename ) ){ $content = file_get_contents( $filename ); // otherwise, if one of the values was not sent, or the ti // not exist we send a NO_DATA image } else { $content = file_get_contents( NO_DATA ); } N ow that we know whic h image we are s ending bac k, we are ready to do s o. T he reas on we didn't jus t s end it previous ly is that we firs t need to tell the brows er that we are s ending an image. We tell it this by s ending it s ome header information: header("Content-type: image/gif"); N ow we c an pas s it the image path with a s imple ec ho of $content echo $content; ?> 7.7.1. Conclusion T hat's all there is to it! Save it as index.php and upload it to your image folder. T here are two things I really like about this s c ript that make it a lifes aver. T he firs t is the NO_DATA c ondition. For the s ubway map, I made only tiles that c overed the greater N Y C area. O uts ide that, there are no c us tom tiles . Without the NO_DATA image, in thes e plac es where I don't have tiles to matc h G oogle's , we would normally s ee broken image links or the grey bac kground of the map window. But thanks to the NO_DATA image, I c an c reate one blue tile that matc hes my border and extends infinitely anywhere I don't have c us tom tiles for a loc ation. Figures 7 - 1 8 , 7 - 1 9 , and 7 - 2 0 s how what my zoom- in, zoom- out, and no- data files look like. Figure 7-18. Zoom-in image Figure 7-19. Zoom-out image Figure 7-20. No-data image A lternatively for thos e more advanc ed, you c ould extend this s c ript to relay the x, y, and zoom values bac k to G oogle; then you c ould reques t their tiles for plac es where you do not have any. T he other thing I like about this s c ript is that you c an quic kly adjus t whic h zoom levels are available. You jus t s et min and max thres holds in thos e if/else s tatements and you get alternative tiles s ent to the map for anything outs ide your zoom range. I n c reating the N Y C Subway M ap, I tweaked the map art at eac h level. T his is a bit time c ons uming, but gives me better- looking maps . So I inc rementally add new zoom levels as I c omplete the art. E very time I add a new one all I have to do is go into this s c ript and c hange the min or max value to make it available. 7.7.2. See Also "A dd Your O wn C us tom M ap" [Hack #66] "A utomatic ally C ut and N ame C us tom M ap T iles " [Hack #68] Will James Hack 68. Automatically Cut and Name Custom Map Tiles Make time to really enjoy a cup of cof f ee. G oogle M aps are made of dozens to thous ands of tile images , depending on the zoom level. A t the dis tant zoom levels you only need a few images to c over a large area. For example, the N Y C Subway M ap us es 4 9 images to c over the greater metropolitan area at zoom level 5 . But at the c los er zoom levels , thous ands of images are required. I t takes more than 3 5 0 0 images to c over the N Y C metropolitan area at zoom level 2 . "H ow Big I s the World? " [Hack #16] dis c us s es the amount of dis k s pac e needed to tile the entire planet. Figure 7 - 2 1 s hows a c us tom tile at zoom level 5 , while Figure 7 - 2 2 s hows part of the s ame area at zoom level 2 . C reating and then uniquely naming eac h of thes e images for even a s mall part of our world would be a daunting tas k if you had to do it by hand. T hat's why we us e a s c ript to do this . T he following hac k will s how you how to c onfigure a batc h proc es s ing s c ript to us e with P hotos hop 7 or C S that will c arve all the tiles you need from one big image into hundreds of s maller G I Fs and name them exac tly as you need them named. 7.8.1. The Google Map Tile Structure Before we s et up and us e our s c ript we need to know a few things about G oogle's tiles . A s we learned in "Serve C us tom M ap I magery" [Hack #67], eac h 2 5 6 X 2 5 6 pixel tile has a longitude, a latitude, and a zoom value. T hes e are repres ented in the U RL by the x, y, and zoom values . Figure 7-21. A custom tile at zoom level 5 Figure 7-22. A custom tile at zoom level 2 H ere is what a tile path from G oogle looks like: http://mt.google.com/mt?v=w2.4&x=1206&y=1539&zoom=5 7.8.2. Figuring Out the Values for Your Tiles So how do you get the x, y, and zoom values ? Fortunately you don't have to get all the x, y, and z values for all your images . We only need to get a s et of values for one tile and from there we c an derive all the other values we need. We s tart with a limited area for our map bec aus e we as s ume you don't want to remap the whole world, but jus t a s mall c orner of it. A ll we need then is to get the x, y, and z value of the upper- left c orner tile of our map area and know how many tiles wide and high our map area is . For s implic ity, our example map is s quare s o that the area width and height are the s ame, but you c ould tweak this s c ript to work with rec tangular areas . O nc e we know the upper- left c orner tile values , our batc h proc es s ing s c ript will c alc ulate the res t for us . U nfortunately getting jus t thes e c orner tile values is not eas y on our own. Fortunately again there is a web s ite that will help do this for us . T he s ite at http://www.onnyturf.c om/google/latlontotile.html has a s et of tools that will help us figure out this information for the upperleft c orner tile values . Figure 7 - 2 3 illus trates the proc es s of c onverting lat/long to tile row and c olumn. Figure 7-23. Converting latitude and longitude to tile row and column U s ing the map on the right s ide of this page you c an find the c enter of your map area. When you c lic k there the web page will get the latitude and longitude for the c enter of your map. You c an als o s et the zoom level and tile width here. When you pres s s ubmit, the web s ite will return G oogle's tiles that make up your reques ted map area. For our batc h proc es s ing s c ript, you will want to do this for your furthes t zoom level. You'll probably have to experiment a little until you get the right values that matc h your map area. For my N Y C Subway map, the furthes t zoom level is 5 and my tile width is 7 , as s hown in Figure 7 - 2 4 . Your maximum zoom level will probably be s omewhere between 5 and 8. Figure 7-24. Finding the upper-left corner for a given latitude/longitude To get the values for the upper- left c orner tile, we now jus t rightc lic k on that tile and s elec t V iew I mage. T his will load the image into the brows er window, and now we c an s ee our x, y, and zoom values in the image U RL : http://mt.google.com/mt?v=w2.4&x=1206&y=1539&zoom=5 Whew. So there it is . N ow we know our s tart values for this example are: x = 1206 y = 1539 zoom = 5 tile width = 7 7.8.3. Configuring the Script T he batc h proc es s ing s c ript provided is too long to go through in detail here. T his hac k foc us es on s howing you how to c onfigure it for your map area s o you c an make your tiles . To us e the s c ript provided you mus t enter s ome c us tom values , inc luding the ones we jus t got for our upper- lefthand tile. T he values you mus t c us tomize c ome at the beginning of the s c ript. 7.8.3.1. ZoomLevel. L as t things firs t. T he firs t variable you enc ounter s ets the Zoom L evel you want to generate tiles for. To c reate your c us tom map you will probably want tiles at various levels . For eac h level you want to c reate tiles for, you mus t c hange this value and rerun the batc h proc es s ing s c ript on your mas ter art. H ere it is s et to 3 , but you will c hange this every time you want to run this s c ript for another level. var ZoomLevel = 3; T he res t of the variables you mus t c us tomize you will only c us tomize once for your map area. L et's go through them one by one. 7.8.3.2. FolderPath. T his next one s ets the path to where your tiles will be s aved. T his path is for us e on a P C . T he path on the M ac will be s lightly different. T his s ample path us es a s eparate folder for eac h zoom level, and thos e folders are in a folder GoogleMap that s its on the us er des ktop. You will have to prec reate your zoom folders , but the path to thos e folders is dynamic ally generated in this example. var FolderPath = "~/Desktop/GoogleMap/Zoom"+ZoomLevel+"Map 7.8.3.3. Furthest zoom upper-left corner values. L as tly, we put our upper- left c orner values to work. T hes e are the originating values , off of whic h the batc h proc es s ing s c ript will figure out the values for all the tiles you are c reating. var var var var var OrgX = 1204; //<-- the X value OrgY = 1536; //<-- the Y value OrgZoomLevel = 5; //<-- the zoom level OrgTileWidth = 7; //<-- the number of tiles wide your OrgTileHeight = 7; //<-- the number of tiles high your T hat's all you have to c onfigure! H ere is how the whole thing looks with our c us tomized values at the top: /* Tile Carver for Photoshop 7 and CS Created by Will James http://onNYTurf.com */ //**** CUSTOMIZE THE FOLLOWING VARIABLES FOR YOUR MAP AREA var ZoomLevel = 3; var FolderPath = "~/Desktop/GoogleMap/Zoom"+ZoomLevel+"Map var OrgX = 1204; var var var var OrgY = 1536; OrgZoomLevel = 5; OrgTileWidth = 6; OrgTileHeight = 6; //**** EVERYTHING BEYOND THIS POINT SHOULD NOT BE TOUCHED //**** UNLESS YOU KNOW WHAT YOU ARE DOING!!! **** var StartX = OrgX * (OrgZoomLevel - MakeZoomLevel) * 2; var StartY = OrgY * (OrgZoomLevel - MakeZoomLevel) * 2; var xTiles = OrgTileWidth * (OrgZoomLevel - MakeZoomLevel) var yTiles = OrgTileHeight * (OrgZoomLevel - MakeZoomLevel var PixelWidth = 256; var PixelHeight = 256; var TotalTiles = (xTiles)*(yTiles); preferences.rulerUnits = Units.PIXELS; var xm = 0; var ym = 0; var TileX = StartX; var TileY = StartY; for (n=1; n<TotalTiles+1; n++) { if (ym == yTiles){ xm += 1; ym = 0; TileX += 1; TileY = StartY; }; MyXO MyXL MyYO MyYL = = = = xm*(PixelWidth); xm*(PixelWidth)+(PixelWidth); ym*(PixelHeight); ym*(PixelHeight)+(PixelHeight); var srcDoc = activeDocument; srcDoc.selection.select(Array (Array(MyXO, MyYO), Arra Array(MyXL, MyYL), Array(MyXO, MyYL)), SelectionType srcDoc.selection.copy(); var pasteDoc = documents.add(PixelWidth, PixelHeight, "Paste Target"); pasteDoc.paste(); pasteDoc = null; var saveMe = activeDocument; saveMe.flatten(); saveFile = new File(FolderPath + TileX+ "_" + TileY+ + ".gif"); gifSaveOptions = new GIFSaveOptions(); gifSaveOptions.colors = 64; gifSaveOptions.dither = Dither.NONE; gifSaveOptions.matte = MatteType.NONE; gifSaveOptions.preserveExactColors = 0; gifSaveOptions.transparency = 0; gifSaveOptions.interlaced = 0; saveMe.saveAs(saveFile, gifSaveOptions, true,Extension saveMe.close(SaveOptions.DONOTSAVECHANGES); ym += 1; TileY += 1; } A t http://mapki.c om/index.php? title=A utomatic _T ile_C utter, you c an get c opies of this s c ript. Save your s c ript as TileCutterNamer.j s , as it is a J avaSc ript file. P ut the s c ript s omewhere eas y to find, bec aus e next you are going to open it from P hotos hop. 7.8.4. Running Our Script in Photoshop We are going to c ut our tiles from one big image. For the N Y C Subway map, I c reated my map art in A dobe I llus trator and then imported it into P hotos hop. A s you c reate your c us tom map, an important thing to keep in mind is to know how wide and high to make your map art. I s tarted in I llus trator with the dimens ions for the furthes t zoom level; then, when I open the art in P hotos hop, I tell P hotos hop to c reate a bitmap to matc h whic hever zoom level I am working on. We c an figure out how wide and high our art mus t be by multiplying the total number of tiles ac ros s and down by the individual tile width of 2 5 6 pixels . For my furthes t zoom, the width and height of the s ubway map ends up being 1 ,7 9 2 pixels : 7 tiles wide by 2 5 6 pixels . But in our example batc h proc es s ing s c ript, we are making tiles for zoom level 3 ; 1 ,7 9 2 X 1 ,7 9 2 pixels is going to be too s mall an image to c arve all our tiles from. So how do we get the right width and height for other zoom levels ? E very zoom level is twic e the height and width of its previous zoom level. So, if our firs t zoom level was 1 ,7 9 2 pixels wide, we end up with a matrix like Table 7 - 1 . Table 7-1. Zoom level versus pre-tiled map width Zoom level Pixel width 5 1 ,7 9 2 4 3 ,5 8 4 3 7 ,1 6 8 2 1 4 ,3 3 6 To batc h proc es s tiles for zoom level 3 then, I s tart with a file 7 ,1 6 8 pixels wide. By the way, this is 2 8 tiles ac ros s . We know that bec aus e 7 ,1 6 8 pixels divided by 2 5 6 pixels is 2 8 . For a s quare map area 2 8 pixels wide by 2 8 pixels high, we are then making 7 8 4 tiles ! T hank goodnes s this s c ript als o names thes e tiles for us ! G etting bac k to our batc h proc es s or, I open my I llus trator art into P hotos hop at 7 ,1 6 8 X 7 ,1 6 8 pixels , as s hown in Figure 7 - 25. Figure 7-25. Photoshop's File Import dialog O nc e the file is ras terized, we run the J avaSc ript by going to File A utomate Sc ripts . I n P hotos hop 7 , this will pop up a s mall dialogue box. C hoos e Brows e and then find the TileCutterNamer.j s file and c lic k O pen. O ff it goes ! A s the s c ript runs , you c an watc h P hotos hop make new tiles and s ave them. Fun, I know. I f you are c utting a s mall number of tiles les s than 6 0 , s aythe proc es s will take only about a minute. For s omething like 7 0 0 tiles , it will take 1 0 minutes or more. L evel 3 of my s ubway map is made of more than 3 ,5 0 0 tiles . I f you are c utting that many, you might want to make s ome other plans for the next hour. T his might be the time to enjoy that c up of c offee. When the s c ript has finis hed c utting the las t tile, you will have a folder full of images , as s hown in Figure 7 - 2 6 . Figure 7-26. The list of completed custom map tiles T he only thing left to do then is upload your new zoom level to your maptiles / folder on your s erver and then go and c hec k out your new map in your web page! 7.8.5. Hacking the Hack T his batc h proc es s ing s c ript is written to produc e G I Fs . I t c ould als o be written to produc e J P G s or P N G s . You will have to c us tomize the s ettings in this part of the s c ript: //Set path to file and file name saveFile = new File(FolderPath + TileX+ "_" + TileY+ "_" + ZoomLevel + ".gif"); //Set save options gifSaveOptions = new GIFSaveOptions(); gifSaveOptions.colors = 64; gifSaveOptions.dither = Dither.NONE; gifSaveOptions.matte = MatteType.NONE; gifSaveOptions.preserveExactColors = 0; gifSaveOptions.transparency = 0; gifSaveOptions.interlaced = 0; 7.8.6. See Also "A dd Your O wn C us tom M ap" [Hack #66] "Serve C us tom M ap I magery" [Hack #67] Will James Hack 69. Cluster Markers at High Zoom Levels When necessary, avoid cramming a map too f ull of markers by clustering them together. Two major problems c an oc c ur when you try to put too many markers on a G oogle M ap at onc e. Firs t, the large quantity of markers c an take a long time to render, c ons ume a lot of memory in the brows er, and pretty muc h s low things to a c rawl. We addres s this partic ular problem to s ome degree in "Show L ots of StuffQ uic kly" [Hack #59]. T he other, equally s erious problem is a more general matter of good digital c artography, in that too many markers plac ed too c los e together c an make the markers diffic ult to c lic k and the map diffic ult to interpret. Both problems c an be fairly effec tively s olved by firs t applying a c lus tering algorithm to a large data s et of points , and then by tailoring the dis play of the point c lus ters , s uc h that they bec ome readily identifiable and eas y to interac t with. 7.9.1. The Hack To experiment with this idea, we took over 6 0 0 waypoints from Ric h G ibs on's G P S rec eiver, repres enting the highlights of s everal years ' worth of travels . Sinc e Ric h lives in northern C alifornia, mos t of the points are c entered around the wes tern U nited States , while the remainder are s c attered from M exic o to M as s ac hus etts to Venic e, I taly. We figured that about 6 0 0 points would qualify as too many to s how on a map at onc e, but not s o many as to make experimentation diffic ult. T he s olution that we eventually hit upon for vis ualizing all of Ric h's travels at onc e c an be s een at http://mappinghac ks .c om/projec ts /gmaps /c lus ter.html, as s hown in Figure 7 - 2 7 . T he s tandard G oogle M aps marker is us ed to repres ent a c lus ter of points , roughly bounded by the red box around the marker. C lic king on a marker pans and zooms the map to the area c overed by that c lus ter. A s you get c los er in, more loc alized c lus ters appear, eventually res olving into the s mall G oogle Ridefinder markers , whic h repres ent Ric h's individual waypoints . C lic king on one of thes e s maller markers opens a s mall info window, s howing the name and c oordinates of the waypoint, as s hown in Figure 7 - 2 8 . Figure 7-27. Clusters of points show the general outlines of Rich's travels A lthough this demo has s ome obvious defic ienc ies , we think that, to s ome degree, it does s uc c eed at s ummarizing the data at high zoom levels , while s till allowing exploration of the individual data points . C oming up with a lightweight and reas onably fas t s olution to this problem took a lot of trial and error! Before we take a look at the c ode, let's peer down the blind alleys we followed before finally s ettling on our c urrent implementation. 7.9.2. Choosing the Right Clustering Algorithm Stepping away from the map for a moment, let's res tate the problem: we have a large number of points in a two- dimens ional c oordinate s ys tem, whic h we want to as s ign to a muc h s maller number of c lus ters , bas ed in s ome way on their relative proximity to eac h other. T his is a fairly c ommon problem in c omputational s tatis tic s , and s everal well- doc umented algorithms already exis t. Figure 7-28. Zooming in causes the clusters to resolve as individual waypoints 7.9.2.1. k-means clustering. T he firs t one we tried was the k-means clus tering algorithm, whic h is one of the mos t popular c lus tering algorithms in the literature, on ac c ount of its relative s implic ity: 1. Selec t a c enter point for eac h of k c lus ters , where k is a s mall integer. 2. A s s ign eac h data point to the c lus ter whos e c enter point is c los es t. 3. A fter all the data points are as s igned, move eac h c lus ter's c enter point to the arithmetic mean of the c oordinates of all the points in that c lus ter, treating eac h dimens ion s eparately. 4. Repeat from Step 2 , until the c enter points s top moving. T he other advantage to k- means c lus tering, as ide from its eas e of implementation, is that it is relatively quic k, us ually c ompleting in les s than O (n 2) time. T he mos t obvious dis advantage of k- means is that you have to s omehow s elec t the value of k ahead of time, but we c ould try to make an educ ated gues s about that. T he primary dis advantage of k- means derives from the ambiguity of Step 1 : how, exac tly, does one s elec t the initial c enter points ? We found that s elec ting random points in s pac e led to s ome c lus ters never ac quiring points at all, while randomly s elec ting points from the data s et as initial c enters led to the c lus ters thems elves c lumping up, whic h is s omething we were trying to avoid. A ny attempt to c hoos e k or the initial c enters bas ed on the data its elf only c omplic ated matters , in a s ort of rec urs ive fas hion. A ls o, to top it all off, k- means apparently offers not only no guarantee that a globally optimum c lus tering will res ult, but not even any guarantee that a "loc ally" optimum c lus tering will res ult. I t looked like we were bac k to the drawing board. 7.9.2.2. Hierarchical clustering. T he next approac h we tried was a s eries of variations on hierarchical clus tering algorithms . I ns tead of iteratively building c lus ters from the top down, as k- means does , hierarc hic al algorithms attempt to c lus ter the data from the bottom up, ins tead. A typic al hierarc hic al c lus tering algorithm works as follows : 1. A s s ign eac h point to its own c lus ter. 2. C alc ulate the dis tanc e from eac h c lus ter to every other c lus ter, either from their res pec tive mean c enters , or from the two neares t points from eac h c lus ter. 3. Take the two c los es t c lus ters and c ombine them into one c lus ter. 4. Repeat from Step 2 , until you have the right number of c lus ters , or the c lus ters are s ome minimum dis tanc e apart from eac h other, or until you have one big c lus ter. By now, you c an probably gues s that hierarc hic al c lus tering pres ents at leas t one of the s ame problems as k- means namely, that you have to know s omehow when you have enough c lus ters . A ls o, though hierarc hic al c lus tering c an be s hown to produc e globally optimal res ults , optimality c omes with a c os t: hierarc hic al c lus tering algorithms are frequently known to run to O (n 3) time in the wors t c as e. A lthough this c an be mitigated s omewhat by c lever us e of data s truc tures , s uc h as us ing a heap to s tore the lis t of c lus ter dis tanc es , we found that our bes t attempt at implementing hierarc hic al algorithms provided reliable res ults , but it was , quite frankly, too s low. P olynomialtime algorithms are abs olutely fine when n is s mall, but we wanted an approac h that c ould potentially s c ale to thous ands of points and be able to run dynamic ally in a reas onable time for an H T T P reques t. T he hierarc hic al approac h apparently jus t was n't it for us . 7.9.2.3. Naïve grid-based clustering. We realized, of c ours e, that we were looking at the problem the wrong way: we didn't need optimal c lus tering, or mathematic ally prec is e c lus tering, or anything like that. What we were after was s ome way of c ons olidating points on a map s uc h that: (a) the markers we dis play don't wind up overlapping, and (b) we don't s how too many markers at onc e. We c an s olve requirement (a) by drawing a grid on the map, as s hown in Figure 7 - 2 9 , s uc h that eac h "c ell" in the grid is guaranteed to be at leas t as large as our marker image when the map is dis played. N ext, we take all of the points within any one grid c ell and c all them a s ingle c lus ter. For added meas ure, we c an als o c hec k eac h c lus ter formed this way and s ee if there are any c lus ters in the immediately adjac ent c ells . I f there are, we c ombine them them into a s ingle larger c lus ter. Figure 7-29. Assignment of points to clusters based on grid cell membership By definition, this approac h is guaranteed to s olve requirement (a), but how likely is it to s olve requirement (b)? I nitially, we note that the number of c lus ters we wind up with is n't s ens itive to the number of points being c lus tered, jus t to their dis tribution. L et us as s ume the wors t c as e, where there is at leas t one point in every potential c ell. L et us s uppos e that a G oogle M ap of the entire world c ould be as large as 1 ,0 2 4 pixels wide and 7 6 8 pixels high, thereby taking up all of an ordinary des ktop s c reen. I f the default G oogle M aps ic on is 2 0 X 3 4 pixels , then we get a wors t c as e of (1 ,0 2 4 ÷ 2 0 ) X (7 6 8 ÷ 3 4 ) = about 1 ,1 5 6 c ells or, at mos t, 1 ,1 9 6 c ells if we round up both s ides of the produc t. H owever, s inc e every nine c ells will be c ombined into a s uperc lus ter, we wind up with an abs olute wors t- c as e maximum of under 1 5 0 c lus ters , whic h, although not great, is n't horrifying, either. L et's jus t s ay that if you have a data s et that c overs the entire s urfac e of the planet, you might think about us ing s omething other than G oogle M aps to illus trate it. A ls o, you c an s ee that the algorithm is more s ens itive to the s ize of the grid c ells than anything els e. A t the very leas t, even if our naïve grid- bas ed algorithm is n't perfec t, it c an be s hown to run in O (n) time, whic h is an improvement over our earlier experiments . 7.9.3. The Code T he c ode we developed to tes t the grid- bas ed c lus tering algorithm has two parts : firs t, a C G I s c ript written in P erl runs on the s erver s ide, whic h filters a file of waypoints for thos e points within a given bounding box, c lus ters thos e points as des c ribed above, and then s pits out an XM L file des c ribing the c lus ters ; and s ec ond, an H T M L page on our s erver c ontains c lient- s ide J avaSc ript that us es the G oogle M aps A P I to fetc h the c lus ter des c ription for the c urrent map view and plot the c lus ters on the map. 7.9.3.1. The server-side CGI script. T he C G I s c ript its elf is only 1 2 0 lines of P erl, but we'll jus t s how the highlights here. I f you're interes ted in looking at the full s ourc e, you c an find it at http://mappinghac ks .c om/projec ts /gmaps /c lus ter- grid.txt. M uc h like the G oogle M aps interfac e, our s c ript expec ts a lat/long c enter point for the map, and a map s pan, meas ured in degrees latitude and longitude. A dditionally, bec aus e the map geometry matters to our c alc ulations , we als o expec t a width and height for the intended map in pixels . T he following P erl c ode takes c are of that: my $q = CGI->new; my %var = $q->Vars; if ($var{ll} and $var{spn}) { my ($lon, $lat) = split( " ", $var{ll} ); my ($width, $height) = split( " ", $var{spn} ); $bbox = [ $lon - $width/2, $lat - $height/2, $lon + $width/2, $lat + $height/2 ]; } if ($var{size}) { my ($width, $height) = split( " ", $var{size} ); $size = [ $width, $height ]; } T he res ult is that the $bbox variable c ontains a referenc e to an array lis ting the minimum longitude and latitude, and the maximum longitude and latitude for our map, in that order. T he $size variable s imilarly s tores the width and height of the map in pixels . We then pas s $bbox to a func tion that loads the waypoints from a c omma- delimited file, keeping only the ones that fit within our bounding box: while (<FH>) { chomp; my ($lat, $lon, $name) = split /,\s+/, $_; push @data, [$lon, $lat, $name] if $lon >= $bbox->[0] and $lon <= $bbox->[2] and $lat >= $bbox->[1] and $lat <= $bbox->[3]; } T his hac k would be more elegant if we pars ed the waypoints from a G P X file ins tead, but we were aiming to s implify the problem as muc h as pos s ible, from a tec hnic al s tandpoint. T he points thems elves are returned as a referenc e to an array of arrays . We then es timate the grid s ize in degrees , s tarting with a hardc oded ic on s ize in pixels , as follows : my $icon_size = [ 20, 34 ]; my $grid_x = $icon_size->[0] / $map_size->[0] * ($bbox->[2 my $grid_y = $icon_size->[1] / $map_size->[1] * ($bbox->[3 Bas ic ally, we divide the width of the marker ic on (in pixels ) by the width of the entire map (als o in pixels ), whic h gives us a proportion of the map that a s ingle marker would c over, in the horizontal dimens ion. We multiply this frac tion by the total s pan of the map in degrees longitude, to yield the number of degrees longitude that a marker would c over on a map of this s ize and s pan. We then perform the s ame c alc ulation the marker height, map height, and map s pan in degrees latitude to get the marker height in degrees latitude. By making our grid c ells at leas t this many degrees wide and high, we c an guarantee that none of the markers we plac e on the map will vis ually overlap eac h other by muc h, if at all. We then c all the cluster() func tion, whic h takes the bounding box, the grid c ell s ize, and the data points as arguments : sub cluster { my ($bbox, $grid, $data) = @_; my %cluster; for my $point (@$data) { my $col = int( ($point->[0] - $bbox->[0]) / $gridmy $row = int( ($point->[1] - $bbox->[1]) / $gridpush @{$cluster{"$col,$row"}}, $point; } T hes e few lines of c ode ac tually do all the work of as s igning eac h point to a c lus ter. We divide the differenc e between the point's longitude and the wes tern edge of the map by the grid c ell s ize, whic h, dis c arding the remainder, gives us the grid c olumn that the point lies within. We follow a parallel c alc ulation to determine the row of the point, c ounting from s outh to north. We then pus h the point on to a has h of arrays that lis ts the points within eac h c ell. Sinc e we plan to take eac h c ell that c ontains one or more points as an initial c lus ter, this has h is s imply c alled %cluster. We're already halfway finis hed. T he next bit of c ode is a bit tric ker, as it c onc erns the neighbor analys is that we us e to c ombine adjac ent c lus ters into s uperc lus ters . A s a heuris tic , we as s ume that the points are already naturally c lus tered in s ome way and c onc lude that the dens es t of our initial c lus ters are mos t likely to be the "c enters " of the c ombined s uperc lus ters . We implement this heuris tic by s orting the lis t of c lus ters we've found, ac c ording to the number of points within eac h one, in des c ending order: my @groups = sort { @{$cluster{$b}} <=> @{$cluster{$a}} } We then iterate over the lis t of c lus ters , looking at the eight c ells immediately adjac ent to eac h one. I f any of the adjac ent c ells als o c ontains a c lus ter, we add the points from that c lus ter to our new s uperc lus ter and remove the s ubs umed c lus ter from our lis t. Finally, when all is s aid and done, we return an array of arrays , c ontaining our original points grouped into c lus ters . for my $group (@groups) { next unless $cluster{$group}; my ($col, $row) = split ",", $group; for my $dx (-1 .. 1) { for my $dy (-1 .. 1) { next unless $dx or $dy; $dx += $col; $dy += $row; if (exists $cluster{"$dx,$dy"}) { my $other = delete $cluster{"$dx,$dy"} push @{$cluster{$group}}, @$other; } } } } return [values %cluster]; } We won't bore you with the tedious details of generating XM L from this data s truc ture; onc e again, you c an refer to the s ourc e c ode online, if you're partic ularly interes ted. H owever, in order to unders tand how the J avaSc ript frontend works , it's worth looking at an example output from this s c ript: <points> <cluster lat="40.76706" lon="-123.334565" points="187" width="1.85699" height="6.57074" <cluster lat="44.40734" lon="10.832265" points="70" width="3.33653" height="5.03806" / <cluster lat="41.507245" lon="-72.426195" points="10" width="2.74580999" height="1.73063 <cluster lat="39.27062" lon="-115.56396" points="239" width="13.66804" height="11.94808 <point name="CAIRO" lat="30.05671" lon="31.23585" /> </points> A s you c an s ee, this doc ument c ontains enough information to draw eac h c lus ter, as well as to allow the U I to zoom direc tly in on the extents of any one c lus ter. Finally, any c lus ter with only one point is n't really a c lus ter: it's jus t a point and is treated as s uc h. T he J avaSc ript us er interfac e therefore only needs to be able to pas s the map c enter, s pan, and s ize into this s c ript, and then be able to pars e the c lus ter and point des c riptions from the XM L output. 7.9.3.2. The client-side JavaScript. N aturally, the J avaSc ript frontend to this c lus tering experiment needs to do all the us ual things to import the G oogle M aps A P I c ode and s et up the map its elf. T hes e tas ks are already wellc overed els ewhere in this book, and, of c ours e, you c an always V iew Sourc e on the demo page, if you're interes ted in the details . We'll go s traight to the loadClusters() func tion, whic h c alls our C G I s c ript when the page is loaded: function loadClusters () { var request = GXmlHttp.create(); var center = map.getCenterLatLng(); var span = map.getSpanLatLng(); var url = "http://mappinghacks.com/projects/gmaps/cluster url += "ll=" + center.x + "+" + center.y + "&spn=" + span.width + "+" + span.height + "&size=" + map.mapSize.width + "+" + map.mapSize. request.open("GET", url, true); request.onreadystatechange = function() { if (request.readyState == 4) showOverlays(request.responseXML); }; } T his c ode initiates a GXmlHttp reques t in the us ual way, pas s ing in the map c enter, s pan, and s ize. T he map.mapSize property us ed here is undoc umented in the G oogle M aps A P I , but you c ould almos t c ertainly us e the D O M A P I to find out the width and height s tyles of the map div element ins tead. When the H T T P reques t returns , the pars ed XM L doc ument is pas s ed to the showOverlays() func tion, whic h is s hown below: function showOverlays (xml) { map.clearOverlays(); var cluster = xml.documentElement.getElementsByTagName for (var i = 0; i < cluster.length; i++) { showCluster( cluster[i] ); } var point = xml.documentElement.getElementsByTagName(" for (var i = 0; i < point.length; i++) { showPoint( point[i] ); } } T he showOverlays() func tion c lears the map of its exis ting overlays and then us es the getElementsByTagName() method from the D oc ument O bjec t M odel A P I to extrac t eac h cluster and point element from the XM L doc ument, pas s ing them one by one to the appropriate rendering func tion. T he showPoint() func tion does n't do anything more exc iting than put a marker on the map in the appropriate plac e and bind an info window popup to the c lic k event. L et's look at the showCluster() func tion, ins tead, bec aus e that's where mos t of the exc itement really is : function showCluster (elem) { var point = new GPoint(parseFloat(elem.getAttribut parseFloat(elem.getAttribut var width = parseFloat(elem.getAttribute("width")) height = parseFloat(elem.getAttribute("height" count = parseInt(elem.getAttribute("count")); var marker = new GMarker(point); T he showCluster() func tion pars es the various attributes out of the cluster element and us es the latitude and longitude to c reate a new marker. So far, no s urpris es . T he ac tion that we bind to that marker's c lic k event is muc h more interes ting: GEvent.addListener(marker, "click", function() { var span = new GSize(width * 1.1, height * 1.1 // undocumented: http://xrl.us/getLowestZoomLe var zoom = map.spec.getLowestZoomLevel(point, viewSize); loadClusters(); map.centerAndZoom(point, zoom); }); I ns tead of binding an info window to the c lic k event on the marker, we bind an anonymous func tion that c alc ulates the c enter point and s pan of the c lus ter, augmenting the s pan by 1 0 % in eac h dimens ion, s o that all of our points are well within the map view and not hiding out at the edges of the map. N ext, we us e the method des c ribed in "Find the Right Zoom L evel" [Hack #58] to c alc ulate the bes t zoom level for viewing the entire c lus ter. T he anonymous func tion then c alls loadClusters() to kic k off a reques t for the new s et of c lus ters and points for that map view, and then pans and zooms the map to that view. T he finale of the showCluster() func tion gives the c lus ter s ome vis ual c larity, by drawing a rec tangular polyline around the extents of the c lus ter, s o that the us er c an s ee whic h part of the map that the c lus ter c overs : var bbox = new GPolyline( [new GPoint(point.x - width/2, new GPoint(point.x - width/2, new GPoint(point.x + width/2, new GPoint(point.x + width/2, new GPoint(point.x - width/2, 'ff0000', 2, .80); point.y point.y point.y point.y point.y + + - height height height height height map.addOverlay(marker); map.addOverlay(bbox); } T he us er c an zoom into a c lus ter by c lic king on it, but what if s he wants to zoom bac k out? A s ingle event handler takes c are of refres hing the map dis play when the us er zooms in or out [Hack #60]. GEvent.addListener(map, "zoom", loadClusters); 7.9.4. Conclusion We've s een here that there c an be viable s olutions to the vexing problem of what to do when you have too many points to s how on a map. We've als o s een that s ome traditional c lus tering algorithms may be inadequate for c ertain tas ks of prac tic al digital c artography and that a more c us tomized approac h, us ing grid- bas ed c lus tering, c an yield pretty good res ults . T here's no doubt that this method is n't perfec t, though, and we'd really like to s ee it improved upon. I f you do us e this tec hnique as an ins piration for your own projec ts , pleas e let us know! 7.9.5. See Also Wikipedia on c lus tering algorithms : http://en.wikipedia.org/wiki/D ata_c lus tering "Find the Right Zoom L evel" [Hack #58] "Show L ots of StuffQ uic kly" [Hack #59] "M ake T hings H appen When the M ap M oves " [Hack #60] Hack 70. Will the Kids Barf? (and Other Cool Ways to Use Google Maps) Google Maps Hacks are turning up everywhere; here are some things we just didn't have time to cover f ully. M y kids get s ic k on c urvy roads . I t is jus t a fac t of life. O ne meas ure of the c urvines s of a road is the detour index. T his is the ratio of the s hortes t road dis tanc e and the s traight- line dis tanc e. Some mathematic ians als o c all this the "frac tal dimens ion of the polyline." Detour Index = road distance ÷ straight line distance X 10 We c an get the road dis tanc e by c alc ulating the driving direc tions and grabbing that dis tanc e. Figure 7 - 3 0 s hows it is 6 8 .1 miles from C loverdale to M endoc ino. See "H ow Far I s T hat? G o Beyond D riving D irec tions " [Hack #12] for different ways to c alc ulate the s traight- line dis tanc e. I us ed our s ample tool at http://mappinghac ks .c om/projec ts /gmaps /lines .html. Be c areful to meas ure the s ame dis tanc e! I noted the s tart and s top points of the G oogle route and tried to matc h thos e in c alc ulating the s traight- line dis tanc e as s hown in Figure 7 - 3 1 . Figure 7-30. From Cloverdale to Mendocino is 68.1 miles on the road Figure 7-31. Straight-line distance from Cloverdale to Mendocino is 55.1 miles T he s traight- line dis tanc e is 5 5 .1 miles , s o the detour index is 68.1÷55.1 X 100=123.6. T hrough c areful analys is of four or five trips , as partially des c ribed in Mapping Hacks , I 've determined that a detour index over about 1 2 0 is a rec ipe for c ars ic k fun. I f you are a motorc yc lis t looking for c urves , you c an us e the number for your own ends . But remember, as the heartles s half of this book's writing team s ays , "For s ome people, motion s ic knes s is no laughing matter. For the res t of us , it is ." We really wanted to turn this into a G oogle M aps demo that you c ould experiment with yours elf, but we jus t didn't have the time! 7.10.1. Other Cool Google Maps Hacks O ne of the painful c hallenges in writing this book during the heady days of the releas e of the offic ial A P I was that we jus t c ould not keep up with all of the c ool work that was being done, muc h les s c ontribute to it ours elves . We'd watc h our email, and the G oogle M aps A P I mailing lis t, and D el.ic io.us , and more c ool "mus t inc lude" hac ks appeared than we c ould pos s ibly ever write about. H ere are a few of the c ooles t. 7.10.1.1. Google sightseeing. What c ould be better than s tanding on a s unlit peak overlooking the G rand C anyon at s uns et with your loving family by your s ide? H ow about looking over it without the 1 0 - hour c ar trip in an overheating s tation wagon with s tic ky s eats , grumpy c hildren, and a fed- up wife? We have G oogle, s o why bother s eeing the world for real? T he G oogle Sights eeing s ite at http://www.googles ights eeing.c om/ s hows neat plac es on G oogle M aps . C ons ider it a map geeks blog: A lex, J ames , and O lly s c our (imagery of) the E arth to bring you lands c apes to amus e and amaze. 7.10.1.2. ZIP Code maps. P os tal c ode boundaries are often a bit arbitrary. You c an go to http://maps .huge.info/, enter a ZI P C ode, and s ee the area it c overs . Figure 7 - 3 2 s hows 9 5 4 7 2 on a map. ("E xamine P atterns of C riminal A c tivity" [Hack #18] s hows another example of rendering arbitrary G I S vec tor data on G oogle M aps .) T he s ite is c areful to note its own limitations : ZI P C ode data is derived from the C ens us 'ZC TA s (ZI P C ode Tabulation A reas ),' whic h may be different than the U SP S defined ZI P C ode delivery routes . A U SP S ZI P C ode is not a geographic al area but a route whic h may not be definable as a polygon. 7.10.1.3. Google Planimeter. You c an us e G oogle M aps to meas ure areas at http://www.ac me.c om/planimeter/. N avigate to your s elec ted area and then c lic k on at leas t three points , and it will c alc ulate the area. Figure 7 - 3 3 s hows that the P oint Reyes N ational Seas hore is roughly 1 3 7 s quare miles . Figure 7-32. ZIP Code 95472 displayed on a map 7.10.1.4. Play games on Google Maps. I n Tripods , you "battle invading G oogle M aps Tripod markers that are invading M anhattan." T his is a multiplayer game, s o you c an gang up with other players to fight the menac e, as s hown in Figure 7 - 3 4 . You c an play Tripods at http://www.thomas s c ott.net/tripods /. Find the L andmark, at http://landmark.maps game.c om/, gives you a landmark and times your attempts to find it. Figure 7 - 3 5 s hows my "I give up" time at finding the Spac e N eedle in Seattle. O ther games are dis c us s ed on the G ames O n G oogle M aps wiki page at http://moloko.itc .it/trus tmetric s wiki/moin.c gi/G ames O nG oogleM ap 7.10.1.5. Map versus satellite. O verlay a s mall s ec tion of a map view over the s atellite view, or vic e vers a, at http://www.kokogiak.c om/gmaps trans parenc ies .html. T his helps you to s ee dis c repanc ies between the map and the imagery, as in Figure 7 - 3 6 . 7.10.1.6. Edible plants in the public domain. T he G arden of the C ommons at http://c ommons garden.org/ maps plants growing in public s pac es that have food or medic inal value and offers us ers the c hanc e to c ontribute their own finds . Figure 7-33. Measure the area of Point Reyes National Seashore 7.10.1.7. Animate a route. T here is a bookmarklet at http://www.ergul.c om/maps / that will animate your driving direc tions , even c ros s - c ountry. E nter your end points and watc h as the c omputer follows your route for you. 7.10.1.8. Track your credit card spending. G reg M c C arroll has done work on mapping his c redit c ard s tatement at http://www.mc c arroll.org.uk/~gem/c reditc ardtrac ker/. Being able to s ee where you s pend money might jus t help you manage your s pending habits ! Figure 7-34. Fight the Tripods! Figure 7-35. Find the LandmarkThe Space Needle Figure 7-36. Compare the map with the satellite view 7.10.2. Where to from Here? We c an rec ommend a c ouple of web s ites that trac k the G oogle M aps phenomenon in all its glory and bring you up- to- date on the lates t developments . T he firs t is G oogle M aps M ania, at http://googlemaps mania.blogs pot.c om/, a veritable c ornuc opia of G oogle M aps news and reviews . T he other, of c ours e, is our very own M apping H ac ks blog, at http://mappinghac ks .c om/ where we hope to pres ent a more vaired and in- depth view of the rapidly evolving world of digital c artography, inc luding, of c ours e, G oogle M aps . So where to now? G oogle M aps has provided a brus h or two, an eas el, and a few pots of paint. G et out there and s ee what you c an make! Colophon T he tool on the c over of Google Maps Hacks is an antique globe of the earth. U nlike maps , globes allow for undis torted geographic al repres entations of the earth and other s pheric al c eles tial bodies . T he earlies t known globe, the N urnberg Terres trial G lobe, was made during the years 1 4 9 0 1 4 9 2 by G erman navigator and mapmaker M artin Behaim. T he c over image is from the "C M C D E veryday O bjec ts " C D . T he c over font is A dobe I T C G aramond. T he text font is L inotype Birka; the heading font is A dobe H elvetic a N eue C ondens ed; and the c ode font is L uc as Font's T heSans M ono C ondens ed. Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] &output=js + (plus) key + (plus) sign in URLs ; (semicolon) <geo:lat-…> tag (Flickr) 2nd Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] A9+Gmaps fragility of hack loading A9 images on Google Maps interface 2nd A9.com ActivePerl adding icons customization to travelogue slideshow s adding maps customization customizing map button name list of map types setting path to map images adding to maps Flash applets examples of advertisements on Google Maps aerial photography aggregator ahding.com low est gas prices airport codes obtaining driving directions AJAX algorithms 2nd 3rd hierarchical clustering algorithms for clustering markers hierarchical clustering Amazon anti-mega w orld w eather site Apache w eb servers ApartmentRatings.com API (application programming interface) Apple computer keyboards Area 51 arrow keys 2nd horizontal/vertical panning Art Director's Toolkit (Mac OS X) Ask the Spider search engine Asynchronous JavaScript And XML (AJAX) Atomic Archive site automatically cutting/naming custom map tiles customization running script in Photoshop automatically using right one developer's key (Google Maps API) Perl script for avoiding traffic jams in United States Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] Backstage BBC maps of traffic conditions BAHT (Bay Area Hiking Trails) copying to create local maps Ning Playground BBC London Jam Cams site Bermuda Triangle example bicycle routes Blackbird Sighting page blogs 2nd bookmarklets animating driving directions del.icio.us Firefox JavaScript bookmarks maps managing w ith del.icio.us 2nd 3rd view s of locations Boston Subw ay Station Map Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] calculating distances from latitude/longitude coordinates cartographic projection cell phones Geobloggers version for tow ers 2nd censored maps Census Bureau (U.S.) street address information TIGER/Line data 2nd CGI script 2nd Cheap Gas site Chicago city maps site GIS Department site police department site Transit Authority map site chicagocrime.org cities generating street maps from Google Ride Finder 2nd 3rd 4th 5th locating places in mapping current traffic conditions in 2nd 3rd 4th North American 2nd obtaining w eather information Clear Points button (Google Weather Maps) click-to-map tool clicking maps calculating distances by 2nd 3rd 4th 5th double-clicks client-side JavaScript clustering algorithms 2nd 3rd hierarchical clustering clustering markers 2nd 3rd 4th 5th 6th 7th algorithms for 2nd clusters Colorado Future com ports Comma Separated Values (CSV) SPC w eather data in command-line interface communities collaborative photography maps 2nd 3rd guided tour maps Community Walk del.icio.us location searches on maps context in location searches in reading materials 2nd 3rd in satellite imagery coordinates for latitude/longitude converting street addresses to determining from map view Geocoder.us street addresses 2nd 3rd 4th 5th 6th Copy option (Link to this page corporate intranets CPAN (Comprehensive Perl Archive Netw ork) Perl module dow nloads Craigslist pairing information w ith Google Maps RSS feeds from creating collaborative photography maps of communities for guided tours 2nd 3rd 4th 5th custom icons to mark maps 2nd 3rd 4th 5th fullscreen maps 2nd 3rd 4th 5th Credit Card Tracker credit cards fraud criminal activities ZIP Code and w ard boundaries crontab tips CSV (Comma Separated Values) customization adding icons to maps 2nd 3rd 4th 5th 6th 7th adding maps 2nd 3rd 4th 5th 6th 7th automatically cutting/naming custom map tiles configuring batch processing script 2nd determining values for tiles 2nd 3rd building icons on the fly 2nd serving custom map imagery 2nd 3rd 4th 5th cyberspace Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] dead spots Degree Confluence Project del.icio.us 2nd 3rd bookmarklets Community Walk integration w ith detour index 2nd developer's key (Google Maps API) application form automatically using right one 2nd 3rd 4th JavaScript for 2nd dew point display modes 2nd 3rd sw itching among distances distortion of maps Dive into Greasemonkey .dmg files documentation Google Maps Google Maps API GxMagnifier XMaps DOM (Document Object Model) drag panning 2nd alternative to magnifier on Google Maps draw.pl script driving directions 2nd 3rd 4th 5th alternative search methods betw een points converting to other formats 2nd 3rd emailing optimal routes steps in obtaining to multiple locations 2nd 3rd 4th Durius Java applet Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] EasyGPS eBay edible plants in public domain elsew here.org emailing links End key EPSG (European Petroleum Survey Group) estimating time of routes European Petroleum Survey Group (EPSG) EVDB (Events and Venues Database) events mapping locations of 2nd user-initiated Events and Venues Database (EVDB) everything2 site EVMapper extents Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] Fabl site FCC (Federal Communications Commission) converting coordinates in degrees/minutes/seconds to decimal degrees database of locations of cell phone tow ers features of Google Maps files .dmg .kml 2nd 3rd CSV GPX Tracklog WSDL films at local theaters Find the Landmark game Flash applets adding to maps 2nd 3rd 4th 5th Flickr as data source for Geobloggers geotagging example photographs on 2nd 3rd 4th photographs on brow sing by locations 2nd 3rd 4th 5th 6th 7th 8th Flickr API 2nd 3rd Flickrcity setting up installations for communities on folksonomy for public transportation routes in Vancouver fractal dimension of the polyline fullscreen maps creating adding side panel to Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] games Garden of Commons Garmin GPS receiver Garnix GPS receiver connecting to MS-DOS binary version of garnix.cfg file Gas Buddy site gasoline prices 2nd 3rd GasWatch Generate API Key button (Google Maps API) Geo::Coder::US module Geo::Coder::US::Import module Geobloggers Flickr as data source for mobile phone version of Geobloggers API geoblogging w ith Google Maps 2nd 3rd 4th geocoded RSS 2nd 3rd Geocoder.us database demo application of developer documentation Geo::Coder::US home page O'Reilly Media headquarters location terms and conditions of service for TIGER/Line data and geocoding 2nd difficulties of street addresses addresses outside U.S. w ith Geocoder.us Geographic Information System (GIS) Geographic Names Information System (GNIS) GeoIP database (MaxMind) Geoserver geospatial applications Geospatial Web geotagging W3C-derived style of GEvent API GMap class (Google Maps API) GMap Pedometer GMaps site maps tracking International Space Station other projects gmaptrack site GmiF script (Greasemonkey) GNIS (Geographic Names Information System) Google Google Earth imagery from Netw ork Link tracking movements w ith 2nd 3rd Google Groups threads Google Mappers community Google Mapping Hacks example of mapping w ireless signals geotagging Flickr photographs page map_in_box page size_of site page takeme.pl script available on Google Maps adding to w eb sites 2nd 3rd 4th 5th clicking logo extreme hacks 2nd 3rd 4th 5th 6th 7th narrative possibilities of 2nd pinning maps to 2nd 3rd 4th 5th 6th restrictions on use of results page tile structure traceroute Google Maps API 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th creating/displaying maps documentation driving directions ease of handling client side and user interaction hard drive space required for Google Maps server home page introduction to JavaScript library mapping travel slideshow s 2nd posting links to maps on w eb pages routes TPhoto extension travelogue slideshow versions of Google Maps GPX View er Google Maps Mania Google Maps mashups Google Maps server Google Phonebook Google Planimeter Google Ride Finder markers Google Search Google Sightseeing Google Weather Maps Google-Traffic.com Traffic-Weather Maps site GPoint class GPS device GPS devices com port coordinates for latitude/longitude Garmin driving directions 2nd 3rd Garmin Garnix maps photographs points GPS Exchange Format (GPX) GPS tracklogs GPX files 2nd GPX view ing overlaying on hiking trail maps plotting on maps 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th client-side implementation GPSBabel 2nd 3rd overlays gpsvisualizer.net GPX (GPS Exchange Format) 2nd converting to JavaScript using Ruby 2nd 3rd 4th 5th 6th 7th 8th standard GPX files points in reducing complexity of saving GPS route points to GPX-to-Google Maps solutions Greasemap home page JavaScript source code Greasemonkey extension site installing script user script 2nd 3rd GxMagnifier documentation zooming maps w ith 2nd 3rd 4th 5th Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] habitat data hard drives Hello World! of Google Maps (Google Maps API) 2nd hierarchical clustering algorithms hiking trails 2nd 3rd Home key horizontal/vertical panning keyboard shortcuts on Apple computers hotels HousingMaps 2nd HTML (Hypertext Markup Language) JavaScript and maps and 2nd 3rd Hurricane Track Map (Storm Report Map) hurricanes/tropical storms Hybrid display mode 2nd HYDESim w eb site Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] IANA (Internet Address and Naming Authority) iBook keyboards Icon Color Shades example icons custom building on the fly 2nd 3rd generic IE (Internet Explorer) Google Maps API library and GPX data location searches Image::Magick module ImageMagick info w indow alternative, adding to maps using TLabel animation 2nd map and text 2nd 3rd 4th innovations in Google Maps interface installing Greasemonkey script interface 2nd 3rd 4th 5th dynamic nature of features smaller version International Space Station (ISS) 2nd 3rd Internet 2nd 3rd 4th Internet Address and Naming Authority (IANA) Internet Movie Database site IP addresses ISS (International Space Station) 2nd 3rd Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] Japan location searches for subw ay stations Java applets JavaScript Google Maps interface and HTML and open source library redraw ing maps and selecting developer's key 2nd JavaScript library Google Maps API location of jogging routes Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] k-means clustering algorithm Ka-Maps client interface to Mapserver Katrina display mode 2nd keyboard shortcuts 2nd kilometers number of in one mile scale bar distance indicator KisMAC Kismet XML logs KML (Keyhole Markup Language) .kml files 2nd 3rd Konfabulator for Window s Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] Landsat imagery latitude represented in URLs LatLon to Tile tool left-clicking maps Link to this page link (Google Maps) limitations of URLs 2nd Link to this page link (Google Phonebook) links Mobiledia support for to local places to maps 2nd 3rd 4th 5th 6th generating in spreadsheets 2nd 3rd posting on w eb pages 2nd 3rd 4th 5th Linux connecting to Magellan/Garmin GPS receivers mapping w ireless signals w ith Kismet loading pages in Google Maps Location Search box entering names of businesses in obtaining driving directions simplicity/versatility of location searches Cell phone reception search context settings corresponding street addresses difficulties w ith entering locations 2nd 3rd other than addresses/intersections 2nd 3rd events 2nd info w indow integrated local searches low est gas prices 2nd of Flickr photographs 2nd 3rd 4th 5th 6th 7th 8th XML proxy 2nd on Community Walk single search box feature span of LWP::Simple module Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M ] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] Mac OS X GasWatch on Macromedia Flash Google Maps and MacStumbler Magellan GPS receiver Map display mode map tiles custom 2nd 3rd 4th 5th 6th 7th Mapping Hacks blog maps alternative info w indow 2nd 3rd blogs corresponding to new s reports 2nd 3rd creating w ith Google Maps API custom 2nd 3rd 4th 5th 6th 7th custom imagery 2nd 3rd 4th 5th events 2nd Flash applets fullscreen geocoded RSS geographic regions 2nd geolocated photographs on creating guided tour maps 2nd GPS track logs/w aypoints GPS track logs/waypoints, plotting on using Ruby housing 2nd 3rd imagery 2nd 3rd 4th 5th interactive International Space Station/Space Shuttle Internet packets 2nd 3rd 4th 5th linking to 2nd 3rd using Google Maps API 2nd measuring w ith new types of nuclear explosions 2nd 3rd 4th of cell phone tow ers 2nd of credit card spending of criminal activity patterns 2nd 3rd of Cupertino of edible plants in public domain of hiking trails 2nd 3rd of jogging/running routes of travels 2nd 3rd of w ireless signals 2nd 3rd 4th 5th 6th 7th 8th of ZIP Codes on Community Walk overlays on 2nd photographs public transportation routes 2nd 3rd span of street 2nd subjective imagery on 2nd 3rd telephone numbers 2nd text and 2nd 3rd 4th tracking local w eather 2nd 3rd 4th 5th UPS packages 2nd 3rd 4th w eather 2nd 3rd 4th 5th 6th 7th storm reports 2nd 3rd 4th zooming w ith GxMagnifier Mapserver markers clustering 2nd 3rd 4th creating from Geocoder.us data MaxMind GeoIP database MaxMind site meatspace Mercator projection Metamark Shorten Service METAR-formatted w eather reports meteorological data 2nd 3rd 4th 5th 6th 7th 8th 9th Microsoft Excel Microsoft Virtual Earth Microsoft Windows command line Perl version for miles number of kilometers equal to mini-maps exclusion from emails mini-search box (info w indow ) minus (-) key Mobiledia mod_rewrite enabling developer's key sharing Monkey Homes Mozilla Firefox Flickr photographs Greasemonkey extension keyboard shortcuts and maps UPS packages MySQL database 2nd 3rd 4th 5th 6th Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] naïve grid-based clustering algorithm NASA Satellite Tracking Page National Oceanic & Atmospheric Administration (NOAA) National Weather Service (NWS) navigating public transportation Chicago Transit Authority maps NYC subw ay map navigating Google Maps 2nd Netstumbler Netw ork Link (Google Earth) new s reports 2nd 3rd Ning Playground 2nd NOAA (National Oceanic & Atmospheric Administration) North America approximate area in pixels for public transportation maps for cities in North American cities Boston Chicago New York City Seattle Vancouver north pole nuclear explosions illustrating effects of 2nd List of Nuclear Accidents (Wikipedia) New York City example Nuclear Weapons FAQ 2nd NYC Subw ay Map site Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] O'Reilly Media site of 2nd 3rd 4th 5th 6th of communities photographs adding to Community Walk maps of Flickr photographs location searches using Geobloggers OGC (Open Geospatial Consortium) 2nd Directory of Services online mapping services interoperability standards page loading and Open Geospatial Consortium (OGC) 2nd open source map generators 2nd OpenStreetMap overlays display modes draw ing time 2nd overpressure overview map Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] page loading in Google Maps paid premium content sites performance markers and overlays and Perl accessing Geocoder.us service using XML-RPC interface w ithin 2nd 3rd Flickrcity installations selecting developer's key in takeme.pl script Window s version PgDn/PgUp keys photographs aerial Google Earth maps 2nd 3rd 4th of communities 2nd 3rd 4th 5th creating maps 2nd 3rd 4th on Flickr geotagging 2nd PHP (PHP Hypertext Preprocessor) BAHT code displaying data from MySQL databases script platforms platial.com plotting movements with Google Earth links creating dynamic Placemarks plus (+) key plus (+) sign in URLs points clusters of exporting to GPS GMaps Pedometer/Walk Jog Run points of interest Poor Clio's Side-by-Side Google Maps PostGIS 2nd posting links to maps on web sites before Google Maps posting links to maps on web pages Google Maps API adding points generating a developer's key PROJ.4 cartographic projections library proximity searches public transportation maps for cities in North America Boston Chicago Vancouver public transportation routes maps in Chicago in New York City in Seattle in Vancouver Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] query parameter Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] RDF Primer (W3C) site RDF/XML document read/w rite markers 2nd 3rd readability of maps 2nd 3rd 4th 5th reading materials recentering maps 2nd Red Geographics Map-Server page regular expressions (JavaScript) resizing magnifiers on Google Maps maps REST service RESTful API site reverse lookups Risk routes alternatives to automobile draw ing for joggers/runners for public transportation 2nd 3rd 4th 5th RSS (Rich Site Summary) Ruby scripting language code GPX tracks running routes Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] Satellite display mode 2nd 3rd 4th 5th satellite imagery using as reality check Satellite Tracking Page (NASA) scale scale bar estimating distances and scenic routes script src= (Google Maps API) Seattle Bus Monster site segments of routes semicolon (;) server-side CGI script servers code for Google Maps providing custom map imagery WMS 2nd 3rd sleep.exe file sll parameters SOAP service SOAP::Lite module South pole span values spatial reference identifiers (SRIDs) spatial reference system (SRS) SPC (Storm Prediction Center) spn parameter SR 71 Blackbirds SRIDs (spatial reference identifiers) SRS (spatial reference system) sspn parameter standard GPX (GPS Exchange Format) tools that support Storm Prediction Center (SPC) Storm Report Map site street addresses coordinates for latitude/longitude outside U.S. geocoding 2nd 3rd street intersections structure of URLs (Universal Resource Locators) negative values in Subfinder application subway stations in Boston in Japan/United Kingdom in New York City Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] telephone numbers reverse lookup service Terms of Service (Google Maps) Terms of Use page (Google Maps API) The Who locations site Thingster geoblogging service 2nd 3rd instructions for using TIGER/Line data limitations of U.S. Census Bureau time-to-live (TTL) TLabel extension using TLabel object TLabel page Topografix site towers brow sing for 2nd 3rd FCC database of antennas TPhoto as georeferencing tool traceroute online services traceroute utility tracking packages UPS form for traffic jams avoiding 2nd traffic tickets 2nd Traffic-Weather Maps site (Google-Traffic.com) travelogue slideshows example of Tripods game tropical storms/tropical depressions TTL (time-to-live) Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] U.S. National Weather Service U.S. SPC site Update Map button (Google Weather Maps) UPS tracking packages 2nd tracking user script site UPS packages maps example outside United States URI::Escape module URLs Link to this page link (Google Maps) parameters in URLs (Universal Resource Locators) shortening links to maps structure of 2nd 3rd 4th 5th tw o different user-initiated events GEvent API users GEvent API Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] v-1 parameter (URL to "Hello World!" of Google Maps) Vancouver Transit Map verifying locations/directions subjective nature of map imagery versions of Google Maps softw are VML (VODAK Model Language) IE and Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] Walk Jog Run w ard boundaries w ardriving 2nd 3rd 4th tools for waypoints name/coordinates of noting w ith GPS w hen photographing travels weather dew point tracking on maps 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th w eather stations Weather Underground 2nd Weatherbug 2nd Web Feature Service (WFS) web sites linking to Mobiledia HTML form maps 2nd 3rd 4th 5th open source mapping solutions posting links to maps on Webcams checkbox (Google Weather Maps w ebcams on w eather maps WFS (Web Feature Service) WhatIsMyIPAddress.com Whereis service traceroute mapping service added to Wi-Fi 2nd 3rd w idgets Wikipedia w ireless devices 2nd 3rd 4th WiScan log WMS (Web Mapping Service) 2nd data and map imagery available from WMS Cookbooks WMS interface 2nd 3rd 4th 5th 6th 7th 8th 9th WMS servers 2nd 3rd 4th World Wide Web Consortium (W3C) WSDL file Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] XMaps XMaps API XMaps Library 2nd XML parser in Google Maps API XML proxy 2nd 3rd XML-RPC client libraries interface 2nd XML::Simple module XMLRPC::Lite module XSLT processor in Google Maps API Index [SYMBOL] [A ] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V ] [W] [X] [Z] z parameter ZIP Codes boundaries delineated by maps of Zoom Box button (Google Weather Maps) zoom control ruler zoom levels determining scaling factor for displaying different levels in email links finding right one 2nd length ratios from one to another setting span of maps zooming using plus and minus keys