PHP: convert arcgis recordset to geojson

raw

arcgis-to-geojson.php

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
<?php
/**
 * Convert a ArcGis web recordset polygon to a geojson polygon feature.
 *
 * Validate the generated JSON with http://geojsonlint.com/
 *
 * Dependency installation:
 * $ composer require php-coord/php-coord
 *
 * @author Christan Weiske <cweiske@cweiske.de>
 */
require_once __DIR__ . '/vendor/autoload.php';
 
function err($msg)
{
    echo $msg . "\n";
    exit(1);
}
 
if ($argc < 2) {
    err("convert.php <esriGeoMetryFile.json>");
}
 
$file = $argv[1];
$data = json_decode(file_get_contents($file));
 
if (!isset($data->RecordSet->geometryType)
    || $data->RecordSet->geometryType != 'esriGeometryPolygon'
) {
    err('No esriGeometryPolygon');
}
 
$sRefs = [
    25833 => ['N', 33]
];
$sRef = $data->RecordSet->spatialReference->wkid;
if (!isset($sRefs[$sRef])) {
    err('Unknown spatial reference EPSG ' . $sRef);
}
list($latZone, $lngZone) = $sRefs[$sRef];
 
$geoJson = [
    'type'       => 'Feature',
    'title'      => basename($file, '.json'),
    'properties' => null,
    'geometry'   => [
        'type'        => 'Polygon',
        'coordinates' => [],
    ],
];
foreach ($data->RecordSet->features as $feature) {
    foreach ($feature->geometry->rings as $ring) {
        $coords = [];
        foreach ($ring as $point) {
            $utm = new \PHPCoord\UTMRef(
                $point[0], $point[1], 0, $latZone, $lngZone
            );
            $ll = $utm->toLatLng();
            $coords[] = [$ll->getLng(), $ll->getLat()];
        }
 
        $geoJson['geometry']['coordinates'][] = $coords;
    }
}
 
echo json_encode($geoJson, JSON_PRETTY_PRINT) . "\n";
?>
 
raw

combine-geojson.php

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
<?php
/**
 * Takes several geojson files and combines them into a single one.
 *
 * @author Christian Weiske <cweiske@cweiske.de>
 */
function err($msg)
{
    echo $msg . "\n";
    exit(1);
}
 
if ($argc < 2) {
    err("combine-geojson.php <files>");
}
 
$files = $argv;
array_shift($files);
 
$combined = [
    'type'     => 'FeatureCollection',
    'features' => [],
];
 
foreach ($files as $file) {
    $combined['features'][] = json_decode(file_get_contents($file));
}
 
echo json_encode($combined, JSON_PRETTY_PRINT) . "\n";
?>
 
Christian Weiske Christian Weiske
owner

History