Helper method to get geometries within a certain bounds (as WKT).

        Returns GeoJSON (loaded as a list of python dictionaries).
548638
def get_geoms_for_bounds(self, bounds):
        
        poly = ogr.CreateGeometryFromWkt(bounds)
        self._layer.SetSpatialFilter(poly)
        poly.Destroy()

        return [json.loads(e.GetGeometryRef().ExportToJson()) for e in self._layer]
19068
def get_dimension(geometry):
    """"""
    coordinates = geometry["coordinates"]
    type_ = geometry["type"]
    if type_ in ('Point',):
        return len(coordinates)
    elif type_ in ('LineString', 'MultiPoint'):
        return len(coordinates[0])
    elif type_ in ('Polygon', 'MultiLineString'):
        return len(coordinates[0][0])
    elif type_ in ('MultiPolygon',):
        return len(coordinates[0][0][0])
    else:
        raise ValueError("Invalid type '{}'".format(type_))
827612
def filter_geometry(queryset, **filters):
    
    fieldname = geo_field(queryset).name
    query = {'%s__%s' % (fieldname, k): v for k, v in filters.items()}
    return queryset.filter(**query)
519315
def _from_json(json_data):
        
        if len(json_data) >= 6:
            return BoundingBox(
                        Coordinate(_parse_float(json_data[0]),
                                   _parse_float(json_data[1]),
                                   _parse_float(json_data[2])),
                        Coordinate(_parse_float(json_data[3]),
                                   _parse_float(json_data[4]),
                                   _parse_float(json_data[5])))
        else:
            raise USGSException("The bounding box information was incomplete.")
202
def get_bounds(self):
        

        size = self.get_size()
        top_left = self.get_position([0, 0])

        # t, r, b, l
        bounds = [top_left[1], top_left[0] + size[0], top_left[1] + size[1], top_left[0]]
        return bounds
700963
def fromGeoJson(struct, attributes=None):
    ""
    if isinstance(struct, basestring):
        struct = json.loads(struct)
    type_map = {
        'Point': Point,
        'MultiLineString': Polyline,
        'LineString': Polyline,
        'Polygon': Polygon,
        'MultiPolygon': Polygon,
        'MultiPoint': Multipoint,
        'Box': Envelope
    }
    if struct['type'] == "Feature":
        return fromGeoJson(struct, struct.get('properties', None))
    elif struct['type'] == "FeatureCollection":
        sr = None
        if 'crs' in struct:
            sr = SpatialReference(struct['crs']['properties']['code'])
            members = map(fromGeoJson, struct['members'])
            for member in members:
                member.spatialReference = sr
            return members
        else:
            return map(fromGeoJson, struct['members'])
    elif struct['type'] in type_map and hasattr(type_map[struct['type']], 
                                              'fromGeoJson'):
        instances = type_map[struct['type']].fromGeoJson(struct)
        i = []
        assert instances is not None, "GeoJson conversion returned a Null geom"
        for instance in instances:
            if 'properties' in struct:
                instance.attributes = struct['properties'].copy()
                if '@esri.sr' in instance.attributes:
                    instance.spatialReference = SpatialReference.fromJson(
                                               instance.attributes['@esri.sr'])
                    del instance.attributes['@esri.sr']
            if attributes:
                if not hasattr(instance, 'attributes'):
                    instance.attributes = {}
                for k, v in attributes.iteritems():
                    instance.attributes[k] = v
            i.append(instance)
        if i:
            if len(i) > 1:
                return i
            return i[0]
    raise ValueError("Unconvertible to geometry")
644878
def _get_bounds(mapper, values):
        

        array = np.array([mapper.get(x) for x in values])
        return array[:, 0], array[:, 1]
