Wednesday, April 22, 2015

OpenLayers 3 for Beginners: Part 1

Welcome to the OpenLayers 3 for Beginners: Part 1
In this tutorial, I will assume a few things:
  • You have experience with JavaScript
  • You know something about GIS (Coordinates, File Formats, etc)
  • You know some very base HTML/CSS
If for some reason you have a lesser knowledge of one of the 3 things above, you should be okay. (Ie, you know what the coordinates of the Equator are, but not the formatting of a map file or you understand JavaScript well but (I don’t know why) you don’t know anything about HTML.
If you can assure yourself you have some clue about the above 3 things, you will succeed at this tutorial, so let us begin.

OpenLayers 3 for Beginners

OpenLayers 3, the next version of the famous open source library, OpenLayers 2. I used OpenLayers 2 to implement a web map in the science world that helped show the impact of global warming on Brook Trout in New England. The biggest reason we used a web map is because interactivity allows us to show more information than a static poster, often found in many scientific presentations. We often have to make decisions in static mapping, whether or not the spacial scale is too large or too small, what layers should be shown, and how much data do we put on it. With OpenLayers we can remove this question and allow users to explore data for themselves.
We choose OpenLayers because it is free. Many organizations will put money into proprietary software when they only need to hire a programmer to create a personalized mapping application instead of a sandbox, “stitch-em-up” version that does almost the same thing.
The way I see it, is every one, despite their needs, will look at a map of data that 1) Pertains to their actual needs (Financially and Scientifically) and 2) “I wonder how that is at my house?” This is why the laboratory I work at decided that Web Mapping was important, however, it is not easy.
Remember, OpenLayers 3 is brand new. (At the time of writing, April 30th, 2014, Version 3.0.0 beta 5 has been released). This means that it can and will change. For this reason alone, if you are serious about web mapping or want to join the game before the big dogs come to play, now is the time to get good at it. You will learn how to start a Mapping Application and configure some tools, manipulate layers, and leave this set of tutorials with the basis of a mapping application. I will explain material to the best of my ability, but I will not dive into the depths of Graphic Information Systems. This tutorial is for those just starting out with Web GIS or have some OpenLayers 2 experience. If that is what you are looking for, you should head over to https://www.coursera.org/ and find yourself a nice GIS course.
This tutorial will be split up into multiple parts, I will create a Table of Contents at the top of each part once more than 1 have been created, and more features depending on the popularity. A video tutorial will follow the written tutorial for those who hate reading and love movies with me in them.
There are many other tutorials on OpenLayers 3, namely the OpenLayers 3 Workshop, however, if you feel like you want to be walked through from start to finish, stay here. If you want a product now and don’t really care to learn much, head on over to: http://ol3js.org/ol3-workshop/. I can provide you with a good start-up understanding of the basics of OpenLayers 3 that you can use to then refer to the many examples on OL3JS.org. I assure you, these couple of hours will be worth it.
You can application here I have been building with OpenLayers 3 that shows multiple layers and the ability to run some models on any given polygon. http://felek.cns.umass.edu:8080/geoserver/www/gismapper/index.html?app=nalcc#
Warning: If you wish to show your own data, you will need to configure your own map server (GeoServer, MapServer, ArcServer). You may use public data I will provide.

Part 1: Hello Map

1. Setup

You are going to need to set up a local server on your machine. OpenLayers makes http requests and if your file is being hosted through a file protocol, it will not work.


MAC:
I enjoy using MAMP on Mac. You can download it here: https://www.mamp.info/en/. Once installed and turned on, navigate to /Applications/MAMP/htdocs/. You will put your project folder here. Then, you can navigate to: http://localhost:8888/[your project name] via any web browser.
If you wish to use MAC’s built in local server, that is fine too. Follow the instructions here: http://osxdaily.com/2012/09/02/start-apache-web-server-mac-os-x/


Windows:
For Windows, I use XAMP. https://www.apachefriends.org/index.html. Download and configure it as needed, navigate to the /htdocs/ within XAMP and place your project there. Then, navigate to :http://localhost:888/[your project name] in any web browser.


Linux:
If you are using Linux I am going to safely assume setting up local servers is like breathing air to you, but just in case you can follow this link: http://www.youtube.com/watch?v=a8SMwjt_1cc

Create a new folder on your local server, and call it something appropriate. I will call mine /hello-map. In that folder, you will need to create two (2) more folders called /js and /css.

2. HTML

Now, you will need to create a simple HTML file to house your application. The basic HTML does not change and should seem familiar, the only unique line is:
<div id='map'></div>
And even then, that isn’t all that unique.
Create an index.html file and type/copy and paste the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
    <head>
        <title>Hello Map</title>
        
        <!-- Scripts go here -->
        
        <!-- Styles go here -->
        
    </head>
    
    <body>
        <div id='map'></div>
    </body>
</html>
Line 13 is the only special line, granted you know something about HTML. This is the container for our map. OpenLayers requires a div be designated the container, whether we choose to render in Canvas or directly in the DOM.
Great, we still need three (3) more lines. But first, let’s download OpenLayers 3!
You can either download or link to http://ol3js.org/en/master/build/ol.js in your <head> tag.
Insert the following into your head tag:
 <script src='http://ol3js.org/en/master/build/ol.js'></script>
