压缩geojson(php版)
GeoJSON是⼀种对各种地理数据结构进⾏编 码的格式,可以表⽰⼏何、特征或者特征集合。
点 {"type":"Point","coordinates":[6,10]}
线 {"type":"LineString","coordinates":[[44, 4],[11, 44],[33, 25]]}
⾯ {"type":"Polygon","coordinates":[[[1, 1],[2, 2],[3, 3],[4, 4],[5, 5],[1, 1]],[[11, 11],[2, 13],[34, 43],[34, 42],[52, 52],[11, 11]]]}
多点 {"type":"MultiPoint","coordinates":[[44, 4],[11, 44],[33, 25]]}
多线 {"type":"MultiLineString","coordinates":[[[3, 4],[10, 50],[20, 25]],[[-5, -8],[-10, -8],[-15, -4]]}
多⾯ {"type":"MultiPolygon","coordinates":[[[3, 4],[10, 50],[20, 25]],[[-5, -8],[-10, -8],[-15, -4]]]}
⼏何集合 {"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[4,6]},}, {"type":"Feature","geometry":{"type":"LineString","coordinates":[[[4,6],[7,10]]}]}
数据格式:
geoJson: {"type":"MultiPolygon","coordinates":[[[[1,1],[5,1],[5,5],[1,5],[1,1]],[[2,2],[2,3],[3,3],[3,2],[2,2]]],[[[6,3],[9,2],[9,4], [6,3]]]]}
原⽂章是js版,现在写⼀个php版,(根据js版转换)
/**
* 压缩coordinate
*/
function encodePolygon($coordinate, &$encodeOffsets) {
$result = '';
$prevX = quantize($coordinate[0][0]);
$prevY = quantize($coordinate[0][1]);
$encodeOffsets[0] = $prevX;
$encodeOffsets[1] = $prevY;
for ($i = 0; $i < count($coordinate); $i++) {
$point = $coordinate[$i];
$result .= encode($point[0], $prevX);
$result .= encode($point[1], $prevY);
$prevX = quantize($point[0]);
$prevY = quantize($point[1]);
}
}
return $result;
}
function encode($val, $prev) {
$val = quantize($val);
$val = $val - $prev;
if ((($val << 1) ^ ($val >> 15)) + 64 === 8232) {
$val--;
}
$val = ($val << 1) ^ ($val >> 15);
return chr($val + 64);
}
function quantize($val) {
return ceil($val * 1024);
}
//测试写的编码⽅法
function encodeCoordinate(&$json){
$feature = &$json;
$coordinates = &$feature->geometry->coordinates;
$encodeOffsets = &$feature->geometry->encodeOffsets;
for ($c = 0; $c < count($coordinates); $c++) {
$coordinate = &$coordinates[$c];
if ($feature->geometry->type === 'Polygon') {
$coordinates[$c] = encodePolygon(
$coordinate,
$encodeOffsets[$c]
);
} else if ($feature->geometry->type === 'MultiPolygon') {
for ($c2 = 0; $c2 < count($coordinate); $c2++) {
$polygon = $coordinate[$c2];
$coordinate[$c2] = encodePolygon(
$polygon,
$encodeOffsets[$c][$c2]
);
}
}
}
return $feature;
}
补充:
数据格式:
wkt: MULTIPOLYGON(((1 1,5 1,5 5,1 5,1 1),(2 2,2 3,3 3,3 2,2 2)),((6 3,9 2,9 4,6 3)))
WKT(Well-known text)是⼀种⽂本标记语⾔,⽤于表⽰⽮量⼏何对象、空间参照系统及空间参照系统之间的转换。它的⼆进制表⽰⽅式,亦即WKB(well-known-binary)则胜于在传输和在数据库中存储相同的信息。
点 POINT(6 10)
线 LINESTRING(44 4,11 44,33 25)
⾯ POLYGON((1 1,2 2,3 3,4 4,5 5,1 1),(11 11,2 13,34 43,34 42,52 52,11 11))
多点 MULTIPOINT(44 4,11 44,33 25)
多线 MULTILINESTRING((3 4,10 50,20 25),(-5 -8,-10 -8,-15 -4))
phpjson格式化输出
多⾯ MULTIPOLYGON(((1 1,5 1,5 5,1 5,1 1),(2 2,2 3,3 3,3 2,2 2)),((6 3,9 2,9 4,6 3)))
⼏何集合 GEOMETRYCOLLECTION(POINT(4 6),LINESTRING(4 6,7 10))