Skip to content

Instantly share code, notes, and snippets.

@mtravis
Last active April 27, 2023 07:53
Show Gist options
  • Save mtravis/57778a3e609b70522b5a to your computer and use it in GitHub Desktop.
Save mtravis/57778a3e609b70522b5a to your computer and use it in GitHub Desktop.
Leaflet mouse position plugin adapted for BNG (EPSG:27700)
//Adpated by mtravis from https://github.com/ardhi/Leaflet.MousePosition/ for use with BNG co-ords. Inspired by http://ghost.mixedbredie.net/reprojecting-leaflet-coordinates/
//You will still need Leaflet.MousePosition/src/L.Control.MousePosition.css from the original repo for this to work
//Also include a link to https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.10/proj4.js
//Finally add L.control.mousePosition().addTo(map); to the your script
L.Control.MousePosition = L.Control.extend({
options: {
position: 'bottomleft',
separator: ' : ',
emptyString: 'Unavailable',
lngFirst: true,
numDigits: 5,
lngFormatter: undefined,
latFormatter: undefined,
prefix: ""
},
onAdd: function (map) {
this._container = L.DomUtil.create('div', 'leaflet-control-mouseposition');
L.DomEvent.disableClickPropagation(this._container);
map.on('mousemove', this._onMouseMove, this);
this._container.innerHTML=this.options.emptyString;
return this._container;
},
onRemove: function (map) {
map.off('mousemove', this._onMouseMove)
},
_onMouseMove: function (e) {
var bngproj = '+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(bngproj, [e.latlng.lng, e.latlng.lat]);
east = bngcoords[0].toFixed(0)
north = bngcoords[1].toFixed(0)
var lng = L.Util.formatNum(east, 6) + ' E';
var lat = L.Util.formatNum(north, 5) + ' N';
var value = this.options.lngFirst ? lng + this.options.separator + lat : lat + this.options.separator + lng;
var prefixAndValue = this.options.prefix + ' ' + value;
this._container.innerHTML = prefixAndValue;
}
});
L.Map.mergeOptions({
positionControl: false
});
L.Map.addInitHook(function () {
if (this.options.positionControl) {
this.positionControl = new L.Control.MousePosition();
this.addControl(this.positionControl);
}
});
L.control.mousePosition = function (options) {
return new L.Control.MousePosition(options);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment