Here are the examples of the python api django.contrib.gis.geos.Point taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
127 Examples
3
Example 1
Project: django-fakery Source File: test_gis.py
def test_gis_fields(self):
from django.contrib.gis import gdal, geos
gigis = factory.make('tests.Pizzeria')
self.assertTrue(isinstance(gigis.hq, geos.Point))
self.assertTrue(isinstance(gigis.directions, geos.LineString))
self.assertTrue(isinstance(gigis.floor_plan, geos.Polygon))
self.assertTrue(isinstance(gigis.locations, geos.MultiPoint))
self.assertTrue(isinstance(gigis.routes, geos.MultiLineString))
self.assertTrue(isinstance(gigis.delivery_areas, geos.MultiPolygon))
self.assertTrue(isinstance(gigis.all_the_things, geos.GeometryCollection))
if django_version >= (1, 9, 0):
self.assertTrue(isinstance(gigis.rast, gdal.GDALRaster))
3
Example 2
def __init__(self, *args, **kwargs):
super(Venue, self).__init__(*args, **kwargs)
if self.location is None:
longitude = float(kwargs.get('longitude', '0'))
latitude = float(kwargs.get('latitude', '0'))
self.location = geos.Point(longitude, latitude)
3
Example 3
def clean(self):
data = super(LocationForm, self).clean()
if 'point_pos' in self.errors:
del self.errors['point_pos']
if "latitude" in self.changed_data or "longitude" in self.changed_data:
try:
lat, lng = float(data.pop("latitude", None)), float(data.pop("longitude", None))
data['point_pos'] = GEOSGeometry(Point(lng, lat), srid=4326)
except (TypeError, ValueError):
data['point_pos'] = None
if not (data.get("point_pos") or data.get("latitude")):
raise forms.ValidationError({"latitude": "Coordinates is required"})
return data
3
Example 4
Project: django-rest-framework-gis Source File: tests.py
def test_geometry_serializer_method_field(self):
location = Location.objects.create(name='geometry serializer method test', geometry='POINT (135.0 45.0)')
location_loaded = Location.objects.get(pk=location.id)
self.assertEqual(location_loaded.name, 'geometry serializer method test')
self.assertEqual(location_loaded.geometry, Point(135.0, 45.0))
url = reverse('api_geojson_location_details_hidden', args=[location.id])
data = {
"properties": {
"name":"hidden geometry"
}
}
response = self.client.generic('PATCH', url, json.dumps(data), content_type='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data['properties']['name'], 'hidden geometry')
self.assertEqual(response.data['geometry']['type'], 'Point')
self.assertEqual(response.data['geometry']['coordinates'], (0.0, 0.0))
3
Example 5
Project: hue Source File: tests.py
def test_olwidget_has_changed(self):
"""
Check that changes are accurately noticed by OpenLayersWidget.
"""
geoadmin = admin.site._registry[City]
form = geoadmin.get_changelist_form(None)()
has_changed = form.fields['point']._has_changed
initial = Point(13.4197458572965953, 52.5194108501149799, srid=4326)
data_same = "SRID=3857;POINT(1493879.2754093995 6894592.019687599)"
data_almost_same = "SRID=3857;POINT(1493879.2754093990 6894592.019687590)"
data_changed = "SRID=3857;POINT(1493884.0527237 6894593.8111804)"
self.assertTrue(has_changed(None, data_changed))
self.assertTrue(has_changed(initial, ""))
self.assertFalse(has_changed(None, ""))
self.assertFalse(has_changed(initial, data_same))
self.assertFalse(has_changed(initial, data_almost_same))
self.assertTrue(has_changed(initial, data_changed))
3
Example 6
Project: vegphilly.com Source File: search.py
def address_search(query):
geocode_result = geocode.geocode_address(query)
if geocode_result is None:
return Vendor.objects.none()
latitude, longitude, neighborhood = geocode_result
point = Point(x=longitude, y=latitude, srid=4326)
vendors = Vendor.objects.approved().filter(
location__dwithin=(point, .004))
return vendors
3
Example 7
def get_queryset(self):
if not self.request.GET.get('lat'):
return None
nearby_degrees = 0.3
lat = float(self.request.GET.get('lat'))
lng = float(self.request.GET.get('lng'))
user_location = Point(lng, lat)
near_user = user_location.buffer(nearby_degrees)
points = MapData.objects.filter(points__contained=near_user).distance(user_location, field_name='points').order_by('distance')[:30]
polys = MapData.objects.filter(polys__contained=near_user).distance(user_location, field_name='polys').order_by('distance')[:30]
lines = MapData.objects.filter(lines__contained=near_user).distance(user_location, field_name='lines').order_by('distance')[:30]
queryset = sorted(list(points)+list(polys)+list(lines), key=attrgetter('distance'))[:30]
return queryset
3
Example 8
Project: TransitNearMe Source File: views.py
def get_api_result(self, *args, **kwargs):
stops = Stop.objects.filter(location__distance_lte=(
Point(self.lng, self.lat, srid=4326),
D(m=self.radius_m)))
return [s.json_dict() for s in stops]
3
Example 9
Project: shareabouts-api Source File: utils.py
def to_geom(string):
"""
Given a string, convert it to a geometry.
"""
try:
geom = GEOSGeometry(string)
except ValueError:
try:
lat, lng = [float(coord.strip()) for coord in string.split(',')]
except ValueError:
raise ValueError(
('Argument must be a comma-separated pair of numbers or a '
'string that the GEOSGeometry constructor can handle: %r')
% string
)
else:
geom = Point(lng, lat)
return geom
3
Example 10
Project: roundware-server Source File: api.py
def is_listener_in_range_of_stream(form, proj):
# If latitude and longitude is not specified assume True.
if not form.get('latitude', None) or not form.get('longitude', None):
return True
listener = Point(float(form['longitude']), float(form['latitude']))
# See if there are any active speakers within range of the listener's location
in_range = models.Speaker.objects.filter(
project=proj,
activeyn=True,
shape__dwithin=(listener, D(m=proj.out_of_range_distance))
).exists()
return in_range
3
Example 11
Project: django-rest-framework-gis Source File: tests.py
def test_patch_geojson_location(self):
location = Location.objects.create(name='geojson patch test', geometry='POINT (135.0 45.0)')
url = reverse('api_geojson_location_details', args=[location.id])
data = {
"properties": {
"name":"geojson successful patch test"
},
"geometry": {
"type": "Point",
"coordinates": [10.1, 10.1]
}
}
response = self.client.generic('PATCH', url, json.dumps(data), content_type='application/json')
self.assertEqual(response.status_code, 200)
location_reloaded = Location.objects.get(pk=location.id)
self.assertEquals(location_reloaded.name, 'geojson successful patch test')
self.assertEquals(location_reloaded.geometry, Point(10.1, 10.1))
3
Example 12
Project: colorado-geology-geodjango Source File: views.py
def find_rocks(request):
"""
Given a given lat/long pair, return the unit(s) surrounding it.
"""
if request.is_ajax():
lat = request.GET.get('lat', None)
lon = request.GET.get('lon', None)
if lat and lon:
point = Point(float(lon), float(lat))
units = Unit.objects.filter(geom__contains=point)
geojson_data = GeoJSONSerializer().serialize(
units, use_natural_keys=True)
return HttpResponse(geojson_data,
mimetype='application/json')
msg = "Bad request: not AJAX or no latlong pair present"
return HttpResponseBadRequest(msg)
3
Example 13
def geos(self, query):
"Returns a GEOS Point object for the given query."
ll = self.lon_lat(query)
if ll:
from django.contrib.gis.geos import Point
return Point(ll, srid=4326)
else:
return None
3
Example 14
Project: django-fakery Source File: fakes.py
def point(faker, field, srid):
lat = random.uniform(-180.0, 180.0)
lng = random.uniform(-90, 90)
if field.dim == 2:
return geos.Point(lat, lng, srid=srid)
else:
alt = random.uniform(-4000.0, 9000.0)
return geos.Point(lat, lng, alt, srid=srid)
3
Example 15
def form_valid(self, form):
form.instance.location = Point(
(float(form.cleaned_data['location_lon']), float(form.cleaned_data['location_lat']))
)
return super(ReportIncidentView, self).form_valid(form)
3
Example 16
def setUp(self):
try:
register(User)
except AlreadyRegistered:
pass
self.obj = User.objects.create(username='user')
self.point = Point(5, 5)
self.poly = Polygon(((0, 0), (0, 10), (10, 10), (0, 10), (0, 0)),
((4, 4), (4, 6), (6, 6), (6, 4), (4, 4)))
3
Example 17
def test_GeometryField(self):
point = Point(0, 25)
field = GeometryField()
result = field.to_representation(point)
assert result['type'] == 'Point'
assert result['coordinates'] == [0.0, 25.0]
3
Example 18
Project: postcodeinfo Source File: test_addressbase_basic_importer.py
def test_that_running_import_replaces_any_existing_data(self):
dummy_date = time.strftime("%Y-%m-%d")
Address.objects.create(postcode_index='abcdef',
point=Point(123, 123),
rpc=012345,
uprn=1234567890,
start_date=dummy_date,
last_update_date=dummy_date,
entry_date=dummy_date,
process_date=dummy_date
)
self.test_import()
self.assertEqual(None, Address.objects.filter(uprn=1234567890).first() )
3
Example 19
Project: django-geotagging Source File: tag_tests.py
def setUp(self):
self.installTagLibrary('geotagging.templatetags.geotagging_tags')
denver_user = User.objects.create(username='denver')
dia_user = User.objects.create(username='dia')
aa_user = User.objects.create(username='annarbor')
self.line = LineString((-104.552299, 38.128626), (-103.211191, 40.715081))
self.denver = Geotag.objects.create(tagged_obj=denver_user,
point=Point(-104.9847034, 39.739153600000002))
dia = Geotag.objects.create(tagged_obj=dia_user,
point=Point(-104.673856, 39.849511999999997))
aa = Geotag.objects.create(tagged_obj=aa_user,
point=Point(-83.726329399999997, 42.2708716))
3
Example 20
def test_node(self):
w = osm.OSMCreateWriter()
id = w.build_node(geos.Point(123, 456), [])
# print w.xml()
n = w.tree.find('./create/node')
self.assert_(n is not None, "Couldn't find <node>")
self.assertEqual(n.get('id'), id[0])
self.assertEqual(len(w.tree.findall('.//node')), 1)
self.assert_(int(n.get('id')) < 0, "ID < 0")
self.assertEqual(float(n.get('lon')), 123)
self.assertEqual(float(n.get('lat')), 456)
self.assertEqual(len(n.getchildren()), 0)
id = w.build_node(geos.Point(234, 567), [])
self.assertEqual(len(w.tree.findall('.//node')), 2)
3
Example 21
Project: hue Source File: tests.py
def test_olmap_OSM_rendering(self):
geoadmin = admin.site._registry[City]
result = geoadmin.get_map_widget(City._meta.get_field('point'))(
).render('point', Point(-79.460734, 40.18476))
self.assertIn(
"""geodjango_point.layers.base = new OpenLayers.Layer.OSM("OpenStreetMap (Mapnik)");""",
result)
3
Example 22
def test_olmap_WMS_rendering(self):
geoadmin = admin.GeoModelAdmin(City, admin.site)
result = geoadmin.get_map_widget(City._meta.get_field('point'))(
).render('point', Point(-79.460734, 40.18476))
self.assertIn(
"""geodjango_point.layers.base = new OpenLayers.Layer.WMS("OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: \'basic\', format: 'image/jpeg'});""",
result)
3
Example 23
def geos(self, query):
"Return a GEOS Point object for the given query."
ll = self.lon_lat(query)
if ll:
from django.contrib.gis.geos import Point
return Point(ll, srid=4326)
else:
return None
3
Example 24
Project: django-location Source File: runmeter.py
def _get_processed_point(self, point, base_time):
point = point.copy()
point['point'] = Point(
point['lat'],
point['lng'],
)
point['date'] = base_time + datetime.timedelta(
seconds=point['time']
)
return point
3
Example 25
def test_olmap_WMS_rendering(self):
geoadmin = admin.GeoModelAdmin(City, admin.site)
result = geoadmin.get_map_widget(City._meta.get_field('point'))(
).render('point', Point(-79.460734, 40.18476))
self.assertIn(
"""geodjango_point.layers.base = new OpenLayers.Layer.WMS("OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: \'basic\', format: 'image/jpeg'});""",
result)
3
Example 26
Project: django-rest-framework-gis Source File: filters.py
def get_filter_point(self, request):
point_string = request.query_params.get(self.point_param, None)
if not point_string:
return None
try:
(x, y) = (float(n) for n in point_string.split(','))
except ValueError:
raise ParseError('Invalid geometry string supplied for parameter {0}'.format(self.point_param))
p = Point(x, y)
return p
3
Example 27
def get_width_height(self, extent):
"""
Returns the width and height for the given extent.
"""
# Getting the lower-left, upper-left, and upper-right
# coordinates from the extent.
ll = Point(extent[:2])
ul = Point(extent[0], extent[3])
ur = Point(extent[2:])
# Calculating the width and height.
height = ll.distance(ul)
width = ul.distance(ur)
return width, height
3
Example 28
def __init__(self, *args, **kwargs):
if args:
data = args[0]
if data['latitude'] and data['longitude']:
latitude = float(data['latitude'])
longitude = float(data['longitude'])
data['point_pos'] = GEOSGeometry(Point(longitude, latitude), srid=4326)
try:
coordinates = kwargs['instance'].point_pos.tuple
initial = kwargs.get('initial', {})
initial['longitude'] = coordinates[0]
initial['latitude'] = coordinates[1]
kwargs['initial'] = initial
except (KeyError, AttributeError):
pass
super(LocationForm, self).__init__(*args, **kwargs)
3
Example 29
Project: django-rest-framework-gis Source File: tests.py
def test_patch_geojson_location_wo_changing_geometry(self):
location = Location.objects.create(name='geojson patch test', geometry='POINT (135.0 45.0)')
url = reverse('api_geojson_location_details', args=[location.id])
data = {
"properties": {
"name":"geojson successful patch test"
}
}
response = self.client.generic('PATCH', url, json.dumps(data), content_type='application/json')
self.assertEqual(response.status_code, 200)
location_reloaded = Location.objects.get(pk=location.id)
self.assertEquals(location_reloaded.name, 'geojson successful patch test')
self.assertEquals(location_reloaded.geometry, Point(135.0, 45.0))
3
Example 30
Project: django-geojson Source File: tests.py
def test_geometry_property(self):
class Basket(models.Model):
@property
def geom(self):
return GeometryCollection(LineString((3, 4, 5), (6, 7, 8)), Point(1, 2, 3), srid=4326)
serializer = Serializer()
features = json.loads(
serializer.serialize([Basket()], crs=False, force2d=True))
expected_content = {"type": "FeatureCollection", "features": [{"geometry": {"type": "GeometryCollection", "geometries": [{"type": "LineString", "coordinates": [[3.0, 4.0], [6.0, 7.0]]}, {"type": "Point", "coordinates": [1.0, 2.0]}]}, "type": "Feature", "properties": {"id": None}}]}
self.assertEqual(features, expected_content)
3
Example 31
Project: django-rest-framework-gis Source File: tests.py
def test_geometry_serializer_method_field_none(self):
location = Location.objects.create(name='None value', geometry='POINT (135.0 45.0)')
location_loaded = Location.objects.get(pk=location.id)
self.assertEqual(location_loaded.geometry, Point(135.0, 45.0))
url = reverse('api_geojson_location_details_none', args=[location.id])
response = self.client.generic('GET', url, content_type='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data['properties']['name'], 'None value')
self.assertEqual(response.data['geometry'], None)
3
Example 32
def forwards(self, orm):
"Write your forwards methods here."
# Note: Remember to use orm['appname.ModelName'] rather than "from
# appname.models..."
for vendor in orm.Vendor.objects.all():
if vendor.latitude and vendor.longitude:
p = Point(x=vendor.longitude, y=vendor.latitude, srid=4326)
vendor.location = p
vendor.save()
3
Example 33
def linearring(faker, field, srid, *args, **kwargs):
point_0 = point(faker, field, srid)
point_1 = point(faker, field, srid)
point_2 = point(faker, field, srid)
point_3 = geos.Point(point_0.x, point_0.y)
points = [point_0, point_1, point_2, point_3]
return geos.LinearRing(*points)
3
Example 34
Project: PyClassLessons Source File: tests.py
def test_olmap_OSM_rendering(self):
geoadmin = admin.site._registry[City]
result = geoadmin.get_map_widget(City._meta.get_field('point'))(
).render('point', Point(-79.460734, 40.18476))
self.assertIn(
"""geodjango_point.layers.base = new OpenLayers.Layer.OSM("OpenStreetMap (Mapnik)");""",
result)
3
Example 35
Project: lettuce Source File: tests.py
def test02_select_related(self):
"Testing `select_related` on geographic models (see #7126)."
qs1 = City.objects.all()
qs2 = City.objects.select_related()
qs3 = City.objects.select_related('location')
# Reference data for what's in the fixtures.
cities = (
('Aurora', 'TX', -97.516111, 33.058333),
('Roswell', 'NM', -104.528056, 33.387222),
('Kecksburg', 'PA', -79.460734, 40.18476),
)
for qs in (qs1, qs2, qs3):
for ref, c in zip(cities, qs):
nm, st, lon, lat = ref
self.assertEqual(nm, c.name)
self.assertEqual(st, c.state)
self.assertEqual(Point(lon, lat), c.location.point)
3
Example 36
Project: Roll-Your-Own Source File: data.py
def generate_point(field, instance, counter):
from django.contrib.gis.geos import Point
x_around = 144.940
y_around = -37.814
x = x_around is not None and (x_around + (random.random() - 0.5)) or (random_random() - 0.5) * 360
y = y_around is not None and (y_around + (random.random() - 0.5)) or (random_randint() - 0.5) * 180
return Point(x, y)
3
Example 37
Project: linz2osm Source File: overpass.py
def geometry_for_osm_feature(osm_feature, nodes={}, ways={}):
if osm_feature['type'] == 'way':
node_list = filter(None, [
node_point(node_id, nodes) for node_id in osm_feature['nodes']
])
if node_list:
return LineString(node_list)
else:
return None
elif osm_feature['type'] == 'node':
return Point(osm_feature['lon'], osm_feature['lat'])
elif osm_feature['type'] == 'rel':
# FIXME - implement
return None
else:
return None
3
Example 38
def get_width_height(self, extent):
"""
Returns the width and height for the given extent.
"""
# Getting the lower-left, upper-left, and upper-right
# coordinates from the extent.
ll = Point(extent[:2])
ul = Point(extent[0], extent[3])
ur = Point(extent[2:])
# Calculating the width and height.
height = ll.distance(ul)
width = ul.distance(ur)
return width, height
3
Example 39
Project: roundware-server Source File: gpsmixer.py
def get_current_speakers(self):
logger.info("filtering speakers")
listener = Point(float(self.listener['longitude']), float(self.listener['latitude']))
# get active speakers for this project, and select from those all speakers our listener is inside
speakers = Speaker.objects.filter(activeyn=True, project=self.project).filter(
Q(shape__dwithin=(listener, D(m=0))) | Q(minvolume__gt=0)
)
# make sure all the current speakers are registered in the self.speakers dict
for s in speakers:
self.speakers[s.id] = s
self.inspect_speaker(s)
return list(speakers)
3
Example 40
def geocode(self, query):
data = self.run_query(query)
if not data['status'] == 'OK':
errorcls = get_response_exception(data['status'])
raise errorcls(data['status'])
location = data['results'][0]['geometry']['location']
return Point(location['lng'], location['lat'])
0
Example 41
def test_proxy(self):
"Testing Lazy-Geometry support (using the GeometryProxy)."
## Testing on a Point
pnt = Point(0, 0)
nullcity = City(name='NullCity', point=pnt)
nullcity.save()
# Making sure TypeError is thrown when trying to set with an
# incompatible type.
for bad in [5, 2.0, LineString((0, 0), (1, 1))]:
try:
nullcity.point = bad
except TypeError:
pass
else:
self.fail('Should throw a TypeError')
# Now setting with a compatible GEOS Geometry, saving, and ensuring
# the save took, notice no SRID is explicitly set.
new = Point(5, 23)
nullcity.point = new
# Ensuring that the SRID is automatically set to that of the
# field after assignment, but before saving.
self.assertEqual(4326, nullcity.point.srid)
nullcity.save()
# Ensuring the point was saved correctly after saving
self.assertEqual(new, City.objects.get(name='NullCity').point)
# Setting the X and Y of the Point
nullcity.point.x = 23
nullcity.point.y = 5
# Checking assignments pre & post-save.
self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point)
nullcity.save()
self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point)
nullcity.delete()
## Testing on a Polygon
shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0))
inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40))
# Creating a State object using a built Polygon
ply = Polygon(shell, inner)
nullstate = State(name='NullState', poly=ply)
self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None
nullstate.save()
ns = State.objects.get(name='NullState')
self.assertEqual(ply, ns.poly)
# Testing the `ogr` and `srs` lazy-geometry properties.
if gdal.HAS_GDAL:
self.assertEqual(True, isinstance(ns.poly.ogr, gdal.OGRGeometry))
self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb)
self.assertEqual(True, isinstance(ns.poly.srs, gdal.SpatialReference))
self.assertEqual('WGS 84', ns.poly.srs.name)
# Changing the interior ring on the poly attribute.
new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30))
ns.poly[1] = new_inner
ply[1] = new_inner
self.assertEqual(4326, ns.poly.srid)
ns.save()
self.assertEqual(ply, State.objects.get(name='NullState').poly)
ns.delete()
0
Example 42
@no_mysql
def test_lookup_insert_transform(self):
"Testing automatic transform for lookups and inserts."
# San Antonio in 'WGS84' (SRID 4326)
sa_4326 = 'POINT (-98.493183 29.424170)'
wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84
# Oracle doesn't have SRID 3084, using 41157.
if oracle:
# San Antonio in 'Texas 4205, Southern Zone (1983, meters)' (SRID 41157)
# Used the following Oracle SQL to get this value:
# SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_CS.TRANSFORM(SDO_GEOMETRY('POINT (-98.493183 29.424170)', 4326), 41157)) FROM DUAL;
nad_wkt = 'POINT (300662.034646583 5416427.45974934)'
nad_srid = 41157
else:
# San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084)
nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)' # Used ogr.py in gdal 1.4.1 for this transform
nad_srid = 3084
# Constructing & querying with a point from a different SRID. Oracle
# `SDO_OVERLAPBDYINTERSECT` operates differently from
# `ST_Intersects`, so contains is used instead.
nad_pnt = fromstr(nad_wkt, srid=nad_srid)
if oracle:
tx = Country.objects.get(mpoly__contains=nad_pnt)
else:
tx = Country.objects.get(mpoly__intersects=nad_pnt)
self.assertEqual('Texas', tx.name)
# Creating San Antonio. Remember the Alamo.
sa = City.objects.create(name='San Antonio', point=nad_pnt)
# Now verifying that San Antonio was transformed correctly
sa = City.objects.get(name='San Antonio')
self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6)
self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6)
# If the GeometryField SRID is -1, then we shouldn't perform any
# transformation if the SRID of the input geometry is different.
# SpatiaLite does not support missing SRID values.
if not spatialite:
m1 = MinusOneSRID(geom=Point(17, 23, srid=4326))
m1.save()
self.assertEqual(-1, m1.geom.srid)
0
Example 43
Project: StaticMapService Source File: views.py
def render_static(request, height=None, width=None, format='png',
background='satellite', bounds=None, center=None, render_srid=3857):
# width and height
width = int(width)
height = int(height)
if width > settings.MAX_IMAGE_DIMENSION or \
height > settings.MAX_IMAGE_DIMENSION or \
width <= 1 or height <= 1:
logging.debug("Invalid size")
return HttpResponseBadRequest("Invalid image size, both dimensions must be in range %i-%i" % (1, settings.MAX_IMAGE_DIMENSION))
# image format
if format not in IMAGE_FORMATS:
logging.error("unknown image format %s" % format)
return HttpResponseBadRequest("Unknown image format, available formats: " + ", ".join(IMAGE_FORMATS))
if format.startswith('png'):
mimetype = 'image/png'
elif format.startswith('jpeg'):
mimetype = 'image/jpeg'
# bounds
bounds_box = None
if bounds:
bounds_components = bounds.split(',')
if len(bounds_components) != 4:
return HttpResponseBadRequest("Invalid bounds, must be 4 , separated numbers")
bounds_components = [float(f) for f in bounds_components]
if not (-180 < bounds_components[0] < 180) or not (-180 < bounds_components[2] < 180):
logging.error("x out of range %f or %f" % (bounds_components[0], bounds_components[2]))
return HttpResponseBadRequest("x out of range %f or %f" % (bounds_components[0], bounds_components[2]))
if not (-90 < bounds_components[1] < 90) or not (-90 < bounds_components[3] < 90):
logging.error("y out of range %f or %f" % (bounds_components[1], bounds_components[3]))
return HttpResponseBadRequest("y out of range %f or %f" % (bounds_components[1], bounds_components[3]))
ll = Point(bounds_components[0], bounds_components[1], srid=4326)
ll.transform(render_srid)
ur = Point(bounds_components[2], bounds_components[3], srid=4326)
ur.transform(render_srid)
bounds_box = mapnik.Box2d(ll.x, ll.y, ur.x, ur.y)
elif center:
center_components = center.split(',')
if len(center_components) != 3:
return HttpResponseBadRequest()
lon = float(center_components[0])
lat = float(center_components[1])
zoom = int(center_components[2])
# todo calc bounds from center and zoom
# baselayer
if background not in settings.BASE_LAYERS and background != 'none':
return HttpResponseNotFound("Background not found")
# GeoJSON post data
if request.method == "POST" and len(request.body):
input_data = json.loads(request.body)
else:
input_data = None
if not bounds and not center and not input_data:
return HttpResponseBadRequest("Bounds, center, or post data is required.")
# initialize map
m = mapnik.Map(width, height)
m.srs = '+init=epsg:' + str(render_srid)
# add a tile source as a background
if background != "none":
background_file = settings.BASE_LAYERS[background]
background_style = mapnik.Style()
background_rule = mapnik.Rule()
background_rule.symbols.append(mapnik.RasterSymbolizer())
background_style.rules.append(background_rule)
m.append_style('background style', background_style)
tile_layer = mapnik.Layer('background')
tile_layer.srs = '+init=epsg:' + str(render_srid)
tile_layer.datasource = mapnik.Gdal(base=settings.BASE_LAYER_DIR, file=background_file)
tile_layer.styles.append('background style')
m.layers.append(tile_layer)
# add features from geojson
if input_data and input_data['type'] == "Feature":
features = [input_data]
elif input_data and input_data['type'] == "FeatureCollection":
if 'features' not in input_data:
return HttpResponseBadRequest()
features = input_data['features']
else:
features = []
logging.debug("Adding %d features to map" % len(features))
geometries = []
point_features = []
fid = 0
for feature in features:
if 'geometry' not in feature:
logging.debug("feature does not have geometry")
return HttpResponseBadRequest("Feature does not have a geometry")
if 'type' not in feature['geometry']:
logging.debug("geometry does not have type")
return HttpResponseBadRequest("Geometry does not have a type")
fid += 1
style_name = str(fid)
if feature['geometry']['type'] == 'Point':
point_features.append(feature)
elif feature['geometry']['type'] in ('LineString', 'MultiLineString'):
if feature['geometry']['type'] == 'LineString':
geos_feature = LineString(feature['geometry']['coordinates'])
elif feature['geometry']['type'] == 'MultiLineString':
rings = feature['geometry']['coordinates']
rings = [[(c[0], c[1]) for c in r] for r in rings]
if len(rings) == 1:
geos_feature = LineString(rings[0])
else:
linestrings = []
for ring in rings:
try:
linestrings.append(LineString(ring))
except Exception, e:
logging.error("Error adding ring: %s", e)
geos_feature = MultiLineString(linestrings)
geos_feature.srid = 4326
geos_feature.transform(render_srid)
geometries.append(geos_feature)
style = mapnik.Style()
line_rule = mapnik.Rule()
style_dict = None
if 'style' in feature:
style_dict = feature['style']
elif 'properties' in feature:
style_dict = feature['properties']
line_rule.symbols.append(line_symbolizer(style_dict))
style.rules.append(line_rule)
m.append_style(style_name, style)
wkt = geos_feature.wkt
line_layer = mapnik.Layer(style_name + ' layer')
line_layer.datasource = mapnik.CSV(inline='wkt\n' + '"' + wkt + '"')
line_layer.styles.append(style_name)
line_layer.srs = '+init=epsg:' + str(render_srid)
m.layers.append(line_layer)
elif feature['geometry']['type'] == 'Polygon':
geos_feature = GEOSGeometry(json.dumps(feature['geometry']))
geos_feature.srid = 4326
geos_feature.transform(render_srid)
geometries.append(geos_feature)
style = mapnik.Style()
rule = mapnik.Rule()
style_dict = None
if 'style' in feature:
style_dict = feature['style']
elif 'properties' in feature:
style_dict = feature['properties']
rule.symbols.append(polygon_symbolizer(style_dict))
rule.symbols.append(line_symbolizer(style_dict))
style.rules.append(rule)
m.append_style(style_name, style)
wkt = geos_feature.wkt
layer = mapnik.Layer(style_name + ' layer')
layer.datasource = mapnik.CSV(inline='wkt\n' + '"' + wkt + '"')
layer.styles.append(style_name)
layer.srs = '+init=epsg:' + str(render_srid)
m.layers.append(layer)
else:
logging.info("Not adding unknown feature type")
# point features are coaslesced into a single layer for efficiency
if len(point_features):
logging.debug("Adding %i point features in 1 layer" % len(point_features))
point_style = mapnik.Style()
point_rule = mapnik.Rule()
point_symbolizer = mapnik.PointSymbolizer()
point_rule.symbols.append(point_symbolizer)
point_style.rules.append(point_rule)
m.append_style('point_style', point_style)
csv = 'wkt\n'
for feature in point_features:
geos_feature = Point(feature['geometry']['coordinates'])
geos_feature.srid = 4326
geos_feature.transform(render_srid)
geometries.append(geos_feature)
csv += '"' + geos_feature.wkt + '"\n'
point_layer = mapnik.Layer('point layer')
point_layer.datasource = mapnik.CSV(inline=csv)
point_layer.styles.append('point_style')
point_layer.srs = '+init=epsg:' + str(render_srid)
m.layers.append(point_layer)
# bounds not in url, calculate from data
if not bounds_box:
geometry_collection = GeometryCollection(geometries)
minx, miny, maxx, maxy = geometry_collection.extent
buffer_size = .2
x_buffer_size = ((maxx - minx) * buffer_size)
y_buffer_size = ((maxy - miny) * buffer_size)
if x_buffer_size == 0: # this can happen if there is only 1 point feature
x_buffer_size = 1000
if y_buffer_size == 0:
y_buffer_size = 1000
bounds_box = mapnik.Box2d(minx - x_buffer_size, miny - y_buffer_size,
maxx + x_buffer_size, maxy + y_buffer_size)
m.zoom_to_box(bounds_box)
# render image
im = mapnik.Image(m.width, m.height)
mapnik.render(m, im)
data = im.tostring(str(format))
if background in settings.BASE_LAYERS_ATTRIBUTION:
image = Image.open(cStringIO.StringIO(data))
if format.startswith('png'):
image = image.convert('RGB') # workaround for Pillow palette bug
add_attribution(image, settings.BASE_LAYERS_ATTRIBUTION[background])
output = cStringIO.StringIO()
match = re.match('^(jpeg|png)(\d{1,3})$', format)
if match:
image_format, quality = match.groups()
quality = int(quality)
if image_format == 'jpeg':
image.save(output, 'jpeg', quality=quality)
else:
image = image.convert('P', palette=Image.ADAPTIVE, colors=quality)
bits = int(log(quality, 2))
image.save(output, 'png', bits=bits)
else:
image.save(output, format)
data = output.getvalue()
output.close()
return HttpResponse(data, content_type=mimetype)
0
Example 44
Project: django-airports Source File: airports.py
def get_country(self, name, row):
cols, cache = self.columns, self.countries
if name in cache:
return cache[name]
point = Point(float(row[cols['longitude']]), float(row[cols['latitude']]))
qs = Country.objects.all()
try:
c = qs.get(name__iexact=name) # first attempt
except Country.DoesNotExist:
try:
c = qs.get(alt_names__name__iexact=name) # second attempt
except (Country.DoesNotExist, MultipleObjectsReturned):
try:
c = qs.filter(city__in=City.objects.filter(
location__distance_lte=(point, D(km=25))))[0] # third attempt
except IndexError:
c = None # shut happens
cache[name] = c
return c
0
Example 45
@no_mysql
def test_lookup_insert_transform(self):
"Testing automatic transform for lookups and inserts."
# San Antonio in 'WGS84' (SRID 4326)
sa_4326 = 'POINT (-98.493183 29.424170)'
wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84
# Oracle doesn't have SRID 3084, using 41157.
if oracle:
# San Antonio in 'Texas 4205, Southern Zone (1983, meters)' (SRID 41157)
# Used the following Oracle SQL to get this value:
# SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_CS.TRANSFORM(SDO_GEOMETRY('POINT (-98.493183 29.424170)', 4326), 41157)) FROM DUAL;
nad_wkt = 'POINT (300662.034646583 5416427.45974934)'
nad_srid = 41157
else:
# San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084)
nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)' # Used ogr.py in gdal 1.4.1 for this transform
nad_srid = 3084
# Constructing & querying with a point from a different SRID. Oracle
# `SDO_OVERLAPBDYINTERSECT` operates differently from
# `ST_Intersects`, so contains is used instead.
nad_pnt = fromstr(nad_wkt, srid=nad_srid)
if oracle:
tx = Country.objects.get(mpoly__contains=nad_pnt)
else:
tx = Country.objects.get(mpoly__intersects=nad_pnt)
self.assertEqual('Texas', tx.name)
# Creating San Antonio. Remember the Alamo.
sa = City.objects.create(name='San Antonio', point=nad_pnt)
# Now verifying that San Antonio was transformed correctly
sa = City.objects.get(name='San Antonio')
self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6)
self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6)
# If the GeometryField SRID is -1, then we shouldn't perform any
# transformation if the SRID of the input geometry is different.
# SpatiaLite does not support missing SRID values.
if not spatialite:
m1 = MinusOneSRID(geom=Point(17, 23, srid=4326))
m1.save()
self.assertEqual(-1, m1.geom.srid)
0
Example 46
Project: django-airports Source File: airports.py
def get_city(self, name, row, country):
cols, cache = self.columns, self.cities
iso = country.code
if (iso, name) in cache:
return cache[(iso, name)]
point = Point(float(row[cols['longitude']]), float(row[cols['latitude']]))
qs = City.objects.distance(point).filter(country=country)
try:
c = qs.get(name_std__iexact=name)
except (City.DoesNotExist, MultipleObjectsReturned):
try:
c = qs.get(Q(name__iexact=name) | Q(alt_names__name__iexact=name))
except (City.DoesNotExist, MultipleObjectsReturned):
try:
c = qs.exclude(
location__distance_gte=(point, D(km=50))).order_by('distance')[0]
except IndexError:
c = None
cache[(iso, name)] = c
return c
0
Example 47
Project: splunk-webframework Source File: test_geos.py
def test_hexewkb(self):
"Testing (HEX)EWKB output."
# For testing HEX(EWKB).
ogc_hex = b'01010000000000000000000000000000000000F03F'
ogc_hex_3d = b'01010000800000000000000000000000000000F03F0000000000000040'
# `SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(0 1)', 4326));`
hexewkb_2d = b'0101000020E61000000000000000000000000000000000F03F'
# `SELECT ST_AsHEXEWKB(ST_GeomFromEWKT('SRID=4326;POINT(0 1 2)'));`
hexewkb_3d = b'01010000A0E61000000000000000000000000000000000F03F0000000000000040'
pnt_2d = Point(0, 1, srid=4326)
pnt_3d = Point(0, 1, 2, srid=4326)
# OGC-compliant HEX will not have SRID value.
self.assertEqual(ogc_hex, pnt_2d.hex)
self.assertEqual(ogc_hex_3d, pnt_3d.hex)
# HEXEWKB should be appropriate for its dimension -- have to use an
# a WKBWriter w/dimension set accordingly, else GEOS will insert
# garbage into 3D coordinate if there is none. Also, GEOS has a
# a bug in versions prior to 3.1 that puts the X coordinate in
# place of Z; an exception should be raised on those versions.
self.assertEqual(hexewkb_2d, pnt_2d.hexewkb)
if GEOS_PREPARE:
self.assertEqual(hexewkb_3d, pnt_3d.hexewkb)
self.assertEqual(True, GEOSGeometry(hexewkb_3d).hasz)
else:
try:
hexewkb = pnt_3d.hexewkb
except GEOSException:
pass
else:
self.fail('Should have raised GEOSException.')
# Same for EWKB.
self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb)
if GEOS_PREPARE:
self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb)
else:
try:
ewkb = pnt_3d.ewkb
except GEOSException:
pass
else:
self.fail('Should have raised GEOSException')
# Redundant sanity check.
self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid)
0
Example 48
Project: splunk-webframework Source File: test_geos.py
def test_points(self):
"Testing Point objects."
prev = fromstr('POINT(0 0)')
for p in self.geometries.points:
# Creating the point from the WKT
pnt = fromstr(p.wkt)
self.assertEqual(pnt.geom_type, 'Point')
self.assertEqual(pnt.geom_typeid, 0)
self.assertEqual(p.x, pnt.x)
self.assertEqual(p.y, pnt.y)
self.assertEqual(True, pnt == fromstr(p.wkt))
self.assertEqual(False, pnt == prev)
# Making sure that the point's X, Y components are what we expect
self.assertAlmostEqual(p.x, pnt.tuple[0], 9)
self.assertAlmostEqual(p.y, pnt.tuple[1], 9)
# Testing the third dimension, and getting the tuple arguments
if hasattr(p, 'z'):
self.assertEqual(True, pnt.hasz)
self.assertEqual(p.z, pnt.z)
self.assertEqual(p.z, pnt.tuple[2], 9)
tup_args = (p.x, p.y, p.z)
set_tup1 = (2.71, 3.14, 5.23)
set_tup2 = (5.23, 2.71, 3.14)
else:
self.assertEqual(False, pnt.hasz)
self.assertEqual(None, pnt.z)
tup_args = (p.x, p.y)
set_tup1 = (2.71, 3.14)
set_tup2 = (3.14, 2.71)
# Centroid operation on point should be point itself
self.assertEqual(p.centroid, pnt.centroid.tuple)
# Now testing the different constructors
pnt2 = Point(tup_args) # e.g., Point((1, 2))
pnt3 = Point(*tup_args) # e.g., Point(1, 2)
self.assertEqual(True, pnt == pnt2)
self.assertEqual(True, pnt == pnt3)
# Now testing setting the x and y
pnt.y = 3.14
pnt.x = 2.71
self.assertEqual(3.14, pnt.y)
self.assertEqual(2.71, pnt.x)
# Setting via the tuple/coords property
pnt.tuple = set_tup1
self.assertEqual(set_tup1, pnt.tuple)
pnt.coords = set_tup2
self.assertEqual(set_tup2, pnt.coords)
prev = pnt # setting the previous geometry
0
Example 49
Project: splunk-webframework Source File: test_geos.py
def test_mutable_geometries(self):
"Testing the mutability of Polygons and Geometry Collections."
### Testing the mutability of Polygons ###
for p in self.geometries.polygons:
poly = fromstr(p.wkt)
# Should only be able to use __setitem__ with LinearRing geometries.
self.assertRaises(TypeError, poly.__setitem__, 0, LineString((1, 1), (2, 2)))
# Constructing the new shell by adding 500 to every point in the old shell.
shell_tup = poly.shell.tuple
new_coords = []
for point in shell_tup: new_coords.append((point[0] + 500., point[1] + 500.))
new_shell = LinearRing(*tuple(new_coords))
# Assigning polygon's exterior ring w/the new shell
poly.exterior_ring = new_shell
s = str(new_shell) # new shell is still accessible
self.assertEqual(poly.exterior_ring, new_shell)
self.assertEqual(poly[0], new_shell)
### Testing the mutability of Geometry Collections
for tg in self.geometries.multipoints:
mp = fromstr(tg.wkt)
for i in range(len(mp)):
# Creating a random point.
pnt = mp[i]
new = Point(random.randint(21, 100), random.randint(21, 100))
# Testing the assignment
mp[i] = new
s = str(new) # what was used for the assignment is still accessible
self.assertEqual(mp[i], new)
self.assertEqual(mp[i].wkt, new.wkt)
self.assertNotEqual(pnt, mp[i])
# MultiPolygons involve much more memory management because each
# Polygon w/in the collection has its own rings.
for tg in self.geometries.multipolygons:
mpoly = fromstr(tg.wkt)
for i in xrange(len(mpoly)):
poly = mpoly[i]
old_poly = mpoly[i]
# Offsetting the each ring in the polygon by 500.
for j in xrange(len(poly)):
r = poly[j]
for k in xrange(len(r)): r[k] = (r[k][0] + 500., r[k][1] + 500.)
poly[j] = r
self.assertNotEqual(mpoly[i], poly)
# Testing the assignment
mpoly[i] = poly
s = str(poly) # Still accessible
self.assertEqual(mpoly[i], poly)
self.assertNotEqual(mpoly[i], old_poly)
0
Example 50
def test_proxy(self):
"Testing Lazy-Geometry support (using the GeometryProxy)."
## Testing on a Point
pnt = Point(0, 0)
nullcity = City(name='NullCity', point=pnt)
nullcity.save()
# Making sure TypeError is thrown when trying to set with an
# incompatible type.
for bad in [5, 2.0, LineString((0, 0), (1, 1))]:
try:
nullcity.point = bad
except TypeError:
pass
else:
self.fail('Should throw a TypeError')
# Now setting with a compatible GEOS Geometry, saving, and ensuring
# the save took, notice no SRID is explicitly set.
new = Point(5, 23)
nullcity.point = new
# Ensuring that the SRID is automatically set to that of the
# field after assignment, but before saving.
self.assertEqual(4326, nullcity.point.srid)
nullcity.save()
# Ensuring the point was saved correctly after saving
self.assertEqual(new, City.objects.get(name='NullCity').point)
# Setting the X and Y of the Point
nullcity.point.x = 23
nullcity.point.y = 5
# Checking assignments pre & post-save.
self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point)
nullcity.save()
self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point)
nullcity.delete()
## Testing on a Polygon
shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0))
inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40))
# Creating a State object using a built Polygon
ply = Polygon(shell, inner)
nullstate = State(name='NullState', poly=ply)
self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None
nullstate.save()
ns = State.objects.get(name='NullState')
self.assertEqual(ply, ns.poly)
# Testing the `ogr` and `srs` lazy-geometry properties.
if gdal.HAS_GDAL:
self.assertEqual(True, isinstance(ns.poly.ogr, gdal.OGRGeometry))
self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb)
self.assertEqual(True, isinstance(ns.poly.srs, gdal.SpatialReference))
self.assertEqual('WGS 84', ns.poly.srs.name)
# Changing the interior ring on the poly attribute.
new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30))
ns.poly[1] = new_inner
ply[1] = new_inner
self.assertEqual(4326, ns.poly.srid)
ns.save()
self.assertEqual(ply, State.objects.get(name='NullState').poly)
ns.delete()