Table of Contents for
OpenLayers 3 : Beginner's Guide

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition OpenLayers 3 : Beginner's Guide by Erik Hazzard Published by Packt Publishing, 2015
  1. Cover
  2. Table of Contents
  3. OpenLayers 3 Beginner's Guide
  4. OpenLayers 3 Beginner's Guide
  5. Credits
  6. About the Authors
  7. About the Reviewers
  8. www.PacktPub.com
  9. Preface
  10. What you need for this book
  11. Who this book is for
  12. Sections
  13. Time for action – heading
  14. Conventions
  15. Reader feedback
  16. Customer support
  17. 1. Getting Started with OpenLayers
  18. Advantages of using OpenLayers
  19. What, technically, is OpenLayers?
  20. Anatomy of a web mapping application
  21. Connecting to Google, Bing Maps, and other mapping APIs
  22. Time for action – downloading OpenLayers
  23. Time for action – creating your first map
  24. Where to go for help
  25. OpenLayers issues
  26. OpenLayers source code repository
  27. Getting live news from RSS and social networks
  28. Summary
  29. 2. Key Concepts in OpenLayers
  30. Time for action – creating a map
  31. Time for action – using the JavaScript console
  32. Time for action – overlaying information
  33. OpenLayers' super classes
  34. Key-Value Observing with the Object class
  35. Time for action – using bindTo
  36. Working with collections
  37. Summary
  38. 3. Charting the Map Class
  39. Time for action – creating a map
  40. Map renderers
  41. Time for action – rendering a masterpiece
  42. Map properties
  43. Time for action – target practice
  44. Map methods
  45. Time for action – creating animated maps
  46. Events
  47. Views
  48. Time for action – linking two views
  49. Summary
  50. 4. Interacting with Raster Data Source
  51. Layers in OpenLayers 3
  52. Common operations on layers
  53. Time for action – changing layer properties
  54. Tiled versus untiled layers
  55. Types of raster sources
  56. Tiled images' layers and their sources
  57. Time for action – creating a Stamen layer
  58. Time for action – creating a Bing Maps layer
  59. Time for action – creating tiles and adding Zoomify layer
  60. Image layers and their sources
  61. Using Spherical Mercator raster data with other layers
  62. Time For action – playing with various sources and layers together
  63. Time For action – applying Zoomify sample knowledge to a single raw image
  64. Summary
  65. 5. Using Vector Layers
  66. Time for action – creating a vector layer
  67. How the vector layer works
  68. The vector layer class
  69. Vector sources
  70. Time for action – using the cluster source
  71. Time for action – creating a loader function
  72. Time for action – working with the TileVector source
  73. Time for action – a drag and drop viewer for vector files
  74. Features and geometries
  75. Time for action – geometries in action
  76. Time for action – interacting with features
  77. Summary
  78. 6. Styling Vector Layers
  79. Time for action – basic styling
  80. The style class
  81. Time for action – using the icon style
  82. Have a go hero – using the circle style
  83. Multiple styles
  84. Time for action – using multiple styles
  85. Style functions
  86. Time for action – using properties to style features
  87. Interactive styles
  88. Time for action – creating interactive styles
  89. Summary
  90. 7. Wrapping Our Heads Around Projections
  91. Time for action – using different projection codes
  92. Time for action – determining coordinates
  93. OpenLayers projection class
  94. Transforming coordinates
  95. Time for action – coordinate transforms
  96. Time for action – setting up Proj4js.org
  97. Time for action – reprojecting extent
  98. Time for action – using custom projection with WMS sources
  99. Time for action – reprojecting geometries in vector layers
  100. Summary
  101. 8. Interacting with Your Map
  102. Time for action – converting your local or national authorities data into web mapping formats
  103. Time for action – testing the use cases for ol.interaction.Select
  104. Time for action – more options with ol.interaction.Select
  105. Introducing methods to get information from your map
  106. Time for action – understanding the forEachFeatureAtPixel method
  107. Time for action – understanding the getGetFeatureInfoUrl method
  108. Adding a pop-up on your map
  109. Time for action – introducing ol.Overlay with a static example
  110. Time for action – using ol.Overlay dynamically with layers information
  111. Time for action – using ol.interaction.Draw to share new information on the Web
  112. Time for action – using ol.interaction.Modify to update drawing
  113. Understanding interactions and their architecture
  114. Time for action – configuring default interactions
  115. Discovering the other interactions
  116. Time for action – using ol.interaction.DragRotateAndZoom
  117. Time for action – making rectangle export to GeoJSON with ol.interaction.DragBox
  118. Summary
  119. 9. Taking Control of Controls
  120. Adding controls to your map
  121. Time for action – starting with the default controls
  122. Controls overview
  123. Time for action – changing the default attribution styles
  124. Time for action – finding your mouse position
  125. Time for action – configuring ZoomToExtent and manipulate controls
  126. Creating a custom control
  127. Time for action – extending ol.control.Control to make your own control
  128. Summary
  129. 10. OpenLayers Goes Mobile
  130. Using a web server
  131. Time for action – go mobile!
  132. The Geolocation class
  133. Time for action – location, location, location
  134. The DeviceOrientation class
  135. Time for action – a sense of direction
  136. Debugging mobile web applications
  137. Debugging on iOS
  138. Debugging on Android
  139. Going offline
  140. Time for action – MANIFEST destiny
  141. Going native with web applications
  142. Time for action – track me
  143. Summary
  144. 11. Creating Web Map Apps
  145. Using geospatial data from Flickr
  146. Time for action – getting Flickr data
  147. A simple application
  148. Time for Action – adding data to your map
  149. Styling the features
  150. Time for action – creating a style function
  151. Creating a thumbnail style
  152. Time for action – switching to JSON data
  153. Time for action – creating a thumbnail style
  154. Turning our example into an application
  155. Time for action – adding the select interaction
  156. Time for action – handling selection events
  157. Time for action – displaying photo information
  158. Using real time data
  159. Time for action – getting dynamic data
  160. Wrapping up the application
  161. Time for action – adding dynamic tags to your map
  162. Deploying an application
  163. Creating custom builds
  164. Creating a combined build
  165. Time for action – creating a combined build
  166. Creating a separate build
  167. Time for action – creating a separate build
  168. Summary
  169. A. Object-oriented Programming – Introduction and Concepts
  170. Going further
  171. B. More details on Closure Tools and Code Optimization Techniques
  172. Introducing Closure Library, yet another JavaScript library
  173. Time for action – first steps with Closure Library
  174. Making custom build for optimizing performance
  175. Time for action – playing with Closure Compiler
  176. Applying your knowledge to the OpenLayers case
  177. Time for action - running official examples with the internal OpenLayers toolkit
  178. Time for action - building your custom OpenLayers library
  179. Syntax and styles
  180. Time for action – using Closure Linter to fix JavaScript
  181. Summary
  182. C. Squashing Bugs with Web Debuggers
  183. Time for action – opening Chrome Developer Tools
  184. Explaining Chrome Developer debugging controls
  185. Time for action – using DOM manipulation with OpenStreetMap map images
  186. Time for action – using breakpoints to explore your code
  187. Time for action – playing with zoom button and map copyrights
  188. Using the Console panel
  189. Time for action – executing code in the Console
  190. Time for action – creating object literals
  191. Time for action – interacting with a map
  192. Improving Chrome and Developer Tools with extensions
  193. Debugging in other browsers
  194. Summary
  195. D. Pop Quiz Answers
  196. Chapter 5, Using Vector Layers
  197. Chapter 7, Wrapping Our Heads Around Projections
  198. Chapter 8, Interacting with Your Map
  199. Chapter 9, Taking Control of Controls
  200. Chapter 10, OpenLayers Goes Mobile
  201. Appendix B, More details on Closure Tools and Code Optimization Techniques
  202. Appendix C, Squashing Bugs with Web Debuggers
  203. Index