Then, make a file in your /js folder called main.js. Then add another script tag to your header:
<script src='./js/main.js'></script>
You will also need OpenLayers CSS file. Add this line to the head:
<link rel='stylesheet' href='http://ol3js.org/en/master/css/ol.css'>
Good. Now let’s get down to business.
 If laziness is both your middle and last name, feel free to download the current status of this part: http://christopherjennison.com/tutorials/hello-map_1_2.zip

3. Hello Map

Now that we have a beautiful white screen at: http://localhost:8888/hello-map/ we can start to set up a super cool map.
Open up your main.js file and index.html file simultaneously and lets get to work:
We first need to initialize the mapping application, in your main.js file, let’s do just that. Write these lines in your js file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var map;
function init(){
    map = new ol.Map({
        target:'map',
        renderer:'canvas',
        view: new ol.View({
            projection: 'EPSG:900913',
            center:[0,0],
            zoom:5
        })
    });
}
Lines:
  • 1: Saving a global variable of map.
  • 4: Instantiate a map using the ol.Map class with parameters.
  • 5: Sets Target. The target is the ID of the <div> element we created.
  • 6: Sets Renderer. Here we can set the kind of renderer we want to use. I am going to default to use canvas because I like it better than the DOM that OpenLayers 2 used.
  • 7: Set the View. The View is the viewport of the mapping application. This is important. This is how information will be seen in your map.
  • 8: Setting the Projection (More on this later)
  • 9: The coordinate system of the center of the map.
  • 10: The zoom level
Because we stored our instantiation into a function, we need to call this function once the page has been loaded, head over to your index.html and change the <body> tag to
<body onload='init()'>


What is Projection?
Projection is a vital GIS term we need to spend some time about. If you don’t care, skip to the next section, otherwise you should know what it means.
The Earth is not a perfect sphere.
Oh No
You’ve been thinking about it wrong the whole time.
The Earth is actually a spheroid, that is, in non-geologist terminology, an “Imperfect Sphere”. We have mountains, ocean cliffs, canyons, etc. The way we account for this when making a map is to use Projections. A projection is, in a way, a formula for displaying coordinate points on a map. Depending on the data you receive, you may want to display data on a different projection. Some projections are very different from others, for example, the projection we use for Google is called EPGS:900913 or Google in numbers. This displays the earth as the flattest possible map we can get, still accounting for elevation. This is perfect for getting directions to your friend’s house or finding our where the neatest gas station is. Another projection is EPGS: 4326. This considers the view of the earth as if we were looking at it standing in space at a 0 degree angle from the Equator. The top and bottom of the earth is squished because it moves back in space. This is commonly used for scientific models. Scientists have to account for their position on the Earth’s surface and will use this projection for that.


You may notice now that there is nothing on the map when you reload your page.
Oh no! Is something wrong? Yes.
We forgot to set a CSS property for our map!
In the HTML index page, write the following lines into your <head> tag:
<style>

#map{
  width:100%;
  height:800px;
}

</style>
Alright, let’s try that again.
D’oh! Still no good. Here’s why:
We have nothing to show! Without anything to show, there are no boundaries, zooms, or anything. We need a layer.
In OpenLayers, a Layer is an image we project onto the map using a projection system. The layer can be of a few different types which we will cover later.
The first thing that will most commonly go on any map of the Earth is the Earth!
Below where we instantiated the map, let’s create a layer!
1
2
3
4
5
var newLayer = new ol.layer.Tile({
    source: new ol.source.OSM()
});
map.addLayer(newLayer);
  • 1: Created a new layer using OpenLayers layer.Tile class with parameters.
  • 2: The source is where the layer is going to get its images from. OpenLayers 3 is kind enough to build layers into its framework already!
  • 5: We call the function .addLayer off of our map variable.
Reload your page and there it is! Africa.

Hello Africa!

Map of Africa in OpenLayers
We found Africa.
You should try to do some small things now before moving on:
  1. Head over to http://ol3js.org/en/master/examples/ and look for basemaps. Change your layer code to put different basemaps on your map. Don’t be fooled by some of the code formatting used, you can add layers how we did just by changing the source and adding after the map is instantiated instead of before.
  2. Find out the coordinates of where you live! Go to http://cs2cs.mygeodata.eu/, input the projection 4326 and output 900913 to get your Spherical Mercator coordinates, input this pair into your center array. You should get a large scary number like: -8015003.33712;5160979.44405. [I live somewhere in this area]

If you want to download the source code for this portion of the tutorial, go to:
http://christopherjennison.com/tutorials/hello-map_1_final.zip

When you are ready, move onto Part 2.

Part 2: Layers


Revision History:
– Changed title
– Added Part 2
– Added Featured Image
-Fixed View2D to just View due to a fix on OL3’s side

How to backup and download Database using PHP

< ?php $mysqlUserName = 'databaseusername' ; $mysqlPassword = 'databasepassword' ; $mysqlHostNa...