Open Layers.2.10.Beginners.Guide
User Manual: Pdf
Open the PDF directly: View PDF .
Page Count: 372
Download | ![]() |
Open PDF In Browser | View PDF |
OpenLayers 2.10 Beginner's Guide Create, optimize, and deploy stunning cross-browser web maps with the OpenLayers JavaScript web-mapping library Erik Hazzard OpenLayers 2.10 Beginner's Guide Copyright © 2011 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: March 2011 Production Reference: 1110311 Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK. ISBN 978-1-849514-12-5 www.packtpub.com Cover Image by Jose Argudo (josemanises@gmail.com) Credits Author Erik Hazzard Reviewers Xurxo Méndez Pérez Alan Palazzolo Ian Turton Editorial Team Leader Aanchal Kumar Project Team Leader Priya Mukherji Project Coordinator Jovita Pinto Couzic Mikael Proofreader Acquisition Editor Steve Maguire Usha Iyer Graphics Development Editor Nilesh Mohite Maitreya Bhakal Production Coordinator Technical Editors Adline Swetha Jesuthas Pallavi Kachare Cover Work Indexers Hemangini Bari Rekha Nair Adline Swetha Jesuthas About the Author Erik Hazzard is a web developer—designer, Open Source advocate, and VI user. He loves to learn, teach, and occasionally blogs on his website at http://vasir.net/. As a professional web developer of five years, Erik specializes in Python and JavaScript, using open source software whenever possible. When he's not developing web applications, he's often developing or designing video games. He works at FREAC (Florida Resources and Environmental Analysis Center), a great place with great people that does all kinds of GIS and web development work. I'd like to thank the developers of OpenLayers, who continually do a fantastic job of developing the best web-mapping framework. I'd like to also thank my friends and mentors Ian Johnson and David Arthur for giving me the confidence and support I needed to get into web development. I'd like to thank Georgianna Strode and Stephen Hodge for their guidance, advice, and providing me with the opportunity to become a better web developer. I could not have written this book without the help of the great team at Packt; I hope every author can be as lucky as me to have such an excellent group of people to work with. I'd like to thank my parents for their never ending support. Lastly, I'd like to thank my love, Alisen, for her understanding and taking the time to help me make sure that the book is as easy to read as possible. About the Reviewers Xurxo Méndez Pérez was born in 1983 in Ourense, a little town in the south of Galicia, Spain. He lived there until he started the study for a degree in IT in the University of A Coruña, which finalized in 2008. For the last two years he has been working, at the Computer Architecture Group of the University of A Coruña developing GIS applications (making intensive use of many OGC standards) like Sitegal and SIUXFor (web GIS based applications to manage land properties and promote their good uses in the Galician region), MeteoSIX (a GIS system that provides access to geolocated observed and forecasted meteorological data in Galicia) and others. He also has large experience (3+ years) as a developer of mobile applications, having played first with JavaME, but nowadays he specializes in Google Android, with more than a dozen developed applications, some of them combining concepts like GIS and geolocation, real time responsiveness, and multiuser needs. Alan Palazzolo has been building web applications big and small for over five years, most of which have been with the open source, content management system Drupal, and along the way has picked up some experience in data visualization and mapping. He is a strong believer and advocate for the open source methodology in software and in life. He was involved in starting a Free Geek chapter in the Twin Cities, and constantly tries to use technology, and specifically the Internet, to enhance the lives of those that are less fortunate than most. Ian Turton is a geography researcher at the Pennsylvania State University. He became a geographer by accident nearly 20 years ago and hasn't managed to escape yet. During that period he was a co-founder of the GeoTools open source Java toolkit that is now used as the basis of many geographic open source projects. He continues to serve on the Project Steering Committee for the project as well as committing new code and patches. He has also taught the very popular course "Open Web Mapping" using open standards and open source programs at the Pennsylvania State University and the University of Leeds. www.PacktPub.com Support files, eBooks, discount offers, and more You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why Subscribe? Fully searchable across every book published by Packt Copy and paste, print and bookmark content On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. Table of Contents Preface Chapter 1: Getting Started with OpenLayers What is OpenLayers? Why use OpenLayers? What, technically, is OpenLayers? Client side Library Anatomy of a web-mapping application Web map client Web map server Relation to Google / Yahoo! / and other mapping APIs Layers in OpenLayers What is a Layer? The OpenLayers website Time for action – downloading OpenLayers Making our first map Time for action – creating your first map How the code works Understanding the code—Line by line JavaScript object notation Behind the scenes—Object Oriented Programming (OOP) Interaction happens with objects MadLibs Time for Action – play MadLibs Programming with OOP Subclasses Now what? API docs 1 7 8 8 8 8 9 9 10 10 11 11 12 12 13 15 15 17 18 21 24 25 25 25 26 26 27 28 Table of Contents Where to go for help This book's website Mailing lists IRC OpenLayers source code repository Summary 28 28 28 29 29 30 Chapter 2: Squashing Bugs With Firebug What is Firebug? Setting up Firebug Time for Action – downloading Firebug Firebug controls Panels 31 32 32 32 34 34 Console panel HTML panel CSS panel Script panel DOM panel Net panel 35 35 37 37 38 38 Panel conclusion Using the Console panel Time for Action – executing code in the Console Time for Action – creating object literals Object literals Time for Action – interacting with a map API documentation Summary Chapter 3: The 'Layers' in OpenLayers 41 42 42 43 44 45 47 47 49 What's a layer? Layers in OpenLayers Base layer Overlay layers Time for Action – creating a map with multiple layers Creating layer objects Layer.WMS class WMS layer parameters: 50 50 51 51 51 54 55 55 Parameters versus arguments Time for Action – configuring the options parameter Configuring layer options wms_state_lines layer options Scale dependency 57 58 61 61 61 wms_layer_labels layer options 62 The visibility property 62 [ ii ] Table of Contents The opacity property 62 Map tiles Many images make up a map Available layer properties Data types OpenLayers.Layer class properties 62 63 65 66 66 Modifying layer properties 71 The OpenLayers.Layer class Subclasses Layer Class—Sub and super classes Other layer types Layer.ArcGIS93Rest Layer.ArcIMS Layer.Google Time for Action – creating a Google Maps layer Layer.Grid Layer.Image Time for Action – using the image layer Image layer parameters Layer.MapGuide Layer.TileCache Layer.Vector Layer.VirtualEarth Layer.WFS Layer.WMS Layer.Yahoo Accessing layer objects Time for Action – accessing map.layers Time for Action – accessing layer objects in Firebug Accessing layer properties map.layers Storing references to layer objects 71 71 72 72 72 73 73 73 75 76 76 77 78 79 79 79 80 80 80 80 80 82 82 82 83 Layer class methods Time for Action – defining a global layer object variable Layer class method definitions Summary 85 85 86 88 Chapter 4: Wrapping Our Heads Around Projections 89 Map projections Why on earth are Projections used? Projection characteristics 90 90 90 Area 90 [ iii ] Table of Contents Scale Shape Other characteristics 91 91 91 Types of projections 92 EPSG codes 92 Time for Action – using different projection codes Specifying a different projection Longitude/Latitude Latitude Longitude 93 94 95 96 96 Time for Action – determining LonLat coordinates OpenLayers projection class Creating a projection object Parameters Functions 96 97 97 97 98 Transforming projections Time for Action – coordinate transforms The Proj4js library Time for Action – setting up Proj4js.org Defining custom projections Summary 99 99 100 101 102 102 Chapter 5: Interacting with Third Party APIs Third party mapping APIs Map mashups OpenLayers and third party APIs Google Maps Differences between Google Maps version 2 and version 3 Time for Action – using Goole Maps V3 (standard way) Creating a Google Map layer object Google layer properties sphericalMercator {Boolean} type {GmapType} V2 GMapType values 103 103 104 104 104 105 105 108 108 109 109 110 Time for Action – creating a Google Map layer with V2 (Deprecated) Yahoo! Maps API Time for Action – using the Yahoo! Maps Layer Yahoo! Maps Layer class properties Yahoo! Maps Layer types 111 113 113 115 115 Microsoft's mapping API Time for Action – creating a Bing/Virtual Earth Layer VirtualEarth layer class properties Possible type values 115 115 117 118 OpenStreetMap 118 [ iv ] Table of Contents Time for Action – creating an OpenStreetMap Layer Accessing your own OSM tiles Spherical Mercator Spherical Mercator—EPSG code Time for Action – using Spherical Mercator Map properties with Spherical Mercator layers maxExtent maxResolution units projection 118 119 120 120 121 122 122 122 123 123 Using Google Maps and other layers Time For Action – creating your first mashup WMS with Spherical Mercator/third party map layers Summary Chapter 6: Taking Control of Controls 123 124 127 127 129 What are controls? Using controls in OpenLayers Adding controls to your map Time for Action – creating a map with no controls Time for Action—Adding controls to a map Adding controls by passing in an array of controls Adding controls to map with addControl() and addControls() Removing controls OpenLayers.Control class OpenLayers.Control properties OpenLayers.Control functions OpenLayers.Control subclasses OpenLayers.Control.ArgParser OpenLayers.Control.Permalink OpenLayers.Control.Attribution Attribution properties 130 130 130 131 132 135 135 136 136 137 137 138 138 139 139 139 Time for Action – using attributions OpenLayers.Control.EditingToolbar OpenLayers.Control.Graticule 140 141 141 Graticule properties 142 OpenLayers.Control.KeyboardDefaults 143 KeyboardDefaults properties 143 OpenLayers.Control.LayerSwitcher 143 LayerSwitcher properties LayerSwitcher functions 143 144 OpenLayers.Control.MousePosition 144 MousePosition properties 144 [v] Table of Contents OpenLayers.Control.Navigation 145 Navigation properties 145 OpenLayers.Control.NavigationHistory 146 NavigationHistory properties NavigationHistory functions 146 146 Time for Action – using the NavigationHistory control OpenLayers.Control.NavToolbar OpenLayers.Control.OverviewMap OverviewMap properties OverviewMap functions 146 147 147 148 150 OpenLayers.Control.PanPanel 150 PanPanel properties 151 OpenLayers.Control.PanZoom OpenLayers.Control.PanZoomBar 151 151 PanZoomBar properties 151 OpenLayers.Control.Scale 151 Scale properties 152 OpenLayers.Control.ScaleLine 152 ScaleLine properties 152 OpenLayers.Control.ZoomPanel Panels Control types Time for Action – using Panels OpenLayers.Control.Panel 153 153 153 154 157 Panel properties Panel functions 158 159 Now what? Creating our own controls OpenLayers.Control.Button 159 159 159 Button properties Button functions 160 161 Creating a custom button Time for Action – creating a simple button Other control types Process for creating other button control types Events Event listeners and handlers Custom events Creating a TYPE_TOGGLE control Time for Action – creating a custom TYPE_TOGGLE control Summary [ vi ] 161 161 165 165 165 165 166 166 166 170 Table of Contents Chapter 7: Styling Controls 171 What is CSS? Ideas behind CSS and HTML Editing CSS HTML elements 172 172 172 173 HTML—IDs and classes 173 Styling HTML elements with CSS Using CSS in your code Time for Action – using external CSS files Cascading Style Sheets—Inheritance Order of inheritance Referencing elements 174 175 176 178 178 179 OpenLayers and CSS Styling OpenLayers—using themes Creating your own themes 180 180 181 OpenLayers—class names and IDs 181 Time for Action – styling controls Time for Action – styling the LayerSwitcher control Other resources Summary Chapter 8: Charting the Map Class 182 186 188 189 191 The Map class Creating a map object Map class properties Map properties 192 192 192 193 allOverlayers controls displayProjection div 193 193 194 194 Time for Action – using the allOverlays Map property eventListeners fallThrough layers maxExtent minExtent restrictedExtent numZoomLevels Time for Action – setting zoom levels and maxExtent Map properties—Continued Resolutions 194 196 197 197 198 198 198 198 199 200 200 Time for Action – using resolutions array Map/Layer property inheritance [ vii ] 201 201 Table of Contents Map properties discussion—Continued maxResolution minResolution 202 202 202 Time for Action – using Min and Max resolution scales maxScale minScale Time for Action – Using scales panMethod panDuration Time for Action – working with Pan animations projection theme tileSize unit Map functions Control related Time for Action – using control methods Extent/Coordinate/Bounds related Methods 202 204 204 204 205 206 207 207 208 208 208 208 209 209 210 210 211 Time for Action – using coordinate related functions Layer related functions Other functions Doing stuff with events Map event types Using map events Using the eventListeners property 213 214 214 215 216 216 217 Time for Action – using eventListeners Using map.events.register Event object Time for Action – working with Map events Multiple maps Using multiple map objects Time for Action – using multiple map objects Multiple maps and custom events Time for Action – creating a multiple map and custom event application Summary Chapter 9: Using Vector Layers 217 218 218 219 220 220 221 223 223 225 227 What is the Vector Layer? What makes the Vector Layer special? 228 229 The Vector Layer is client side [ viii ] Table of Contents Other uses What is a 'Vector'? Time for Action – creating a Vector Layer How the Vector Layer works How the Vector Layer is rendered SVG Canvas VML 229 230 230 232 233 233 233 233 'Renderers' array Time for Action – changing the Renderers array Vector Layer class OpenLayers.Layer.Vector properties OpenLayers.Layer.Vector methods Working with features 233 234 235 235 237 237 Time for Action – adding features Vector Layer methods (Continued) Time for Action – destroying features Vector Layer methods (Continued) Time For Action – working with feature events Vector Layer class events Vector Layer event types Time For Action – using Vector Layer events Time For Actions – working with more events Geometry and Feature classes Geometry class Geometry subclasses—Theory Geometry class methods 237 239 239 241 242 243 244 246 247 248 249 249 250 Time for Action – using Geometry class methods Geometry subclasses Geometry subclass methods Feature class How the Feature class works Feature subclasses Feature functions Instantiating a feature object Interacting with Features using Control.SelectFeature Time For Action – using the SelectFeature control Control.SelectFeature class SelectFeature control properties SelectFeature control methods 251 253 255 255 255 256 256 256 257 257 262 262 264 The Vector class, part two Format, protocol, and strategy classes 264 265 Who invited these classes over? 265 [ ix ] Table of Contents Brief overview of the three classes How these three classes interact Example instantiation 266 267 267 Time for Action – creating a Vector Layer Cross server requests Using the Vector Layer without a Protocol class Time for Action – using the Format and Strategy classes alone Format class Format class properties Format class methods Format subclasses Strategy class Strategy.BBOX Strategy.Cluster Strategy.Filter Strategy.Fixed Strategy.Paging Strategy.Refresh Strategy.Save Summary Chapter 10: Vector Layer Style Guide 268 269 270 270 273 273 273 274 274 274 274 275 275 275 275 276 276 277 Styling the Vector Layer Applying styles 277 278 What are symbolizers? 278 Time For Action – applying some basic Styling The StyleMap class What is an 'intent'? The Style class Symbolizer properties List of common symbolizer properties 279 281 281 281 282 282 Time for Action – common style examples Remaining symbolizer properties 284 286 Attribute replacement Time For Action – working with attribute replacement Rules and filters How do we follow rules? Using addUniqueValueRules Calling the addUniqueValueRules function The intent parameter The property parameter The symbolizer_lookup parameter The context parameter 287 287 289 289 290 290 290 290 291 291 [x] Table of Contents Time For Action – using addUniqueValueRules Rules and filters How do they work? How do we use them? Time for Action – using rules and filters OpenLayers.Rule class OpenLayers.Filter class Filter Subclasses Filter.Comparison Filter.FeatureId Feature.Logical 291 294 295 295 295 298 299 299 299 303 303 Time For Action – figuring out logical filters Feature.Spatial 304 308 Summary 309 Chapter 11: Making Web Map Apps 311 Development strategies Creating a web map application using Flickr Note on APIs Accessing the Flickr public data feeds 311 312 312 312 How we'll do it Time For Action – getting Flickr data Why did we do this? 313 313 314 Reducing possible errors 314 Time for Action – adding data to your map Time for Action – extract style Turning our example into an application Adding interactivity Selecting features 315 317 318 319 319 Time for Action – adding some interactivity Using real time data with a ProxyHost Time for Action – getting dynamic data Wrapping up the application Recap The plan Changing the URL 319 325 325 326 326 327 327 Time For Action – adding dynamic tags to your map Deploying an application Building the OpenLayers Library file Always try to serve small files Using the OpenLayers build file Configuring the build script 327 330 330 330 331 331 Time for Action – building a Config file 332 [ xi ] Table of Contents Running the build script 333 Time for Action – running the Build script Summary Appendix: Pop Quiz Answers 333 334 335 Chapter 2: Squashing Bugs With Firebug Chapter 3: The 'Layers' in OpenLayers Chapter 4: Wrapping Our Heads Around Projections Chapter 6: Taking Control of Controls Chapter 7: Styling Controls Chapter 8: Charting the Map Class Chapter 9: Using Vector Layers Chapter 10: Vector Layer Style Guide Chapter 11: Making Web Map Apps Index 335 335 335 335 336 336 336 336 336 337 [ xii ] Preface Web mapping is the process of designing, implementing, generating, and delivering maps on the World Wide Web and its products. OpenLayers is a powerful, community driven, open source, pure JavaScript web-mapping library. With it, you can easily create your own web map mashup using WMS, Google Maps, and a myriad of other map backends. Interested in knowing more about OpenLayers? This book is going to help you learn OpenLayers from scratch. OpenLayers 2.10 Beginner's Guide will walk you through the OpenLayers library in the easiest and most efficient way possible. The core components of OpenLayers are covered in detail, with examples, structured so that you can easily refer back to them later. The book starts off by introducing you to the OpenLayers library and ends with developing and deploying a full-fledged web map application, guiding you through every step of the way. Throughout the book, you'll learn about each component of the OpenLayers library. You'll work with backend services like WMS, third-party APIs like Google Maps, and even create maps from static images. You'll load data from KML and GeoJSON files, create interactive vector layers, and customize the behavior and appearance of your maps. There is a growing trend in mixing location data with web applications. OpenLayers 2.10 Beginner's Guide will show you how to create powerful web maps using the best web mapping library around. This book will guide you to develop powerful web maps with ease using the open source JavaScript library OpenLayers. Preface What you need for this book The only thing you'll need for this book is a computer and text editor. Your operating system will come with a text editor, and any will do, but if you are using Windows I recommend using Notepad++ (http://notepad-plus-plus.org/), VI if you are using Linux, and Textmate if on OSX. An Internet connection will be required to view the maps, and you'll also need a modern web browser such as Firefox, Google Chrome, Safari, or Opera. While a modern browser is required to get the most of the library, OpenLayers even provides support for non standards based browsers such as Internet Explorer (even IE6, to some extent). No knowledge of Geographic Information Systems (GIS) is required, nor is extensive JavaScript experience. A basic understanding of JavaScript syntax and HTML / CSS will greatly aid in understanding the material, but is not required. What this book covers Chapter 1: Getting Started with OpenLayers. This chapter will introduce OpenLayers and some programming concepts behind it. It covers how to create a map, walking through how to set up the code and configure various settings. Chapter 2: Squashing Bugs with Firebug. This chapter will cover setting up the Firebug plugin, which we'll use throughout the book, so that we can do simple debugging and better understand how OpenLayers works behind the scenes. Chapter 3: The 'Layers' in OpenLayers. Here, we'll cover one of the core classes of OpenLayers—the Layer class. We'll discuss what a 'Layer' is, how to work with layers and the different layer classes. Chapter 4: Wrapping our Heads Around Projections. This chapter will cover a few basic geography concepts and why understanding them will help us use OpenLayers. We'll also cover projections, why they are used, and how to use them. Chapter 5: Interacting With Third Party APIs. This chapter will focus on creating an OpenLayers map using different third party APIs, such as Google Maps and OpenStreetMaps. Chapter 6: Taking Control of Controls. We'll cover another core class of OpenLayers, the Control class. We'll cover what controls are and discuss the various types of controls, along with how to work with the events. Chapter 7: Giving Controls Some Style. This chapter will walk through how OpenLayers uses CSS to style controls. [2] Preface Chapter 8: Charting the Map Class. This chapter will discuss another core component of OpenLayers—the Map class. We'll learn about how to map functions and their properties, along with how to set up multiple maps on the same page. Chapter 9: Using Vector Layers. Here, we'll learn what a Vector layer is and how it works. We'll also cover how to work with the data, such as KML files. Chapter 10: Vector Layer Style Guide. In this chapter we'll cover how to style the vector layer and how to use the Rule and Filter classes. Chapter 11: Creating Web Map Applications. This final chapter will go over how to build a web-mapping application from scratch, and how to use the OpenLayers build file. Who this book is for This book is for anyone who has any interest in using maps on their website, from hobbyists to professional web developers. OpenLayers provides a powerful, but easy-to-use, pure JavaScript and HTML (no third-party plug-ins involved) toolkit to quickly make crossbrowser web maps. A basic understanding of JavaScript will be helpful, but there is no prior knowledge required to use this book. If you've never worked with maps before, this book will introduce you to some common mapping topics and gently guide you through the OpenLayers library. If you're an experienced application developer, this book will also serve as a reference to the core components of OpenLayers. How to read this book This book is primarily designed to be read from start to finish, with chapters building on each other and increasing in complexity. At the same time, however, the chapters are modular so that each can also serve as reference once you've learned the material. This book should preferably be read straight through first, of course, and then serve as a reference later. Conventions In this book, you will find several headings appearing frequently. [3] Preface To give clear instructions of how to complete a procedure or task, we use: Time for action – heading 1. Action 1 2. Action 2 3. Action 3 Instructions often need some extra explanation so that they make sense, so they are followed with: What just happened? This heading explains the working of tasks or instructions that you have just completed. You will also find some other learning aids in the book, including: Pop quiz – heading These are short questions intended to help you test your own understanding. Have a go hero – heading These set practical challenges and give you ideas for experimenting with what you have learned. You will also find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: "You can download it as either a tar.gz or .zip." A block of code is set as follows: Lines [21] to [23] if(!map.getCenter()){ map.zoomToMaxExtent(); } When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: var wms_layer = new OpenLayers.Layer.WMS( 'WMS Layer Title', 'http://vmap0.tiles.osgeo.org/wms/vmap0', [4] Preface {layers: 'basic'}, {} ); New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "By default, your map adds an argParser control which will try to pull information from a permalink.". Warnings or important notes appear in a box like this. Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to feedback@packtpub.com, and mention the book title via the subject of your message. If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail suggest@packtpub.com. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors. Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Downloading the example code for this book You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you. [5] Preface Errata Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code— we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www. packtpub.com/support. Piracy Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at copyright@packtpub.com with a link to the suspected pirated material. We appreciate your help in protecting our authors, and our ability to bring you valuable content. Questions You can contact us at questions@packtpub.com if you are having a problem with any aspect of the book, and we will do our best to address it. [6] 1 Getting Started with OpenLayers Within the past few years, the popularity of interactive web maps has exploded. In the past, creating interactive maps was reserved for large companies or experts with lots of money. But now, with the advent of free services like Google and Yahoo! Maps, online mapping is easily accessible to everyone. Today, with the right tools, anyone can easily create a web map with little or even no knowledge of geography, cartography, or programming. Web maps are expected to be fast, accurate, and easy to use. Since they are online, they are expected to be accessible from anywhere on nearly any platform. There are only a few tools that fulfill all these expectations. OpenLayers is one such tool. It's free, open source, and very powerful. Providing both novice developers and seasoned GIS professionals with a robust library, OpenLayers makes it easy to create modern, fast, and interactive web-mapping applications. In this chapter we will Learn what OpenLayers is Discuss some web mapping application concepts Make our First Map Cover concepts behind OpenLayers, such as Object Oriented Programming Provide information on resources outside of this book Getting Started with OpenLayers What is OpenLayers? OpenLayers is an open source, client side JavaScript library for making interactive web maps, viewable in nearly any web browser. Since it is a client side library, it requires no special server side software or settings—you can use it without even downloading anything! Originally developed by Metacarta, as a response, in part, to Google Maps, it has grown into a mature, popular framework with many passionate developers and a very helpful community. Why use OpenLayers? OpenLayers makes creating powerful web-mapping applications easy and fun. It is very powerful but also easy to use—you don't even need to be a programmer to make a great map with it. It's open source, free, and has a strong community behind it. So if you want to dig into the internal code, or even improve it, you're encouraged to do so. Cross browser compatibility is handled for you—it even works in IE6. OpenLayers is not tied to any proprietary technology or company, so you don't have to worry so much about your application breaking (unless you break it). At the time of writing, support for modern mobile and touch devices is in the works (with many proof of concept examples), and should be in the official library in the near future—if they aren't by the time you're reading this. OpenLayers allows you to build entire mapping applications from the ground up, with the ability to customize every aspect of your map—layers, controls, events, etc. You can use a multitude of different map server backends together, including a powerful vector layer. It makes creating map 'mashups' extremely easy. What, technically, is OpenLayers? We said OpenLayers is a client side JavaScript library, but what does this mean? Client side When we say client side we are referring to the user's computer, specifically their web browser. The only thing you need to have to make OpenLayers work is the OpenLayers code itself and a web browser. You can either download it and use it on your computer locally, or download nothing and simply link to the JavaScript file served on the site that hosts the OpenLayers project (http://openlayers.org). OpenLayers works on nearly all browsers and can be served by any web server or your own computer. Using a modern, standard-based browser such as Firefox, Google Chrome, Safari, or Opera is recommended. [8] Download from Wow! eBookChapter 1 Library When we say library we mean that OpenLayers is an API (Application Programmer Interface) that provides you with tools to develop your own web maps. Instead of building a mapping application from scratch, you can use OpenLayers for the mapping part, which is maintained and developed by a bunch of brilliant people. For example, if you wanted to write a blog you could either write your own blog engine, or use an existing one such as WordPress or Blogger and build on top of it. Similarly, if you wanted to create a web map, you could write your own from scratch, or use software that has been developed and tested by a group of developers with a strong community behind it. By choosing to use OpenLayers, you do have to learn how to use the library (or else you wouldn't be reading this book), but the benefits greatly outweigh the costs. You get to use a rich, highly tested and maintained code base, and all you have to do is learn how to use it. Hopefully, this book will help you with that. OpenLayers is written in JavaScript, but don't fret if you don't know it very well. All you really need is some knowledge of the basic syntax, and we'll try to keep things as clear as possible in the code examples. If you are unfamiliar with JavaScript, Mozilla provides phenomenal JavaScript documentation at https://developer.mozilla. org/en/javascript. Anatomy of a web-mapping application First off—what is a 'web-mapping application'? To put it bluntly, it's some type of Internet application that makes use of a map. This could be a site that displays the latest geo-tagged images from Flickr (we'll do this in Chapter 11), a map that shows markers of locations you've traveled to, or an application that tracks invasive plant species and displays them. If it contains a map and it does something, you could argue that it is a web map application. The term can be used in a pretty broad sense. [9] Getting Started with OpenLayers So where exactly does OpenLayers fit in? We know OpenLayers is a client side mapping library, but what does that mean? Let's take a look at the following screenshot: This is called the Client / Server Model and it is, essentially, the core of how all web applications operate. In the case of a web map application, some sort of map client (e.g., OpenLayers) communicates with some sort of web map server (e.g., a WMS server or the Google Maps backend). Web map client OpenLayers lives on the client side. One of the primary tasks the client performs is to get map images from a map server. Essentially, the client has to ask a map server for what you want to look at. Every time you navigate or zoom around on the map, the client has to make new requests to the server—because you're asking to look at something different. OpenLayers handles this all for you, and it is happening via asynchronous JavaScript (AJAX) calls to a map server. To reiterate—the basic concept is that OpenLayers sends requests to a map server for map images every time you interact with the map, then OpenLayers pieces together all the returned map images so it looks like one big, seamless map. In Chapter 2, we'll cover this concept in more depth. Web map server A map server (or map service) provides the map itself. There are a myriad of different map server backends. A small sample includes WMS, Google Maps, Yahoo! Maps, ESRI ArcGIS, WFS, and OpenStreet Maps. If you are unfamiliar with those terms, don't sweat it. The basic principle behind all those services is that they allow you to specify the area of the map you want to look at (by sending a request), and then the map servers send back a response containing the map image. With OpenLayers, you can choose to use as many different backends in any sort of combination as you'd like. OpenLayers is not a web map server; it only consumes data from them. So, you will need to be able to access some type of web map service. Don't worry though. Fortunately, there are a myriad of free and/or open source web map servers available that are remotely hosted or easy to set up yourself, such as MapServer. [ 10 ] Chapter 1 Throughout this book, we'll often use a freely available web mapping service from OSGeo, so don't worry about having to provide your own. With many web map servers you do not have to do anything to use them—just supplying a URL to them in OpenLayers is enough. OSGeo, OpenStreet Maps, Google, Yahoo!, and Bing Maps, for instance, provide access to their map servers (although, some commercial restrictions may apply with various services in some situations). Relation to Google / Yahoo! / and other mapping APIs The Google, Yahoo!, Bing, and ESRI Mappings API allow you to connect with their map server backend. Their APIs also usually provide a client side interface (at least in the case of Google Maps). The Google Maps API, for instance, is fairly powerful. You have the ability to add markers, plot routes, and use KML data (things you can also do in OpenLayers)—but the main drawback is that your mapping application relies totally on Google. The map client and map server are provided by a third party. This is not inherently a bad thing, and for many projects, Google Maps and the like are a good fit. However, there are quite a few drawbacks. You're not in control of the backend You can't really customize the map server backend, and it can change at any time There may be some commercial restrictions, or some costs involved These other APIs also cannot provide you with anything near the amount of flexibility and customization that an open source mapping application framework (i.e., OpenLayers) offers Layers in OpenLayers So, what's with the Layer in OpenLayers? Well, OpenLayers allows you to have multiple different 'backend' servers that your map can use. To access a web map server, you create a layer object and add it to your map with OpenLayers. For instance, if you wanted to have a Google Maps and a WMS service displayed on your map, you would use OpenLayers to create a GoogleMaps layer object and a WMS layer object, and then add them to your OpenLayers map. We'll soon see an example with a WMS layer, so don't worry if you're a little confused. [ 11 ] Getting Started with OpenLayers What is a Layer? Like layers of an onion, each layer is above and will cover up the previous one; the order that you add in the layers is important. With OpenLayers, you can arbitrarily set the overall transparency of any layer, so you are easily able to control how much layers cover each other up, and dynamically change the layer order at any time. For instance, you could have a Google map as your base layer, a layer with satellite imagery that is semi-transparent, and a vector layer all active on your map at once. A vector layer is a powerful layer that lets us add markers and various geometric objects to our maps—we'll cover it in Chapter 9. Thus, in this example, your map would have three separate layers. We'll go into much more depth about layers and how to use and combine them in Chapter 3. The OpenLayers website The website for OpenLayers is located at http://openlayers.org/. To begin, we need to download a copy of OpenLayers (or, we can directly link to the library—but we'll download a local copy). You can download the compressed library as either a .tar.gz or .zip, but both contain the same files. [ 12 ] Chapter 1 Let's go over the links: Link to the hosted version: If you do not want to actually download OpenLayers, you can instead link to the OpenLayers library by adding this script URL to your site in a 7. 27. 28. 29. 30. 31.32. 33.