Snippets
Created by
Piotr Szrajber
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 | !(function(window, undefined) {
function atoxy(point) {
return {
x: point[0],
y: point[1]
};
}
function xytoa(point) {
return [point.x, point.y];
}
function pack(array) {
return array.reduce(function(prev, current) {
return {
packed: prev.packed.concat(current),
lengths: prev.lengths.concat(current.length)
}
}, {
packed: [],
lengths: []
});
}
function unpack(obj) {
var packed = obj.packed,
ret = [];
for (var i = 0, l = obj.lengths.length; i < l; i++) {
var current = packed.splice(0, obj.lengths[i]);
ret.push(current);
}
return ret;
}
function _transformGeometry(sourceCrsId, targetCrsId, coords, type, callback, errback) {
if (typeof callback !== "function") {
if (typeof errback === "function") errback({
success: false,
message: "you must specify a callback"
});
}
switch (type) {
case "Point":
return $GP.crs.transform({
sourceCrsId: sourceCrsId,
targetCrsId: targetCrsId,
points: [{
x: coords[0],
y: coords[1]
}]
}, function(ret) {
var points = ret.points.map(xytoa);
callback({
coordinates: points[0],
type: type
});
},
errback);
case "LineString":
case "MultiPoint":
return $GP.crs.transform({
sourceCrsId: sourceCrsId,
targetCrsId: targetCrsId,
points: coords.map(atoxy)
},
function(ret) {
var points = ret.points.map(xytoa);
callback({
coordinates: points,
type: type
});
}, errback);
case "Polygon":
case "MultiLineString":
// capture lengths of subarrays before flattening
var packInfo = pack(coords);
return _transformGeometry(sourceCrsId, targetCrsId, packInfo.packed, "LineString", function(ret) {
packInfo.packed = ret.coordinates;
var coords = unpack(packInfo);
return callback({
coordinates: coords,
type: type
});
});
case "MultiPolygon":
var packInfo1 = pack(coords);
var packInfo2 = pack(packInfo1.packed);
return _transformGeometry(sourceCrsId, targetCrsId, packInfo2.packed, "LineString", function(ret) {
packInfo2.packed = ret.coordinates;
packInfo1.packed = unpack(packInfo2);
var coords = unpack(packInfo1);
return callback({
coordinates: coords,
type: type
});
});
break;
}
}
function transformGeometry(config, callback, errback) {
return _transformGeometry(config.sourceCrsId, config.targetCrsId, config.geometry.coordinates, config.geometry.type, callback, errback);
}
if (window.gjutils && !window.gjutils.transformGeometry) {
window.gjutils.transformGeometry = transformGeometry;
return;
}
var GeoJSONUtils = function() {}
GeoJSONUtils.prototype = {
transformGeometry: transformGeometry
};
window.gjutils = new GeoJSONUtils();
})(window);
|
Comments (0)
You can clone a snippet to your computer for local editing. Learn more.