desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns the WKT representation of the given geometry.'
def write(self, geom):
return wkt_writer_write(self.ptr, geom.ptr)
'Returns the WKB representation of the given geometry.'
def write(self, geom):
return memoryview(wkb_writer_write(self.ptr, geom.ptr, byref(c_size_t())))
'Returns the HEXEWKB representation of the given geometry.'
def write_hex(self, geom):
return wkb_writer_write_hex(self.ptr, geom.ptr, byref(c_size_t()))
'Initializes a Geometry Collection from a sequence of Geometry objects.'
def __init__(self, *args, **kwargs):
if (not args): raise TypeError(('Must provide at least one Geometry to initialize %s.' % self.__class__.__name__)) if (len(args) == 1): if isinstance(args[0], (tuple, list)): init_geoms = args[0] else: init_geoms = args else: init_geoms = args self._check_allowed(init_geoms) collection = self._create_collection(len(init_geoms), iter(init_geoms)) super(GeometryCollection, self).__init__(collection, **kwargs)
'Iterates over each Geometry in the Collection.'
def __iter__(self):
for i in xrange(len(self)): (yield self[i])
'Returns the number of geometries in this Collection.'
def __len__(self):
return self.num_geom
'Returns the Geometry from this Collection at the given index (0-based).'
def _get_single_external(self, index):
return GEOSGeometry(capi.geom_clone(self._get_single_internal(index)), srid=self.srid)
'Create a new collection, and destroy the contents of the previous pointer.'
def _set_list(self, length, items):
prev_ptr = self.ptr srid = self.srid self.ptr = self._create_collection(length, items) if srid: self.srid = srid capi.destroy_geom(prev_ptr)
'Returns the KML for this Geometry Collection.'
@property def kml(self):
return ('<MultiGeometry>%s</MultiGeometry>' % ''.join([g.kml for g in self]))
'Returns a tuple of all the coordinates in this Geometry Collection'
@property def tuple(self):
return tuple([g.tuple for g in self])
'Returns a LineString representing the line merge of this MultiLineString.'
@property def merged(self):
return self._topology(capi.geos_linemerge(self.ptr))
'Returns a cascaded union of this MultiPolygon.'
@property def cascaded_union(self):
if GEOS_PREPARE: return GEOSGeometry(capi.geos_cascaded_union(self.ptr), self.srid) else: raise GEOSException('The cascaded union operation requires GEOS 3.1+.')
'The Point object may be initialized with either a tuple, or individual parameters. For Example: >>> p = Point((5, 23)) # 2D point, passed in as a tuple >>> p = Point(5, 23, 8) # 3D point, passed in with individual parameters'
def __init__(self, x, y=None, z=None, srid=None):
if isinstance(x, (tuple, list)): ndim = len(x) coords = x elif (isinstance(x, (six.integer_types + (float,))) and isinstance(y, (six.integer_types + (float,)))): if isinstance(z, (six.integer_types + (float,))): ndim = 3 coords = [x, y, z] else: ndim = 2 coords = [x, y] else: raise TypeError('Invalid parameters given for Point initialization.') point = self._create_point(ndim, coords) super(Point, self).__init__(point, srid=srid)
'Create a coordinate sequence, set X, Y, [Z], and create point'
def _create_point(self, ndim, coords):
if ((ndim < 2) or (ndim > 3)): raise TypeError(('Invalid point dimension: %s' % str(ndim))) cs = capi.create_cs(c_uint(1), c_uint(ndim)) i = iter(coords) capi.cs_setx(cs, 0, next(i)) capi.cs_sety(cs, 0, next(i)) if (ndim == 3): capi.cs_setz(cs, 0, next(i)) return capi.create_point(cs)
'Allows iteration over coordinates of this Point.'
def __iter__(self):
for i in xrange(len(self)): (yield self[i])
'Returns the number of dimensions for this Point (either 0, 2 or 3).'
def __len__(self):
if self.empty: return 0 if self.hasz: return 3 else: return 2
'Returns the X component of the Point.'
def get_x(self):
return self._cs.getOrdinate(0, 0)
'Sets the X component of the Point.'
def set_x(self, value):
self._cs.setOrdinate(0, 0, value)
'Returns the Y component of the Point.'
def get_y(self):
return self._cs.getOrdinate(1, 0)
'Sets the Y component of the Point.'
def set_y(self, value):
self._cs.setOrdinate(1, 0, value)
'Returns the Z component of the Point.'
def get_z(self):
if self.hasz: return self._cs.getOrdinate(2, 0) else: return None
'Sets the Z component of the Point.'
def set_z(self, value):
if self.hasz: self._cs.setOrdinate(2, 0, value) else: raise GEOSException('Cannot set Z on 2D Point.')
'Returns a tuple of the point.'
def get_coords(self):
return self._cs.tuple
'Sets the coordinates of the point with the given tuple.'
def set_coords(self, tup):
self._cs[0] = tup
'Get the item(s) at the specified index/slice.'
def __getitem__(self, index):
if isinstance(index, slice): return [self._get_single_external(i) for i in xrange(*index.indices(len(self)))] else: index = self._checkindex(index) return self._get_single_external(index)
'Delete the item(s) at the specified index/slice.'
def __delitem__(self, index):
if (not isinstance(index, (six.integer_types + (slice,)))): raise TypeError(('%s is not a legal index' % index)) origLen = len(self) if isinstance(index, six.integer_types): index = self._checkindex(index) indexRange = [index] else: indexRange = range(*index.indices(origLen)) newLen = (origLen - len(indexRange)) newItems = (self._get_single_internal(i) for i in xrange(origLen) if (i not in indexRange)) self._rebuild(newLen, newItems)
'Set the item(s) at the specified index/slice.'
def __setitem__(self, index, val):
if isinstance(index, slice): self._set_slice(index, val) else: index = self._checkindex(index) self._check_allowed((val,)) self._set_single(index, val)
'Iterate over the items in the list'
def __iter__(self):
for i in xrange(len(self)): (yield self[i])
'add another list-like object'
def __add__(self, other):
return self.__class__((list(self) + list(other)))
'add to another list-like object'
def __radd__(self, other):
return other.__class__((list(other) + list(self)))
'add another list-like object to self'
def __iadd__(self, other):
self.extend(list(other)) return self
'multiply'
def __mul__(self, n):
return self.__class__((list(self) * n))
'multiply'
def __rmul__(self, n):
return self.__class__((list(self) * n))
'multiply'
def __imul__(self, n):
if (n <= 0): del self[:] else: cache = list(self) for i in range((n - 1)): self.extend(cache) return self
'Standard list count method'
def count(self, val):
count = 0 for i in self: if (val == i): count += 1 return count
'Standard list index method'
def index(self, val):
for i in xrange(0, len(self)): if (self[i] == val): return i raise ValueError(('%s not found in object' % str(val)))
'Standard list append method'
def append(self, val):
self[len(self):] = [val]
'Standard list extend method'
def extend(self, vals):
self[len(self):] = vals
'Standard list insert method'
def insert(self, index, val):
if (not isinstance(index, six.integer_types)): raise TypeError(('%s is not a legal index' % index)) self[index:index] = [val]
'Standard list pop method'
def pop(self, index=(-1)):
result = self[index] del self[index] return result
'Standard list remove method'
def remove(self, val):
del self[self.index(val)]
'Standard list reverse method'
def reverse(self):
self[:] = self[(-1)::(-1)]
'Standard list sort method'
def sort(self, cmp=None, key=None, reverse=False):
if key: temp = [(key(v), v) for v in self] temp.sort(key=(lambda x: x[0]), reverse=reverse) self[:] = [v[1] for v in temp] else: temp = list(self) if (cmp is not None): temp.sort(cmp=cmp, reverse=reverse) else: temp.sort(reverse=reverse) self[:] = temp
'Assign values to a slice of the object'
def _set_slice(self, index, values):
try: iter(values) except TypeError: raise TypeError('can only assign an iterable to a slice') self._check_allowed(values) origLen = len(self) valueList = list(values) (start, stop, step) = index.indices(origLen) if (index.step is None): self._assign_simple_slice(start, stop, valueList) else: self._assign_extended_slice(start, stop, step, valueList)
'Assign an extended slice by rebuilding entire list'
def _assign_extended_slice_rebuild(self, start, stop, step, valueList):
indexList = range(start, stop, step) if (len(valueList) != len(indexList)): raise ValueError(('attempt to assign sequence of size %d to extended slice of size %d' % (len(valueList), len(indexList)))) newLen = len(self) newVals = dict(zip(indexList, valueList)) def newItems(): for i in xrange(newLen): if (i in newVals): (yield newVals[i]) else: (yield self._get_single_internal(i)) self._rebuild(newLen, newItems())
'Assign an extended slice by re-assigning individual items'
def _assign_extended_slice(self, start, stop, step, valueList):
indexList = range(start, stop, step) if (len(valueList) != len(indexList)): raise ValueError(('attempt to assign sequence of size %d to extended slice of size %d' % (len(valueList), len(indexList)))) for (i, val) in zip(indexList, valueList): self._set_single(i, val)
'Assign a simple slice; Can assign slice of any length'
def _assign_simple_slice(self, start, stop, valueList):
origLen = len(self) stop = max(start, stop) newLen = (((origLen - stop) + start) + len(valueList)) def newItems(): for i in xrange((origLen + 1)): if (i == start): for val in valueList: (yield val) if (i < origLen): if ((i < start) or (i >= stop)): (yield self._get_single_internal(i)) self._rebuild(newLen, newItems())
'Return the unit value and the default units specified from the given keyword arguments dictionary.'
def default_units(self, kwargs):
val = 0.0 default_unit = self.STANDARD_UNIT for (unit, value) in six.iteritems(kwargs): if (not isinstance(value, float)): value = float(value) if (unit in self.UNITS): val += (self.UNITS[unit] * value) default_unit = unit elif (unit in self.ALIAS): u = self.ALIAS[unit] val += (self.UNITS[u] * value) default_unit = u else: lower = unit.lower() if (lower in self.UNITS): val += (self.UNITS[lower] * value) default_unit = lower elif (lower in self.LALIAS): u = self.LALIAS[lower] val += (self.UNITS[u] * value) default_unit = u else: raise AttributeError(('Unknown unit type: %s' % unit)) return (val, default_unit)
'Retrieves the unit attribute name for the given unit string. For example, if the given unit string is \'metre\', \'m\' would be returned. An exception is raised if an attribute cannot be found.'
@classmethod def unit_attname(cls, unit_str):
lower = unit_str.lower() if (unit_str in cls.UNITS): return unit_str elif (lower in cls.UNITS): return lower elif (lower in cls.LALIAS): return cls.LALIAS[lower] else: raise Exception(('Could not find a unit keyword associated with "%s"' % unit_str))
'Initializes the Google Zoom object.'
def __init__(self, num_zoom=19, tilesize=256):
self._tilesize = tilesize self._nzoom = num_zoom self._degpp = [] self._radpp = [] self._npix = [] z = tilesize for i in xrange(num_zoom): self._degpp.append((z / 360.0)) self._radpp.append((z / (2 * pi))) self._npix.append((z / 2)) z *= 2
'Returns the number of zoom levels.'
def __len__(self):
return self._nzoom
'Unpacks longitude, latitude from GEOS Points and 2-tuples.'
def get_lon_lat(self, lonlat):
if isinstance(lonlat, Point): (lon, lat) = lonlat.coords else: (lon, lat) = lonlat return (lon, lat)
'Converts a longitude, latitude coordinate pair for the given zoom level.'
def lonlat_to_pixel(self, lonlat, zoom):
(lon, lat) = self.get_lon_lat(lonlat) npix = self._npix[zoom] px_x = round((npix + (lon * self._degpp[zoom]))) fac = min(max(sin((DTOR * lat)), (-0.9999)), 0.9999) px_y = round((npix + ((0.5 * log(((1 + fac) / (1 - fac)))) * ((-1.0) * self._radpp[zoom])))) return (px_x, px_y)
'Converts a pixel to a longitude, latitude pair at the given zoom level.'
def pixel_to_lonlat(self, px, zoom):
if (len(px) != 2): raise TypeError('Pixel should be a sequence of two elements.') npix = self._npix[zoom] lon = ((px[0] - npix) / self._degpp[zoom]) lat = (RTOD * ((2 * atan(exp(((px[1] - npix) / ((-1.0) * self._radpp[zoom]))))) - (0.5 * pi))) return (lon, lat)
'Returns a Polygon corresponding to the region represented by a fictional Google Tile for the given longitude/latitude pair and zoom level. This tile is used to determine the size of a tile at the given point.'
def tile(self, lonlat, zoom):
delta = (self._tilesize / 2) px = self.lonlat_to_pixel(lonlat, zoom) ll = self.pixel_to_lonlat(((px[0] - delta), (px[1] - delta)), zoom) ur = self.pixel_to_lonlat(((px[0] + delta), (px[1] + delta)), zoom) return Polygon(LinearRing(ll, (ll[0], ur[1]), ur, (ur[0], ll[1]), ll), srid=4326)
'Returns the optimal Zoom level for the given geometry.'
def get_zoom(self, geom):
if ((not isinstance(geom, GEOSGeometry)) or (geom.srid != 4326)): raise TypeError('get_zoom() expects a GEOS Geometry with an SRID of 4326.') env = geom.envelope (env_w, env_h) = self.get_width_height(env.extent) center = env.centroid for z in xrange(self._nzoom): (tile_w, tile_h) = self.get_width_height(self.tile(center, z).extent) if ((env_w > tile_w) or (env_h > tile_h)): if (z == 0): raise GoogleMapException('Geometry width and height should not exceed that of the Earth.') return (z - 1) return (self._nzoom - 1)
'Returns the width and height for the given extent.'
def get_width_height(self, extent):
ll = Point(extent[:2]) ul = Point(extent[0], extent[3]) ur = Point(extent[2:]) height = ll.distance(ul) width = ul.distance(ur) return (width, height)
'Initializes a GEvent object. Parameters: event: string for the event, such as \'click\'. The event must be a valid event for the object in the Google Maps API. There is no validation of the event type within Django. action: string containing a Javascript function, such as \'function() { location.href = "newurl";}\' The string must be a valid Javascript function. Again there is no validation fo the function within Django.'
def __init__(self, event, action):
self.event = event self.action = action
'Returns the parameter part of a GEvent.'
def __str__(self):
return mark_safe(('"%s", %s' % (self.event, self.action)))
'Generates a JavaScript array of GLatLng objects for the given coordinates.'
def latlng_from_coords(self, coords):
return ('[%s]' % ','.join([('new GLatLng(%s,%s)' % (y, x)) for (x, y) in coords]))
'Attaches a GEvent to the overlay object.'
def add_event(self, event):
self.events.append(event)
'The string representation is the JavaScript API call.'
def __str__(self):
return mark_safe(('%s(%s)' % (self.__class__.__name__, self.js_params)))
'The GPolygon object initializes on a GEOS Polygon or a parameter that may be instantiated into GEOS Polygon. Please note that this will not depict a Polygon\'s internal rings. Keyword Options: stroke_color: The color of the polygon outline. Defaults to \'#0000ff\' (blue). stroke_weight: The width of the polygon outline, in pixels. Defaults to 2. stroke_opacity: The opacity of the polygon outline, between 0 and 1. Defaults to 1. fill_color: The color of the polygon fill. Defaults to \'#0000ff\' (blue). fill_opacity: The opacity of the polygon fill. Defaults to 0.4.'
def __init__(self, poly, stroke_color='#0000ff', stroke_weight=2, stroke_opacity=1, fill_color='#0000ff', fill_opacity=0.4):
if isinstance(poly, six.string_types): poly = fromstr(poly) if isinstance(poly, (tuple, list)): poly = Polygon(poly) if (not isinstance(poly, Polygon)): raise TypeError('GPolygon may only initialize on GEOS Polygons.') self.envelope = poly.envelope self.points = self.latlng_from_coords(poly.shell.coords) (self.stroke_color, self.stroke_opacity, self.stroke_weight) = (stroke_color, stroke_opacity, stroke_weight) (self.fill_color, self.fill_opacity) = (fill_color, fill_opacity) super(GPolygon, self).__init__()
'The GPolyline object may be initialized on GEOS LineStirng, LinearRing, and Polygon objects (internal rings not supported) or a parameter that may instantiated into one of the above geometries. Keyword Options: color: The color to use for the polyline. Defaults to \'#0000ff\' (blue). weight: The width of the polyline, in pixels. Defaults to 2. opacity: The opacity of the polyline, between 0 and 1. Defaults to 1.'
def __init__(self, geom, color='#0000ff', weight=2, opacity=1):
if isinstance(geom, six.string_types): geom = fromstr(geom) if isinstance(geom, (tuple, list)): geom = Polygon(geom) if isinstance(geom, (LineString, LinearRing)): self.latlngs = self.latlng_from_coords(geom.coords) elif isinstance(geom, Polygon): self.latlngs = self.latlng_from_coords(geom.shell.coords) else: raise TypeError('GPolyline may only initialize on GEOS LineString, LinearRing, and/or Polygon geometries.') self.envelope = geom.envelope (self.color, self.weight, self.opacity) = (color, weight, opacity) super(GPolyline, self).__init__()
'The GMarker object may initialize on GEOS Points or a parameter that may be instantiated into a GEOS point. Keyword options map to GMarkerOptions -- so far only the title option is supported. Keyword Options: title: Title option for GMarker, will be displayed as a tooltip. draggable: Draggable option for GMarker, disabled by default.'
def __init__(self, geom, title=None, draggable=False, icon=None):
if isinstance(geom, six.string_types): geom = fromstr(geom) if isinstance(geom, (tuple, list)): geom = Point(geom) if isinstance(geom, Point): self.latlng = self.latlng_from_coords(geom.coords) else: raise TypeError('GMarker may only initialize on GEOS Point geometry.') self.envelope = geom.envelope self.title = title self.draggable = draggable self.icon = icon super(GMarker, self).__init__()
'Generates the JavaScript necessary for displaying this Google Map.'
def render(self):
params = {'calc_zoom': self.calc_zoom, 'center': self.center, 'dom_id': self.dom_id, 'js_module': self.js_module, 'kml_urls': self.kml_urls, 'zoom': self.zoom, 'polygons': self.polygons, 'polylines': self.polylines, 'icons': self.icons, 'markers': self.markers} params.update(self.extra_context) return render_to_string(self.template, params)
'Returns HTML body tag for loading and unloading Google Maps javascript.'
@property def body(self):
return format_html('<body {0} {1}>', self.onload, self.onunload)
'Returns the `onload` HTML <body> attribute.'
@property def onload(self):
return format_html('onload="{0}.{1}_load()"', self.js_module, self.dom_id)
'Returns the <script> tag for the Google Maps API javascript.'
@property def api_script(self):
return format_html('<script src="{0}{1}" type="text/javascript"></script>', self.api_url, self.key)
'Returns only the generated Google Maps JavaScript (no <script> tags).'
@property def js(self):
return self.render()
'Returns all <script></script> tags required with Google Maps JavaScript.'
@property def scripts(self):
return format_html('%s\n <script type="text/javascript">\n//<![CDATA[\n%s//]]>\n </script>', self.api_script, mark_safe(self.js))
'Returns additional CSS styling needed for Google Maps on IE.'
@property def style(self):
return format_html('<style type="text/css">{0}</style>', self.vml_css)
'Returns XHTML information needed for IE VML overlays.'
@property def xhtml(self):
return format_html('<html xmlns="http://www.w3.org/1999/xhtml" {0}>', self.xmlns)
'Returns a sequence of GIcon objects in this map.'
@property def icons(self):
return set([marker.icon for marker in self.markers if marker.icon])
'A class for generating sets of Google Maps that will be shown on the same page together. Example: gmapset = GoogleMapSet( GoogleMap( ... ), GoogleMap( ... ) ) gmapset = GoogleMapSet( [ gmap1, gmap2] )'
def __init__(self, *args, **kwargs):
template = kwargs.pop('template', 'gis/google/google-multi.js') self.map_template = kwargs.pop('map_template', 'gis/google/google-single.js') super(GoogleMapSet, self).__init__(**kwargs) self.template = template if isinstance(args[0], (tuple, list)): self.maps = args[0] else: self.maps = args self.dom_ids = [('map%d' % i) for i in xrange(len(self.maps))]
'Returns JavaScript containing all of the loading routines for each map in this set.'
def load_map_js(self):
result = [] for (dom_id, gmap) in zip(self.dom_ids, self.maps): tmp = (gmap.template, gmap.dom_id) gmap.template = self.map_template gmap.dom_id = dom_id result.append(gmap.js) (gmap.template, gmap.dom_id) = tmp return mark_safe(''.join(result))
'Generates the JavaScript for the collection of Google Maps in this set.'
def render(self):
params = {'js_module': self.js_module, 'dom_ids': self.dom_ids, 'load_map_js': self.load_map_js(), 'icons': self.icons} params.update(self.extra_context) return render_to_string(self.template, params)
'Returns the `onload` HTML <body> attribute.'
@property def onload(self):
return mark_safe(('onload="%s.load()"' % self.js_module))
'Returns a sequence of all icons in each map of the set.'
@property def icons(self):
icons = set() for map in self.maps: icons |= map.icons return icons
'Goes through the given sources and returns a 3-tuple of the application label, module name, and field name of every GeometryField encountered in the sources. If no sources are provided, then all models.'
def _build_kml_sources(self, sources):
kml_sources = [] if (sources is None): sources = models.get_models() for source in sources: if isinstance(source, models.base.ModelBase): for field in source._meta.fields: if isinstance(field, GeometryField): kml_sources.append((source._meta.app_label, source._meta.module_name, field.name)) elif isinstance(source, (list, tuple)): if (len(source) != 3): raise ValueError('Must specify a 3-tuple of (app_label, module_name, field_name).') kml_sources.append(source) else: raise TypeError('KML Sources must be a model or a 3-tuple.') return kml_sources
'This method is overrridden so the appropriate `geo_format` attribute is placed on each URL element.'
def get_urls(self, page=1, site=None):
urls = Sitemap.get_urls(self, page=page, site=site) for url in urls: url['geo_format'] = self.geo_format return urls
'This sitemap object initializes on a feed dictionary (as would be passed to `django.contrib.gis.views.feed`) and a slug dictionary. If the slug dictionary is not defined, then it\'s assumed the keys provide the URL parameter to the feed. However, if you have a complex feed (e.g., you override `get_object`, then you\'ll need to provide a slug dictionary. The slug dictionary should have the same keys as the feed dictionary, but each value in the slug dictionary should be a sequence of slugs that may be used for valid feeds. For example, let\'s say we have a feed that returns objects for a specific ZIP code in our feed dictionary: feed_dict = {\'zipcode\' : ZipFeed} Then we would use a slug dictionary with a list of the zip code slugs corresponding to feeds you want listed in the sitemap: slug_dict = {\'zipcode\' : [\'77002\', \'77054\']}'
def __init__(self, feed_dict, slug_dict=None):
self.feed_dict = feed_dict self.locations = [] if (slug_dict is None): slug_dict = {} for section in feed_dict.keys(): if slug_dict.get(section, False): for slug in slug_dict[section]: self.locations.append(('%s/%s' % (section, slug))) else: self.locations.append(section)
'This method is overrridden so the appropriate `geo_format` attribute is placed on each URL element.'
def get_urls(self, page=1, site=None):
urls = Sitemap.get_urls(self, page=page, site=site) for url in urls: url['geo_format'] = 'georss' return urls
'In GeoRSS coordinate pairs are ordered by lat/lon and separated by a single white space. Given a tuple of coordinates, this will return a unicode GeoRSS representation.'
def georss_coords(self, coords):
return u' '.join([(u'%f %f' % (coord[1], coord[0])) for coord in coords])
'Adds a GeoRSS point with the given coords using the given handler. Handles the differences between simple GeoRSS and the more pouplar W3C Geo specification.'
def add_georss_point(self, handler, coords, w3c_geo=False):
if w3c_geo: (lon, lat) = coords[:2] handler.addQuickElement(u'geo:lat', (u'%f' % lat)) handler.addQuickElement(u'geo:lon', (u'%f' % lon)) else: handler.addQuickElement(u'georss:point', self.georss_coords((coords,)))
'This routine adds a GeoRSS XML element using the given item and handler.'
def add_georss_element(self, handler, item, w3c_geo=False):
geom = item.get(u'geometry', None) if (not (geom is None)): if isinstance(geom, (list, tuple)): box_coords = None if isinstance(geom[0], (list, tuple)): if (len(geom) == 2): box_coords = geom else: raise ValueError(u'Only should be two sets of coordinates.') elif (len(geom) == 2): self.add_georss_point(handler, geom, w3c_geo=w3c_geo) elif (len(geom) == 4): box_coords = (geom[:2], geom[2:]) else: raise ValueError(u'Only should be 2 or 4 numeric elements.') if (not (box_coords is None)): if w3c_geo: raise ValueError(u'Cannot use simple GeoRSS box in W3C Geo feeds.') handler.addQuickElement(u'georss:box', self.georss_coords(box_coords)) else: gtype = str(geom.geom_type).lower() if (gtype == u'point'): self.add_georss_point(handler, geom.coords, w3c_geo=w3c_geo) else: if w3c_geo: raise ValueError(u'W3C Geo only supports Point geometries.') if (gtype in (u'linestring', u'linearring')): handler.addQuickElement(u'georss:line', self.georss_coords(geom.coords)) elif (gtype in (u'polygon',)): handler.addQuickElement(u'georss:polygon', self.georss_coords(geom[0].coords)) else: raise ValueError((u'Geometry type "%s" not supported.' % geom.geom_type))
'Figures out the correct OGR Type based upon the input.'
def __init__(self, type_input):
if isinstance(type_input, OGRGeomType): num = type_input.num elif isinstance(type_input, six.string_types): type_input = type_input.lower() if (type_input == 'geometry'): type_input = 'unknown' num = self._str_types.get(type_input, None) if (num is None): raise OGRException(('Invalid OGR String Type "%s"' % type_input)) elif isinstance(type_input, int): if (not (type_input in self._types)): raise OGRException(('Invalid OGR Integer Type: %d' % type_input)) num = type_input else: raise TypeError('Invalid OGR input type given.') self.num = num
'Returns the value of the name property.'
def __str__(self):
return self.name
'Does an equivalence test on the OGR type with the given other OGRGeomType, the short-hand string, or the integer.'
def __eq__(self, other):
if isinstance(other, OGRGeomType): return (self.num == other.num) elif isinstance(other, six.string_types): return (self.name.lower() == other.lower()) elif isinstance(other, int): return (self.num == other) else: return False
'Returns a short-hand string form of the OGR Geometry type.'
@property def name(self):
return self._types[self.num]
'Returns the Django GeometryField for this OGR Type.'
@property def django(self):
s = self.name.replace('25D', '') if (s in ('LinearRing', 'None')): return None elif (s == 'Unknown'): s = 'Geometry' return (s + 'Field')
'Initializes an OGR driver on either a string or integer input.'
def __init__(self, dr_input):
if isinstance(dr_input, six.string_types): self._register() if (dr_input.lower() in self._alias): name = self._alias[dr_input.lower()] else: name = dr_input dr = capi.get_driver_by_name(force_bytes(name)) elif isinstance(dr_input, int): self._register() dr = capi.get_driver(dr_input) elif isinstance(dr_input, c_void_p): dr = dr_input else: raise OGRException(('Unrecognized input type for OGR Driver: %s' % str(type(dr_input)))) if (not dr): raise OGRException(('Could not initialize OGR Driver on input: %s' % str(dr_input))) self.ptr = dr
'Returns the string name of the OGR Driver.'
def __str__(self):
return capi.get_driver_name(self.ptr)
'Attempts to register all the data source drivers.'
def _register(self):
if (not self.driver_count): capi.register_all()
'Returns the number of OGR data source drivers registered.'
@property def driver_count(self):
return capi.get_driver_count()
'Testing OGRGeomType object.'
def test00a_geomtype(self):
try: g = OGRGeomType(1) g = OGRGeomType(7) g = OGRGeomType('point') g = OGRGeomType('GeometrycollectioN') g = OGRGeomType('LINearrING') g = OGRGeomType('Unknown') except: self.fail('Could not create an OGRGeomType object!') self.assertRaises(OGRException, OGRGeomType, 23) self.assertRaises(OGRException, OGRGeomType, 'fooD') self.assertRaises(OGRException, OGRGeomType, 9) self.assertEqual(True, (OGRGeomType(1) == OGRGeomType(1))) self.assertEqual(True, (OGRGeomType(7) == 'GeometryCollection')) self.assertEqual(True, (OGRGeomType('point') == 'POINT')) self.assertEqual(False, (OGRGeomType('point') == 2)) self.assertEqual(True, (OGRGeomType('unknown') == 0)) self.assertEqual(True, (OGRGeomType(6) == 'MULtiPolyGON')) self.assertEqual(False, (OGRGeomType(1) != OGRGeomType('point'))) self.assertEqual(True, (OGRGeomType('POINT') != OGRGeomType(6))) self.assertEqual('PointField', OGRGeomType('Point').django) self.assertEqual('GeometryField', OGRGeomType('Unknown').django) self.assertEqual(None, OGRGeomType('none').django) gt = OGRGeomType('Geometry') self.assertEqual(0, gt.num) self.assertEqual('Unknown', gt.name)
'Testing OGRGeomType object with 25D types.'
def test00b_geomtype_25d(self):
wkb25bit = OGRGeomType.wkb25bit self.assertTrue((OGRGeomType((wkb25bit + 1)) == 'Point25D')) self.assertTrue((OGRGeomType('MultiLineString25D') == (5 + wkb25bit))) self.assertEqual('GeometryCollectionField', OGRGeomType('GeometryCollection25D').django)
'Testing WKT output.'
def test01a_wkt(self):
for g in self.geometries.wkt_out: geom = OGRGeometry(g.wkt) self.assertEqual(g.wkt, geom.wkt)
'Testing EWKT input/output.'
def test01a_ewkt(self):
for ewkt_val in ('POINT (1 2 3)', 'LINEARRING (0 0,1 1,2 1,0 0)'): self.assertEqual(ewkt_val, OGRGeometry(ewkt_val).ewkt) ewkt_val = ('SRID=4326;%s' % ewkt_val) geom = OGRGeometry(ewkt_val) self.assertEqual(ewkt_val, geom.ewkt) self.assertEqual(4326, geom.srs.srid)
'Testing GML output.'
def test01b_gml(self):
for g in self.geometries.wkt_out: geom = OGRGeometry(g.wkt) exp_gml = g.gml if (GDAL_VERSION >= (1, 8)): exp_gml = exp_gml.replace('GeometryCollection', 'MultiGeometry') self.assertEqual(exp_gml, geom.gml)