Time for action – using properties to style features

For this example, we will render the country layer by styling each country based on income level by associating its country code to income level data provided by the world bank. There are quite a few brackets; so, we've simplified it to four levels: high, medium, low, and poor. We'll draw each country in a color associated with its income level based on these brackets. Let's start from the previous example.

  1. At the beginning of the <script> tag, before anything else, we will define colors for the four brackets. Use any colours you like:
    var high = [64,196,64,1];
    var mid = [108,152,64,1];
    var low = [152,108,64,1];
    var poor = [196,32,32,1];
  2. The income levels for each feature are indicated by a code. We need a way to look up the color to use for each code. You don't need to include the comments, they are there to show how we are grouping the income levels:
    var incomeLevels = {
      'HIC': high, // high income
      'OEC': high, // high income OECD
      'NOC': high, // high income, non-OECD
      'UMC': mid, // upper middle income
      'MIC': mid, // middle income
      'LMC': mid, // lower middle income
      'LIC': low, // low income
      'LMY': low, // low and middle income
      'HPC': poor // heavily indebted poor country
    };
  3. It's good practice to have a default style to use if something goes wrong:
    var defaultStyle = new ol.style.Style({
      fill: new ol.style.Fill({
        color: [250,250,250,1]
      }),
      stroke: new ol.style.Stroke({
        color: [220,220,220,1],
        width: 1
      })
    });
  4. Our style function will create styles as needed and cache them. Here's the cache and the style function. We'll discuss what it does at the end of the code.
    var styleCache = {};
    function styleFunction(feature, resolution) {
      var level = feature.get('incomeLevel');
      if (!level || !incomeLevels[level]) {
        return [defaultStyle];
      }
      if (!styleCache[level]) {
        styleCache[level] = new ol.style.Style({
          fill: new ol.style.Fill({
            color: incomeLevels[level]
          }),
          stroke: defaultStyle.stroke
        });
      }
      return [styleCache[level]];
    }
  5. Modify the countries layer to use the style function. While you are at it, make sure the source is specified as a separate object. We'll need this in a moment:
    var source = new ol.source.GeoJSON({
      projection: 'EPSG:3857',
      url: '../assets/data/countries.geojson'
    });
    var countries = new ol.layer.Vector({
      source: source,
      style: styleFunction
    });
  6. Now, we come to the part where we load the income data and associate it with our features. Add the following somewhere after the source is defined:
    var key = source.on('change', function(event) {
      if (event.target.getState() == 'ready') {
        source.unByKey(key);
        $.ajax('../assets/data/income_levels.json').done(function(data) {
          source.forEachFeature(function(feature) {
            var code = feature.get('iso_a2');
            if (data[code]) {
              feature.set('incomeLevel', data[code]);
            }
          });
        });
      }
    });
  7. Give it a whirl, you should see something like the following screenshot:
    Time for action – using properties to style features

