Time for action – creating your first map
Let's dive into OpenLayers and make a map! After you finish this section, you should have a working map, which uses a publicly available WMS server backend from OSGeo.
Navigate to the
code
directory that contains theOpenLayers.js
file,/img
and/theme
directories. Create a file here calledindex.html
. This directory (/code
) will be referred to as our root directory, because it is the base (root) folder where all our files reside.Add in the following code to
index.html
and save the file as an.html
file—if you are using Windows, I suggest using Notepad++. Do not try to edit the file in a program like Microsoft Word, as it will not save properly. The following code will also be used as the base template code for many future examples in this book, so we'll be coming back to it a lot.Tip
The lines numbers in the code are for demonstration purposes; do not type them in when you are writing your code.
1.<!DOCTYPE html> 2.<html lang='en'> 3.<head> 4. <meta charset='utf-8' /> 5. <title>My OpenLayers Map</title> 6. <script type='text/javascript' src='OpenLayers.js'></script> 7. <script type='text/javascript'> 8. 9. var map; 10. 11. function init() { 12. map = new OpenLayers.Map('map_element', {}); 13. var wms = new OpenLayers.Layer.WMS( 14. 'OpenLayers WMS', 15. 'http://vmap0.tiles.osgeo.org/wms/vmap0', 16. {layers: 'basic'}, 17. {} 18. ); 19. 20. map.addLayer(wms); 21. if(!map.getCenter()){ 22. map.zoomToMaxExtent(); 23. } 24. } 25. 26. </script> 27.</head> 28. 29.<body onload='init();'> 30. <div id='map_element' style='width: 500px; height: 500px;'> 31. </div> 32.</body> 33.</html>
Open up
index.html
in your web browser. You should see something similar to:
What just happened?
We just created our first map using OpenLayers! If it did not work for you for some reason, try double checking the code and making sure all the commas and parentheses are in place. You can also refer to the Preface where a link to code samples used in the book is given. By default, we're given a few controls if we don't specify any. We will use the file we created as a template for many examples throughout the book, so save a copy of it so you can easily reference it later.
The control on the left side (the navigation buttons) is called the PanZoom control. You can click the buttons to navigate around the map, drag the map with your mouse/use the scroll wheel to zoom in, or use your keyboard's arrow keys. We'll cover controls in far greater detail in Chapter 6.