[GIS] Using proj4js and Leaflet to transform coordinates

leafletproj

I'm trying to use proj4js with Leaflet to convert a mouse click event from WGS84 coordinates into British National Grid but when I do this I get NaN for the converted coordinates.

Here's the code:

        function onMapClick(e) {

        var bngprojection = "+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";
        var bngcoords = proj4(bngprojection, [e.latlng]);
        popup
            .setLatLng(e.latlng)
            .setContent("You clicked the map at " + e.latlng.toString() + ", or in bng... " + bngcoords.toString())
            .openOn(map);
    }

The BNG projection info I got from: http://spatialreference.org/ref/epsg/27700/proj4/. I can't seem to find much documentation at https://github.com/proj4js/proj4js

Best Answer

The third argument to proj4 is expected to be an array with two values corresponding to a lat, lon, but you are in fact passing an array with one value which is a Leaflet LatLng object.

The correct way to call proj4 in your code is:

var bngcoords = proj4(bngprojection, [e.latlng.lat, e.latlng.lon]);

or, clearer:

var latlon = e.latlng;
var bngcoords = proj4(bngprojection, [latlon.lat, latlon.lon]);

The reference for calling proj4 is at the Using section in this page.