What just happened?

Let's review what is happening in this example. We are using a standard setup for vector layers, and combining some extra data into our features dynamically. The data is used to style, or classify, the country polygons by the income level as recorded by the world bank. Some interesting things are happening in this example; so we'll look at each step and highlight what's going on.

In step 1, we created some colors to be used to fill countries that fall into one of the four income categories. The number of categories is arbitrary—you can create colors for each of the income levels, or decide to group them differently.

In step 2, we created an object that we can use to look up a color based on an income level, and in step 3, we defined a default style. It's usually good practice when dealing with data that can change to have some kind of fallback so that your code doesn't break. We'll use the default style if we can't find a income level in our lookup object.

In step 4, we created our style function. Another best practice is to reuse style objects as much as possible. Since several countries might be drawn in the same style, we created an empty object (the styleCache) to store previously created styles. The actual function comes next. When the style function is called, it gets a reference to the feature being styled and the current resolution of the view on which it is being rendered. We aren't using the resolution in this example. We are using the feature, however. The feature should have a property called incomeLevel that matches the values in our lookup tables, so we grab that value and assign it to a variable. If the income level wasn't set or if it doesn't exist in the lookup table, we'll return the default style. Otherwise, we can check to see whether the styleCache object already has a style for this income level. If it doesn't, we need to create a new style using the color from our lookup table. In this case, we are using the default style's stroke for everything, but you could easily change the stroke for each feature too. Because we've assigned the new style to the correct slot in the cache, we can then return it directly.

Note

Note that in both cases, we return an array containing the style. This is required for a very important reason: performance! The Style functions are executed a lot of times when rendering vector features and if OpenLayers had to check the return type of each call to see if it was a style object or an array of style objects, this would add significant overhead to the rendering pipeline. For individual features, the difference is so tiny that it's probably not measurable even with the best of tools. For many features, this tiny difference adds up to a lot and it is measurable. The OpenLayers developers have put a lot of effort into this kind of detail and it shows!

In step 5, we modified the layer to use the style function we just created and defined a separate variable for the source. This was to make the next step a little easier.

In step 6, we loaded the income level data. The goal of the code in this step is to load the income data and associate it with the appropriate country feature. To do this, we need to make sure that the country features have been loaded. Once the countries are loaded, then, we need to load the income data. Then we can create a new property on each country feature with the appropriate income level. There are a few important things happening in this step, so we'll review each line:

  • Line 1: This registers for the change event on the source and assigns the return value to a variable. The sources inherit from ol.Observable and so they provide the on() method for this. Recall from Chapter 2, Key Concepts in OpenLayers, that the on() method returns a key that can be used later to deregister an event handler (using the unByKey() method)—we'll need it in just a moment. The change event on a vector source is triggered when the source changes state.
  • Line 2: This checks the state of the source to see if the source is ready. There are three states—loading, ready, and error—for a vector source, and we are interested to know when the state changes to ready as that's when we can load our income data safely.
  • Line 3: This unregisters the event handler by using the unByKey() method so that the handler doesn't get called again. This is very important. A source triggers the change event when its state changes, but also when any of its features change. This means that our event handler will get called again when we add properties to the feature. Since the state of the source will already be ready, our code will try to load the income data again and will create an infinite loop.
  • Line 4: This line loads the income data using jQuery's ajax() method. The data loaded from this file is passed to the function we register using done().
  • Line 5: This line starts a loop over each of the features in the source by calling forEachFeature() and providing a function that will be called with each feature.
  • Line 6: This line gets the iso_a2 property of the feature, which is a two letter code associated with each country. The income data in our file is organized by this code so we can use this code to get the income level for each country.
  • Line 7: This checks to see if the income data has a value for the current country and line 8 adds the income level as a property of the feature if it does. As we add the property to each feature, the map responds to the change by redrawing itself. You might think that it seems inefficient to redraw the map for each feature change. What actually happens though, is that the map schedules a redraw for the next available render cycle. This won't happen until the current JavaScript process completes, so all the features will be changed and the map will only be redrawn once at some (very short) time later.

These eight lines of code accomplish quite a bit and combine concepts from other chapters of this book, including Chapter 2, Key Concepts in OpenLayers (event registration and deregistration) and Chapter 5, Using Vector Layers (vector layers, vector sources, and feature properties).