Proj4js is not necessary for this example, as transforming between these two projections is possible without proj4js. Try the following steps:
var proj_4326 = ol.proj.get('EPSG:4326');
var proj_3857 = ol.proj.get('EPSG:3857');var point_to_transform = [-79, 42];
EPSG:4326 (our source proj_4326 projection object) to EPSG:3857 (our destination proj_3857 projection object):var myTransformedPoint = ol.proj.transform(point_to_transform, proj_4326, proj_3857);
console.log(myTransformedPoint); console.log(myTransformedPoint[0], myTransformedPoint[1]);
[-8794239.7714444, 5160979.4433314] -8794239.7714444 5160979.443 3314
We just transformed a point in the EPSG:4326 projection to a point in the EPSG:3857 projection. Let's take a closer look at the transform method we called on the point_to_transform object:
ol.proj.transform(point_to_transform, 'EPSG:4326', 'EPSG:3857');
This will transform the original point from the EPSG:4326 projection to the EPSG:3857 projection. Notice, we are calling the function directly from an ol.Coordinate array. The ol.proj.transform() function's definition is as follows:
In this case, our source projection is in EPSG:4326, and our destination projection is in EPSG:3857. Keep in mind however, that EPSG:4326 and EPSG:3857 are the only two projections you can do transforms on with OpenLayers out-of-the-box.
When creating a map, all the raster layers (image-based layers; nearly every layer except the vector and image layer) must be in the same projection as the map. It's possible to do projection transformations with coordinates and the vector layer, but once OpenLayers gets back an image from a map server, it cannot reproject the image itself (that's something the map server has to do).
The Proj4js library allows you to transform the coordinates from one coordinate system into another coordinate system. The Proj4js website is http://proj4js.org. By just including the Proj4js library on your page (like you do with OpenLayers), you can do more transforms within OpenLayers. Note that Proj4js also only ships with only a few codes. Definitions need to be added for all others.
The site http://epsg.io contains Proj4js definitions for most of the EPSG codes. When you are using data from foreign countries, you need to know the most common used projections. For this, go to the ProjFinder website, http://projfinder.com, and guess projections for unknown places.
Ideally, you should be using the same projection throughout your map, but there are times when you may want to display the coordinates in a different projection—such as with a vector layer. Let's take a look at how to set up the Proj4js library.