Return a (decoded) GeoJSON geometry dictionary corresponding to the given KML node.
540375
def build_geometry(node):
    
    geoms = []
    times = []
    if get1(node, 'MultiGeometry'):
        return build_geometry(get1(node, 'MultiGeometry'))
    if get1(node, 'MultiTrack'):
        return build_geometry(get1(node, 'MultiTrack'))
    if get1(node, 'gx:MultiTrack'):
        return build_geometry(get1(node, 'gx:MultiTrack'))
    for geotype in GEOTYPES:
        geonodes = get(node, geotype)
        if not geonodes:
            continue
        for geonode in geonodes:
            if geotype == 'Point':
                geoms.append({
                  'type': 'Point',
                  'coordinates': coords1(val(get1(
                    geonode, 'coordinates')))
                })
            elif geotype == 'LineString':
                geoms.append({
                  'type': 'LineString',
                  'coordinates': coords(val(get1(
                    geonode, 'coordinates')))
                })
            elif geotype == 'Polygon':
                rings = get(geonode, 'LinearRing')
                coordinates = [coords(val(get1(ring, 'coordinates')))
                  for ring in rings]
                geoms.append({
                  'type': 'Polygon',
                  'coordinates': coordinates,
                })
            elif geotype in ['Track', 'gx:Track']:
                track = gx_coords(geonode)
                geoms.append({
                  'type': 'LineString',
                  'coordinates': track['coordinates'],
                })
                if track['times']:
                    times.append(track['times'])

    return {'geoms': geoms, 'times': times}
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
1167930
def geojsonfeature(source, params=''):
    
    parse = re.search(r'(?P<properties>((\w+)(,\w+)*)?)(:(?P<field>(\w+)?))?(:(?P<srid>(\d+)?))?', params)
    if parse:
        parse = parse.groupdict()
    else:
        parse = {}

    geometry_field = parse.get('field') or 'geom'
    properties = parse.get('properties', '').split(',')
    srid = parse.get('srid') or GEOJSON_DEFAULT_SRID

    if source is None or isinstance(source, string_types):
        return 'null'

    if isinstance(source, (GEOSGeometry, GeometryField)):
        encoder = DjangoGeoJSONEncoder()
        if source.srid != srid:
            source.transform(srid)
        feature = {"type": "Feature", "properties": {}}
        feature['geometry'] = encoder.default(source)
        return json.dumps(feature)

    serializer = Serializer()

    if not hasattr(source, '__iter__'):
        source = [source]

    return serializer.serialize(source, properties=properties,
                                geometry_field=geometry_field, srid=srid)
504217
def from_geojson(cls, filename):
        """"""
        with open(filename) as fd:
            geometry = json.load(fd)

        if 'type' not in geometry:
            raise TypeError("%s is not a valid geojson." % (filename,))

        return cls(to_shape(geometry), WGS84_CRS)
358732
def fromJson(struct, attributes=None):
    ""
    if isinstance(struct, basestring):
        struct = json.loads(struct)
    indicative_attributes = {
        'x': Point,
        'wkid': SpatialReference,
        'paths': Polyline,
        'rings': Polygon,
        'points': Multipoint,
        'xmin': Envelope
    }
    # bbox string
    if isinstance(struct, basestring) and len(struct.split(',')) == 4:
        return Envelope(*map(float, struct.split(',')))
    # Look for telltale attributes in the dict
    if isinstance(struct, dict):
        for key, cls in indicative_attributes.iteritems():
            if key in struct:
                ret = cls.fromJson(dict((str(key), value)
                                   for (key, value) in struct.iteritems()))
                if attributes:
                    ret.attributes = dict((str(key.lower()), val) 
                                           for (key, val)
                                           in attributes.iteritems())
                return ret
    raise ValueError("Unconvertible to geometry")
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")
193535
def _parse_planar_geometry_surface(self, node):
        
        nodes = []
        for key in ["topLeft", "topRight", "bottomRight", "bottomLeft"]:
            nodes.append(geo.Point(getattr(node, key)["lon"],
                                   getattr(node, key)["lat"],
                                   getattr(node, key)["depth"]))
        top_left, top_right, bottom_right, bottom_left = tuple(nodes)
        return geo.PlanarSurface.from_corner_points(
            top_left, top_right, bottom_right, bottom_left)
