22
33namespace Grimzy \LaravelMysqlSpatial \Types ;
44
5+ use GeoJson \GeoJson ;
6+ use GeoJson \Geometry \MultiPolygon as GeoJsonMultiPolygon ;
7+ use Grimzy \LaravelMysqlSpatial \Exceptions \InvalidGeoJsonException ;
58use InvalidArgumentException ;
69
710class MultiPolygon extends GeometryCollection
@@ -97,6 +100,32 @@ public function offsetSet($offset, $value)
97100 parent ::offsetSet ($ offset , $ value );
98101 }
99102
103+ public static function fromJson ($ geoJson )
104+ {
105+ if (is_string ($ geoJson )) {
106+ $ geoJson = GeoJson::jsonUnserialize (json_decode ($ geoJson ));
107+ }
108+
109+ if (!is_a ($ geoJson , GeoJsonMultiPolygon::class)) {
110+ throw new InvalidGeoJsonException ('Expected ' .GeoJsonMultiPolygon::class.', got ' .get_class ($ geoJson ));
111+ }
112+
113+ $ set = [];
114+ foreach ($ geoJson ->getCoordinates () as $ polygonCoordinates ) {
115+ $ lineStrings = [];
116+ foreach ($ polygonCoordinates as $ lineStringCoordinates ) {
117+ $ points = [];
118+ foreach ($ lineStringCoordinates as $ lineStringCoordinate ) {
119+ $ points [] = new Point ($ lineStringCoordinate [1 ], $ lineStringCoordinate [0 ]);
120+ }
121+ $ lineStrings [] = new LineString ($ points );
122+ }
123+ $ set [] = new Polygon ($ lineStrings );
124+ }
125+
126+ return new self ($ set );
127+ }
128+
100129 /**
101130 * Convert to GeoJson MultiPolygon that is jsonable to GeoJSON.
102131 *
@@ -109,6 +138,6 @@ public function jsonSerialize()
109138 $ polygons [] = $ polygon ->jsonSerialize ();
110139 }
111140
112- return new \ GeoJson \ Geometry \ MultiPolygon ($ polygons );
141+ return new GeoJsonMultiPolygon ($ polygons );
113142 }
114143}
0 commit comments