leaflet.utm
Version:
Converts LatLng to UTM WGS84 in Leaflet
100 lines (80 loc) • 3.39 kB
HTML
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Leaflet UTM Demo</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet-src.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.3/proj4.js"></script>
<style type="text/css">
html, body { width: 100%; height: 100%; margin: 0; }
#map, #container { width: 70%; height: 70%; margin: 20px; }
</style>
</head>
<body>
<br>
Format options: {x} {y} {sep} {zone} {band} {hemi} {datum}<br>
toString options: decimals, sep, format, north, south<br>
example: {"decimals": 2, "sep": ";", "north":"NNN", "south": "sss", "format": "{x}{sep} {y}{sep} {zone}{band} {hemi} {datum}"}<br>
<textarea id="opts">{}</textarea> <br>
Last point data...
<div id="res"></div>
<div id="map"></div>
<script src="../L.LatLng.UTM.js"></script>
<script type="text/javascript">
var center = [37.056019, -3.365688];
var options = {
attribution:
'<a href="http://openstreetmap.org/copyright"</a> © ' +
'OpenStreetmap Contributors',
subdomains: 'abc',
minZoom: 0,
maxZoom: 20
};
var osm = L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', options);
var map = L.map('map', {
layers: [osm],
center: center,
zoom: 14
});
var fun = function(t) {
var opts = document.getElementById('opts').value;
var opt = JSON.parse(opts)
t.bindPopup(t.getLatLng().utm().toString(opt), {autoClose: false}).openPopup();
// update last point info
var p = t.getLatLng();
var o = t.getLatLng().utm();
var other = o.latLng();
var txt = '';
txt += 'Original: ' + p.toString(10) + '<br>';
txt += 'UTM-latLng: ' + other.toString(10) + '<br>';
txt += 'UTM: ' + p.utm().toString(opt) + '<br>';
txt += 'stringify: ' + JSON.stringify(o) + '<br>';
txt += 'Original == UTM-latLng: ' + p.equals(other) + '<br>';
// for proj4
var utm = '+proj=utm +zone=' + o.zone + (o.southHemi ? '+south' : '');
var wgs84 = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs';
var pj = proj4(wgs84, utm, [t.getLatLng().lng, t.getLatLng().lat]);
txt += 'proj4: ' + pj[0] + ', ' + pj[1] + '<br>';
var margin = Math.max(Math.abs(o.x - pj[0]), Math.abs(o.y - pj[1]));
txt += 'proj4 == UTM (< 0.001): ' + (margin < 0.001) + ' | err: ' + margin;
document.getElementById('res').innerHTML = txt;
};
var create = function(ll) {
var marker = new L.Marker(ll, {draggable: true}).addTo(map);
marker.on('dblclick', function(e) {
map.removeLayer(marker);
});
marker.on('dragend', function(e) {
fun(e.target);
});
fun(marker);
}
create(center);
map.on('click', function(e) {
create(e.latlng);
});
</script>
</body>
</html>