Table of Contents for
Mastering OpenLayers 3

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Mastering OpenLayers 3 by Gábor Farkas Published by Packt Publishing, 2016
  1. Cover
  2. Table of Contents
  3. Mastering OpenLayers 3
  4. Mastering OpenLayers 3
  5. Credits
  6. About the Author
  7. About the Reviewer
  8. www.PacktPub.com
  9. Preface
  10. What you need for this book
  11. Who this book is for
  12. Conventions
  13. Reader feedback
  14. Customer support
  15. 1. Creating Simple Maps with OpenLayers 3
  16. Structure of OpenLayers 3
  17. Building the layout
  18. Using the API documentation
  19. Debugging the code
  20. Summary
  21. 2. Applying Custom Styles
  22. Customizing the default appearance
  23. Styling vector layers
  24. Customizing the appearance with JavaScript
  25. Creating a WebGIS client layout
  26. Summary
  27. 3. Working with Layers
  28. Building a layer tree
  29. Adding layers dynamically
  30. Adding vector layers with the File API
  31. Adding vector layers with a library
  32. Removing layers dynamically
  33. Changing layer attributes
  34. Changing the layer order with the Drag and Drop API
  35. Clearing the message bar
  36. Summary
  37. 4. Using Vector Data
  38. Accessing attributes
  39. Setting attributes
  40. Validating attributes
  41. Creating thematic layers
  42. Saving vector data
  43. Saving with WFS-T
  44. Modifying the geometry
  45. Summary
  46. 5. Creating Responsive Applications with Interactions and Controls
  47. Building the toolbar
  48. Mapping interactions to controls
  49. Building a set of feature selection controls
  50. Adding new vector layers
  51. Building a set of drawing tools
  52. Modifying and snapping to features
  53. Creating new interactions
  54. Building a measuring control
  55. Summary
  56. 6. Controlling the Map – View and Projection
  57. Customizing a view
  58. Constraining a view
  59. Creating a navigation history
  60. Working with extents
  61. Rotating a view
  62. Changing the map's projection
  63. Creating custom animations
  64. Summary
  65. 7. Mastering Renderers
  66. Using different renderers
  67. Creating a WebGL map
  68. Drawing lines and polygons with WebGL
  69. Blending layers
  70. Clipping layers
  71. Exporting a map
  72. Creating a raster calculator
  73. Creating a convolution matrix
  74. Clipping a layer with WebGL
  75. Summary
  76. 8. OpenLayers 3 for Mobile
  77. Responsive styling with CSS
  78. Generating geocaches
  79. Adding device-dependent controls
  80. Vectorizing the mobile version
  81. Making the mobile application interactive
  82. Summary
  83. 9. Tools of the Trade – Integrating Third-Party Applications
  84. Exporting a QGIS project
  85. Importing shapefiles
  86. Spatial analysis with Turf
  87. Spatial analysis with JSTS
  88. 3D rendering with Cesium
  89. Summary
  90. 10. Compiling Custom Builds with Closure
  91. Configuring Node JS
  92. Compiling OpenLayers 3
  93. Bundling an application with OpenLayers 3
  94. Extending OpenLayers 3
  95. Creating rich documentation with JSDoc
  96. Summary
  97. Index

Customizing the appearance with JavaScript

Apart from direct styling with CSS, OpenLayers 3 offers some methods to specify the appearance of our maps. These methods can be used to make such changes in the behavior of the controls, which would otherwise be quite hard to achieve, if not impossible. In the next example, we will look at some of the JavaScript-based customizing options.

If you open up the code attachment, you can see some files named ch02_controls. In these files, you can examine the changes we made to the previous example. The main changes, like the title suggests, will be in the JavaScript part of the example.

Changing the overview map and the scale bar

In this example, we will group the controls based on their position on the map. In the bottom-left corner, we already lifted the overview map above the scale bar. Now, it is time to change some of their inner properties:

var map = new ol.Map({
    […]
    controls: [
        […]
        new ol.control.ScaleLine({
            units: 'degrees'
        }),
        new ol.control.OverviewMap({
            collapsible: false
        })
        […]
});

The scale bar now shows the scale in degrees, regardless of the map projection. We will later see that, in a WebGIS application, the unit of this control will be bounded to the unit of the current projection. However, the valid options for the controls are only degrees, imperial, nautical, metric, and us.

The overview map is now opened and cannot be closed. However, if you save these changes and open it up in a browser, you can see that the opened overview map covers up the scale bar again. To resolve this issue, we have to extend our CSS file with an additional rule:

.ol-overviewmap.ol-uncollapsible {
    bottom: 2em;
}

If we set an otherwise collapsible control to not collapsible, the library gives a specific class name to the control's DOM element called ol-uncollapsible. Remember the rules of CSS specificity: the more specific declaration wins. This way, we have to make our rule at least as specific as the original one, which uses a logical AND operator between the two classes. We also use this method, which can be achieved in CSS by concatenating the two class names.

Tip

Use the overview map control with great care! It can handle the Web Mercator projection correctly, but with other projections it is unreliable. It cannot handle EPSG:4326 at all, and, in the case of custom projections, it can handle the ones with metric units.

Truncating the coordinate control

The MousePosition control outputs the current mouse coordinates with great precision. This can be good; however, we will fix it to exactly three digits in the next step. Luckily, the control offers a property for a preprocessing function. Let's create a function that can truncate the output to three-digit precision:

new ol.control.MousePosition({
    coordinateFormat: function (coordinates) {
        var coord_x = coordinates[0].toFixed(3);
        var coord_y = coordinates[1].toFixed(3);
        return coord_x + ', ' + coord_y;
    }
})

The function receives an array with two coordinates as an input, and requires a string as an output. We separate the array members into variables and fix them to three decimal places with JavaScript's toFixed function. Next, we return the fixed numbers converted to a string.

Note

When a number is added to a string with the JavaScript's arithmetic + operator, it makes an automatic type conversion and concatenates the number(s) to the string(s). In our case, add the coordinate values to a string containing a comma, and a whitespace is enough to return an automatically converted string.

Changing the attribution

The goal of this step is to rework the attribution element's appearance and content a little bit. We will change the font type of the attribution control and the logo of the map. The logo is a rarely mentioned element of the map, but it plays an important role in every organization. This logo represents the given organization, and in most cases, it gets on the map in one way or another. OpenLayers 3, however, offers a method to define our custom logo and displays it in the attribution control.

Firstly, let's declare some rules for a new CSS class. It contains the required information to style the font of the attribution control:

.info-label {
    font-family: Palatino, serif;
    font-style: italic;
}
.ol-attribution img {
    max-width: 2em;
}

Note

The second rule is required to create an IE-compatible application. The default max-width rule is interpreted differently by Internet Explorer 11 than any other major browser; therefore, we need to give it an exact value. The 2 em value is the same as declared for max-height by default.

Next, we create a span element in our JavaScript code to apply our newly created custom style on it:

var infoLabel = document.createElement('span');
infoLabel.className = 'info-label';
infoLabel.textContent = 'i';

Tip

If you would like to add some text to the element, always use textContent instead of innerHTML. As innerHTML tries to parse its content as HTML, textContent is much faster. There are also some security vulnerabilities behind innerHTML, but they are related to the user input and are out of the scope of this book.

Now, we just have to include our custom element in the attribution control's constructor:

new ol.control.Attribution({
    label: infoLabel
})

For the custom logo, we have to supply an object containing its attributes to the map object. Then, the logo will appear in the attribution control. The object has a mandatory url and an optional href parameter:

var map = new ol.Map({
    […]
    logo: {
        src: '../../res/university_of_pecs.png',
        href: 'http://www.ttk.pte.hu/en'
    }
});

Tip

If the logo does not have a link, it can be directly included as a single URL string to the logo parameter.

If you put every part of the code in place, save them and load the result in a browser; you will see the following customized map:

Changing the attribution

You can also customize the appearance of the attribution control with some simple CSS rules:

.ol-attribution span {
    font-family: Palatino, serif;
    font-style: italic;
}

However, these rules also apply to the » symbol shown when the control is not collapsed:

Changing the attribution