From 2e3700f77a193e4b47b779db8f9f0b1fe0dfc1ea Mon Sep 17 00:00:00 2001 From: Martin Journois Date: Fri, 11 Dec 2015 20:20:55 +0100 Subject: [PATCH] Fix GeoSeries.to_json --- geopandas/geoseries.py | 19 ++++++++++++++++++- tests/test_geoseries.py | 8 ++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/geopandas/geoseries.py b/geopandas/geoseries.py index 3fea310..e0a7ed1 100644 --- a/geopandas/geoseries.py +++ b/geopandas/geoseries.py @@ -6,7 +6,7 @@ from pandas import Series, DataFrame from pandas.core.indexing import _NDFrameIndexer from pandas.util.decorators import cache_readonly import pyproj -from shapely.geometry import box, shape, Polygon, Point +from shapely.geometry import box, mapping, shape, Polygon, Point from shapely.geometry.collection import GeometryCollection from shapely.geometry.base import BaseGeometry from shapely.ops import transform @@ -273,6 +273,23 @@ class GeoSeries(GeoPandasBase, Series): result._invalidate_sindex() return result + def to_json(self, **kwargs): + """ + """ + def geometry_handler(x): + if isinstance(x, BaseGeometry): + return { + 'type': 'Feature', + 'properties': {}, + 'geometry': mapping(x) + } + else: + return x + kwargs.setdefault('default_handler',geometry_handler) + kwargs.setdefault('orient','records') + features = super(GeoSeries,self).to_json(**kwargs) + return '{"type":"FeatureCollection","features":%s}' % features + # # Implement standard operators for GeoSeries # diff --git a/tests/test_geoseries.py b/tests/test_geoseries.py index 91c11f5..700c149 100644 --- a/tests/test_geoseries.py +++ b/tests/test_geoseries.py @@ -1,6 +1,7 @@ from __future__ import absolute_import import os +import json import shutil import tempfile import numpy as np @@ -116,6 +117,13 @@ class TestSeries(unittest.TestCase): self.assertTrue(all(self.g3.geom_equals(s))) # TODO: compare crs + def test_to_json(self): + """Test whether GeoSeries.to_json works and returns an actual json file.""" + s = GeoSeries.from_file(tempfilename) + json_str = s.to_json() + json_dict = json.loads(json_str) + # TODO : verify the output is a valid GeoJSON. + def test_representative_point(self): self.assertTrue(np.alltrue(self.g1.contains(self.g1.representative_point()))) self.assertTrue(np.alltrue(self.g2.contains(self.g2.representative_point())))