This step is similar to the way we set up the now usual template for OpenLayers 3.
proj4.js file into a new assets/proj4js directory at the root code directory.<head> section of your code before the OpenLayers 3 library inclusion code:<script src="../assets/proj4js/proj4.js"> </script>
var test_proj = proj4('EPSG:4326');
console.log(test_proj);
Object {forward: function, inverse: function, oProj: Projection}
We just included the Proj4js library and tested to see if it worked. If you received an error when you attempted to call proj4('EPSG:4326'), it means that the location of the proj4.js file was wrong. Ensure that the path in the <script> tag correctly references the JavaScript file.
Proj4js custom projections are required, particularly when you are using data at the local level and you want to use your country official projection(s) or you depend on external data sources such as web services.
Now that the Proj4js library is included, you can do transforms with more projections, the same way we did in the previous example. Except EPSG:3857, EPSG:4326, and EPSG:4269, there are no projections defined; however, you are able to define them yourself. For example, for France, the main official EPSG code is as follows:
proj4.defs("EPSG:2154","+proj=lcc +lat_1=49 +lat_2=44 +lat_0=46.5 +lon_0=3 +x_0=700000 +y_0=6600000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs");After this, you'd be able to use EPSG:2154 for projection transformations just like you were able to use EPSG:4326 and EPSG:3857 from the earlier examples.
A more complete list of projections (containing Proj4js definitions for nearly any EPSG code) can be found at http://epsg.io.
To get projection definitions, you can copy them from http://epsg.io or also load them from the URL. For example, adding the proj4.js script after the <script src="http://epsg.io/2154.js"></script>. The URL pattern to retrieve the definition is http://epsg.io/xxx.js where xxx is the EPSG code you want to use.
When you are using custom projections in OpenLayers 3, you need to declare the projection, as described earlier. Use ol.proj.get to retrieve its definition and define the projection extent. For this, reuse the http://epsg.io site.
When you want to declare a custom projection, you must create an object, such as the preceding one, when you start your JavaScript code:
var projection = ol.proj.get('EPSG:2154');
projection.setExtent([-378305.81, 6093283.21, 1212610.74, 7186901.68]);You will then be able to use the usual ol.proj.transform function with this new projection.
Sometimes, in another context for example, to provide parameters to web services it can be necessary to convert extent between projections. Let's inspect how to do this operation.