073c26ab4fff4c571a18565479ab818dc5148972
[paste/555.git] / arcgis-to-geojson.php
1 <?php
2 /**
3  * Convert a ArcGis web recordset polygon to a geojson polygon feature.
4  *
5  * Validate the generated JSON with http://geojsonlint.com/
6  *
7  * Dependency installation:
8  * $ composer require php-coord/php-coord
9  *
10  * @author Christan Weiske <cweiske@cweiske.de>
11  */
12 require_once __DIR__ . '/vendor/autoload.php';
13
14 function err($msg)
15 {
16     echo $msg . "\n";
17     exit(1);
18 }
19
20 if ($argc < 2) {
21     err("convert.php <esriGeoMetryFile.json>");
22 }
23
24 $file = $argv[1];
25 $data = json_decode(file_get_contents($file));
26
27 if (!isset($data->RecordSet->geometryType)
28     || $data->RecordSet->geometryType != 'esriGeometryPolygon'
29 ) {
30     err('No esriGeometryPolygon');
31 }
32
33 $sRefs = [
34     25833 => ['N', 33]
35 ];
36 $sRef = $data->RecordSet->spatialReference->wkid;
37 if (!isset($sRefs[$sRef])) {
38     err('Unknown spatial reference EPSG ' . $sRef);
39 }
40 list($latZone, $lngZone) = $sRefs[$sRef];
41
42 $geoJson = [
43     'type'       => 'Feature',
44     'title'      => basename($file, '.json'),
45     'properties' => null,
46     'geometry'   => [
47         'type'        => 'Polygon',
48         'coordinates' => [],
49     ],
50 ];
51 foreach ($data->RecordSet->features as $feature) {
52     foreach ($feature->geometry->rings as $ring) {
53         $coords = [];
54         foreach ($ring as $point) {
55             $utm = new \PHPCoord\UTMRef(
56                 $point[0], $point[1], 0, $latZone, $lngZone
57             );
58             $ll = $utm->toLatLng();
59             $coords[] = [$ll->getLng(), $ll->getLat()];
60         }
61
62         $geoJson['geometry']['coordinates'][] = $coords;
63     }
64 }
65
66 echo json_encode($geoJson, JSON_PRETTY_PRINT) . "\n";
67
68 /*
69 $UTMRef = new \PHPCoord\UTMRef(350531.8, 5689109.2, 0, 'N', 33);
70 $LatLng = $UTMRef->toLatLng();
71
72 echo (string) $UTMRef . "\n";
73 echo (string) $LatLng . "\n";
74 */
75 ?>