From cffeae7829fd6b9e8478e30150ab950aa4d19624 Mon Sep 17 00:00:00 2001 From: Sebastien Savater Date: Wed, 29 May 2019 09:24:29 +0200 Subject: [PATCH] Allow overriding of GeoJSON output --- spec/suites/layer/GeoJSONSpec.js | 41 ++++++++++++++++++++++++++++++++ src/layer/GeoJSON.js | 4 ++-- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/spec/suites/layer/GeoJSONSpec.js b/spec/suites/layer/GeoJSONSpec.js index 944e9edc522..41f16271193 100644 --- a/spec/suites/layer/GeoJSONSpec.js +++ b/spec/suites/layer/GeoJSONSpec.js @@ -471,3 +471,44 @@ describe("L.LayerGroup#toGeoJSON", function () { }); }); }); + +describe("Overriding #toGeoJSON formatting", function () { + it("is possible to overwrite output of #toGeoJSON coordinates", function () { + var marker = new L.Marker([-1.4837191022531273, 43.49222084042808]), + layerGroup = new L.LayerGroup([marker]); + + expect(layerGroup.toGeoJSON()).to.eql({ + type: 'FeatureCollection', + features: [{ + type: 'Feature', + properties: {}, + geometry: { + type: 'Point', + coordinates: [43.492221, -1.483719] + } + }] + }); + + L.GeoJSON.latLngToCoords = function (latlng, precision) { + if (typeof precision === 'number') { + return latlng.alt !== undefined ? + [L.Util.formatNum(latlng.lng, precision), L.Util.formatNum(latlng.lat, precision), L.Util.formatNum(latlng.alt, precision)] : + [L.Util.formatNum(latlng.lng, precision), L.Util.formatNum(latlng.lat, precision)]; + } else { + return latlng.alt !== undefined ? [latlng.lng, latlng.lat, latlng.alt] : [latlng.lng, latlng.lat]; + } + }; + + expect(layerGroup.toGeoJSON()).to.eql({ + type: 'FeatureCollection', + features: [{ + type: 'Feature', + properties: {}, + geometry: { + type: 'Point', + coordinates: [43.49222084042808, -1.4837191022531273] + } + }] + }); + }); +}); diff --git a/src/layer/GeoJSON.js b/src/layer/GeoJSON.js index 2efe7b4bd17..07e95518d56 100644 --- a/src/layer/GeoJSON.js +++ b/src/layer/GeoJSON.js @@ -258,7 +258,7 @@ export function latLngsToCoords(latlngs, levelsDeep, closed, precision) { for (var i = 0, len = latlngs.length; i < len; i++) { coords.push(levelsDeep ? latLngsToCoords(latlngs[i], levelsDeep - 1, closed, precision) : - latLngToCoords(latlngs[i], precision)); + GeoJSON.latLngToCoords(latlngs[i], precision)); } if (!levelsDeep && closed) { @@ -292,7 +292,7 @@ var PointToGeoJSON = { toGeoJSON: function (precision) { return getFeature(this, { type: 'Point', - coordinates: latLngToCoords(this.getLatLng(), precision) + coordinates: GeoJSON.latLngToCoords(this.getLatLng(), precision) }); } };