fixed polygon and multipolygon creation from GeoJSON

This commit is contained in:
javi 2013-03-14 13:05:12 +01:00
parent 81221ae4cd
commit 5c059e7470

View File

@ -15,13 +15,13 @@ L.GeoJSON = L.FeatureGroup.extend({
}, },
addData: function (geojson) { addData: function (geojson) {
var features = L.Util.isArray(geojson) ? geojson : geojson.features, var features = geojson instanceof Array ? geojson : geojson.features,
i, len; i, len;
if (features) { if (features) {
for (i = 0, len = features.length; i < len; i++) { for (i = 0, len = features.length; i < len; i++) {
// Only add this if geometry or geometries are set and not null // Only add this if geometry or geometries are set and not null
if (features[i].geometries || features[i].geometry || features[i].features) { if (features[i].geometries || features[i].geometry) {
this.addData(features[i]); this.addData(features[i]);
} }
} }
@ -97,23 +97,23 @@ L.extend(L.GeoJSON, {
case 'Polygon': case 'Polygon':
latlngs = this.coordsToLatLngs(coords, 1); latlngs = this.coordsToLatLngs(coords, 1);
latlngs = this.removeLastPoint(latlngs, 0);
return new L.Polygon(latlngs); return new L.Polygon(latlngs);
case 'MultiLineString': case 'MultiLineString':
latlngs = this.coordsToLatLngs(coords, 1); latlngs = this.coordsToLatLngs(coords, 1);
return new L.MultiPolyline(latlngs); return new L.MultiPolyline(latlngs);
case 'MultiPolygon': case "MultiPolygon":
latlngs = this.coordsToLatLngs(coords, 2); latlngs = this.coordsToLatLngs(coords, 2);
// geojson closes the polygons added the frist
// coordinate at the end
latlngs = this.removeLastPoint(latlngs, 1);
return new L.MultiPolygon(latlngs); return new L.MultiPolygon(latlngs);
case 'GeometryCollection': case "GeometryCollection":
for (i = 0, len = geometry.geometries.length; i < len; i++) { for (i = 0, len = geometry.geometries.length; i < len; i++) {
layer = this.geometryToLayer({ layer = this.geometryToLayer(geometry.geometries[i], pointToLayer);
geometry: geometry.geometries[i],
type: 'Feature',
properties: geojson.properties
}, pointToLayer);
layers.push(layer); layers.push(layer);
} }
return new L.FeatureGroup(layers); return new L.FeatureGroup(layers);
@ -123,6 +123,21 @@ L.extend(L.GeoJSON, {
} }
}, },
// removes the last point from each array. It allows to remove the
// duplicated point GeoJSON uses to close Polygons
removeLastPoint: function (coords, levelsDeep) {
var latlng,
latlngs = [],
i, len;
for (i = 0, len = coords.length; i < len; i++) {
latlng = levelsDeep ?
this.removeLastPoint(coords[i], levelsDeep - 1) :
coords[i].slice(0, coords[i].length - 1);
latlngs.push(latlng);
}
return latlngs;
},
coordsToLatLng: function (coords, reverse) { // (Array, Boolean) -> LatLng coordsToLatLng: function (coords, reverse) { // (Array, Boolean) -> LatLng
var lat = parseFloat(coords[reverse ? 0 : 1]), var lat = parseFloat(coords[reverse ? 0 : 1]),
lng = parseFloat(coords[reverse ? 1 : 0]); lng = parseFloat(coords[reverse ? 1 : 0]);