Search code examples
javascriptrequirejsopenlayers-3proj4js

Using Openlayers 3 and proj4js with RequireJS


I am experiencing an issue when using Openlayers 3 and proj4js with RequireJS.

Using a standard JavaScript file and html, I have working code to display a map and show the coordinates in EPSG:27700 using an Openlayers mouse position control.

When I make use of RequireJS (see the code below), the code fails due to the proj.get returning "undefined". The error in Chrome would suggest that Require is throwing the error.

I have tried to use shims, but this didn't work and I am not convinced that this is the right approach. Can anyone advise me how to get this working?

require.config({
    baseUrl: './',
    paths: {
        'domReady': '../lib/domReady',
        'openlayers': '../lib/ol',
        'proj4': '../lib/proj4'
    }
});

require([
    'domReady',
    'openlayers',
    'proj4'
], function (domReady, openLayers, proj4) {

    "use strict";

    function getLayers() {
        var baseLayer = new openLayers.layer.Tile({
                source: new openLayers.source.OSM()
            });

        return [baseLayer];
    };

    domReady(function () {
        proj4.defs('EPSG:27700', '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs');

        openLayers.proj.get("EPSG:27700").setExtent([0, 0, 700000, 1300000]);

        var mousePositionControl = new openLayers.control.MousePosition({
            coordinateFormat: openLayers.coordinate.createStringXY(4),
            projection: 'EPSG:27700'
        });

        var map = new openLayers.Map({
            target: 'map',
            layers: getLayers(),
            controls: [mousePositionControl],
            view: new openLayers.View({
                projection: 'EPSG:27700',
                center: [300000, 500000],
                resolutions: [4500, 3200, 2400, 1600, 800, 400, 200, 100, 50, 25, 10, 5, 2.5, 1, 0.5, 0.25, 0.125, 0.0625],
                zoom: 3,
                minResolution: 25,
                maxResolution: 800
            })
        });
    });
});

Solution

  • You have to tell OpenLayers how to find proj4.js first:

    openLayers.proj.setProj4(proj4);
    

    The above snippet requires OpenLayers >= v3.13.0, and assumes a setup like in the code snippet in the question.