1234586
def edge_node(name, points):
    
    line = []
    for point in points:
        line.append(point.longitude)
        line.append(point.latitude)
        line.append(point.depth)
    pos = Node('gml:posList', {}, line)
    node = Node(name, nodes=[Node('gml:LineString', nodes=[pos])])
    return node
228385
def to_latlon(geojson, origin_espg=None):
    

    if isinstance(geojson, dict):

        # get epsg code:
        if origin_espg:
            code = origin_espg
        else:
            code = epsg_code(geojson)
        if code:
            origin = Proj(init='epsg:%s' % code)
            wgs84 = Proj(init='epsg:4326')
            wrapped = test_wrap_coordinates(geojson['coordinates'], origin, wgs84)
            new_coords = convert_coordinates(geojson['coordinates'], origin, wgs84, wrapped)
            if new_coords:
                geojson['coordinates'] = new_coords
            try:
                del geojson['crs']
            except KeyError:
                pass

    return geojson
473361
def _node_to_dict(cls, node, json, json_fields):
        
        if json:
            pk_name = node.get_pk_name()
            # jqTree or jsTree format
            result = {'id': getattr(node, pk_name), 'label': node.__repr__()}
            if json_fields:
                result.update(json_fields(node))
        else:
            result = {'node': node}
        return result
100079
def make_node_dict(outer_list, sort="zone"):
    """"""
    raw_dict = {}
    x = 1
    for inner_list in outer_list:
        for node in inner_list:
            raw_dict[x] = node
            x += 1
    if sort == "name":  # sort by provider - name
        srt_dict = OrderedDict(sorted(raw_dict.items(), key=lambda k:
                               (k[1].cloud, k[1].name.lower())))
    else:  # sort by provider - zone - name
        srt_dict = OrderedDict(sorted(raw_dict.items(), key=lambda k:
                               (k[1].cloud, k[1].zone, k[1].name.lower())))
    x = 1
    node_dict = {}
    for i, v in srt_dict.items():
        node_dict[x] = v
        x += 1
    return node_dict
580768
def _decode_geom(ewkb):
    
    # it's already a shapely object
    if hasattr(ewkb, 'geom_type'):
        return ewkb

    from shapely import wkb
    from shapely import wkt
    if ewkb:
        try:
            return wkb.loads(ba.unhexlify(ewkb))
        except Exception:
            try:
                return wkb.loads(ba.unhexlify(ewkb), hex=True)
            except Exception:
                try:
                    return wkb.loads(ewkb, hex=True)
                except Exception:
                    try:
                        return wkb.loads(ewkb)
                    except Exception:
                        try:
                            return wkt.loads(ewkb)
                        except Exception:
                            pass
    return None
174738
def _get_go2pydotnode(self):
        """"""
        go2node = {}
        go2obj = self.gosubdag.go2obj
        get_node = self.pydotnodego.get_node
        for goid in self.get_goids_plt():
            goobj = go2obj[goid]
            node = get_node(goid, goobj)
            go2node[goid] = node
            if goid != goobj.id: # goid is an alias for goobj
                go2node[goobj.id] = node
        return go2node
540199
def to_dict(self):
        
        return {'type': self.__class__.__name__,
                'points': self.points.tolist(),
                'knots': self.knots.tolist(),
                'closed': self.closed}
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
537952
def get_geoms_for_bounds(self, bounds):
        

        params = {'service'      : 'WFS',
                  'request'      : 'GetFeature',
                  'typeName'     : self._feature_name,
                  'outputFormat' : 'json',
                  'version'      : '1.0.0',
                  'bbox'         : ','.join((str(b) for b in wkt.loads(bounds).bounds))}

        raw_geojson_response = requests.get(self._wfs_server, params=params)
        raw_geojson_response.raise_for_status()
        geojson = raw_geojson_response.json()

        return [g['geometry'] for g in geojson['features']]
957718
def to_dict(self) -> Dict:
        
        return {
            "name": self.name,
            "dateCreated": str(self.dateCreated),
            "variables": lmap(
                lambda n: self.export_node(n), self.nodes(data=True)
            ),
            "timeStep": str(self.Δt),
            "edge_data": lmap(export_edge, self.edges(data=True)),
        }