966569
def get_bounding_box(self):
        """"""
        from pyproj import Geod
        geod = Geod(ellps='WGS84')
        dataset_group = DATASET_KEYS[self.datasets[0]]
        idx = 0
        lons_ring = None
        lats_ring = None
        while True:
            path = 'Data_Products/{dataset_group}/{dataset_group}_Gran_{idx}/attr/'
            prefix = path.format(dataset_group=dataset_group, idx=idx)
            try:
                lats = self.file_content[prefix + 'G-Ring_Latitude']
                lons = self.file_content[prefix + 'G-Ring_Longitude']
                if lons_ring is None:
                    lons_ring = lons
                    lats_ring = lats
                else:
                    prev_lon = lons_ring[0]
                    prev_lat = lats_ring[0]
                    dists = list(geod.inv(lon, lat, prev_lon, prev_lat)[2] for lon, lat in zip(lons, lats))
                    first_idx = np.argmin(dists)
                    if first_idx == 2 and len(lons) == 8:
                        lons_ring = np.hstack((lons[:3], lons_ring[:-2], lons[4:]))
                        lats_ring = np.hstack((lats[:3], lats_ring[:-2], lats[4:]))
                    else:
                        raise NotImplementedError("Don't know how to handle G-Rings of length %d" % len(lons))

            except KeyError:
                break
            idx += 1

        return lons_ring, lats_ring
364217
private static void parseBounds(JSONObject modelJSON,
                                    Shape current) throws JSONException {
        if (modelJSON.has("bounds")) {
            JSONObject boundsObject = modelJSON.getJSONObject("bounds");
            current.setBounds(new Bounds(new Point(boundsObject.getJSONObject("lowerRight").getDouble("x"),
                                                   boundsObject.getJSONObject("lowerRight").getDouble(
                                                           "y")),
                                         new Point(boundsObject.getJSONObject("upperLeft").getDouble("x"),
                                                   boundsObject.getJSONObject("upperLeft").getDouble("y"))));
        }
    }
414381
def get_widths(self, estimation):
        
        widths = estimation[self.map_offset[1]:self.map_offset[2]]\
            .reshape(self.K, 1)
        return widths
201699
def points(self):
        
        feature = geojson.Feature(geometry=self._geom)
        points_coords = list(geojson.utils.coords(feature))
        return [Point(p[0], p[1]) for p in points_coords]
912014
def get(self):
        
        return {k:v for k,v in list(self.options.items()) if k in self._allowed_axes}
1232258
def nodes_geometry(self):
        

        nodes = np.array([
            n for n in self.transforms.nodes()
            if 'geometry' in self.transforms.node[n]
        ])

        return nodes
493954
def prepare_geojson(geojson):
    
    # TODO CW orientation.
    geojson = deepcopy(geojson)

    if geojson["type"] == "Feature":
        geojson = geojson["geometry"]
        if hasattr(geojson, 'properties'):
            del geojson['properties']

    if geojson["type"] == "FeatureCollection":
        geojson["type"] = "GeometryCollection"
        geojson["geometries"] = [
            feature["geometry"] for feature in geojson["features"]
        ]
        del geojson["features"]

    return geojson
50222
def get_geometry(self):
        
        return (self.thet0, self.thet, self.phi0, self.phi, self.alpha, 
            self.beta)
1301951
def geometry(self):
        """"""
        if arcpyFound:
            if self._geom is None:
                if 'feature' in self._dict:
                    self._geom = arcpy.AsShape(self._dict['feature']['geometry'], esri_json=True)
                elif 'geometry' in self._dict:
                    self._geom = arcpy.AsShape(self._dict['geometry'], esri_json=True)
            return self._geom
        return None
1145166
def geo(self):
        """"""
        import geopandas as gpd
        from shapely.geometry.polygon import BaseGeometry
        from shapely.wkt import loads

        gdf = gpd.GeoDataFrame(self)

        first = next(gdf.iterrows())[1].geometry

        if isinstance(first, str):
            # We have a GeoDataframe, but the geometry column is still strings, so
            # it must be converted
            shapes = [ loads(row['geometry']) for i, row in gdf.iterrows()]

        elif not isinstance(first, BaseGeometry):
            # If we are reading a metatab package, the geometry column's type should be
            # 'geometry' which will give the geometry values class type of
            # rowpipe.valuetype.geo.ShapeValue. However, there are other
            # types of objects that have a 'shape' property.

            shapes = [row['geometry'].shape for i, row in gdf.iterrows()]

        else:
            shapes = gdf['geometry']

        gdf['geometry'] = gpd.GeoSeries(shapes)
        gdf.set_geometry('geometry')
        return gdf