def area_polygon(request, srid='', area_id='', format='kml'): if not srid and hasattr(countries, 'area_code_lookup'): resp = countries.area_code_lookup(request, area_id, format) if resp: return resp if not re.match('\d+$', area_id): raise ViewException(format, 'Bad area ID specified', 400) if not srid: srid = 4326 if format in ('kml', 'json', 'geojson') else settings.MAPIT_AREA_SRID srid = int(srid) area = get_object_or_404(Area, id=area_id) try: simplify_tolerance = float(request.GET.get('simplify_tolerance', 0)) except ValueError: raise ViewException(format, 'Badly specified tolerance', 400) try: output, content_type = area.export(srid, format, simplify_tolerance=simplify_tolerance) if output is None: return output_json({'error': 'No polygons found'}, code=404) except SimplifiedAway: return output_json({'error': 'Simplifying removed all the polygons'}, code=404) return HttpResponse(output, content_type='%s; charset=utf-8' % content_type)
def area_polygon(request, srid='', area_id='', format='kml'): if not srid and hasattr(countries, 'area_code_lookup'): resp = countries.area_code_lookup(request, area_id, format) if resp: return resp if not re.match('\d+$', area_id): raise ViewException(format, 'Bad area ID specified', 400) if not srid: srid = 4326 if format in ('kml', 'json', 'geojson') else settings.MAPIT_AREA_SRID srid = int(srid) area = get_object_or_404(Area, id=area_id) try: simplify_tolerance = float(request.GET.get('simplify_tolerance', 0)) except ValueError: raise ViewException(format, 'Badly specified tolerance', 400) try: output, content_type = area.export(srid, format, simplify_tolerance=simplify_tolerance) if output is None: return output_json({'error': 'No polygons found'}, code=404) except TransformError as e: return output_json({'error': e.args[0]}, code=400) response = HttpResponse(content_type='%s; charset=utf-8' % content_type) response['Access-Control-Allow-Origin'] = '*' response['Cache-Control'] = 'max-age=2419200' # 4 weeks response.write(output) return response
def area_polygon(request, srid="", area_id="", format="kml"): if not srid and hasattr(countries, "area_code_lookup"): resp = countries.area_code_lookup(request, area_id, format) if resp: return resp if not re.match("\d+$", area_id): raise ViewException(format, "Bad area ID specified", 400) if not srid: srid = 4326 if format in ("kml", "json", "geojson") else settings.MAPIT_AREA_SRID srid = int(srid) area = get_object_or_404(Area, id=area_id) try: simplify_tolerance = float(request.GET.get("simplify_tolerance", 0)) except ValueError: raise ViewException(format, "Badly specified tolerance", 400) try: output, content_type = area.export(srid, format, simplify_tolerance=simplify_tolerance) if output is None: return output_json({"error": "No polygons found"}, code=404) except SimplifiedAway: return output_json({"error": "Simplifying removed all the polygons"}, code=404) return HttpResponse(output, content_type="%s; charset=utf-8" % content_type)
def postcode(request, postcode, legacy=False, format='json'): postcode = check_postcode(postcode) if isinstance(postcode, HttpResponse): return postcode try: generation = int(request.REQUEST['generation']) except: generation = Generation.objects.current() areas = Area.objects.by_postcode(postcode, generation) # Add manual enclosing areas. extra = [] for area in areas: if area.type in enclosing_areas.keys(): extra.extend(enclosing_areas[area.type]) areas = itertools.chain(areas, Area.objects.filter(id__in=extra)) if legacy: areas = dict( (area.type, area.id) for area in areas ) return output_json(areas) if format == 'html': return render_to_response('postcode.html', { 'postcode': postcode.as_dict(), 'areas': areas, }) out = postcode.as_dict() out['areas'] = dict( ( area.id, area.as_dict() ) for area in areas ) return output_json(out)
def area(request, area_id, legacy=False): if re.match('\d\d([A-Z]{2}|[A-Z]{4}|[A-Z]{2}\d\d\d|[A-Z]|[A-Z]\d\d)$', area_id): area = get_object_or_404(Area, codes__type='ons', codes__code=area_id) elif not re.match('\d+$', area_id): return output_json({ 'error': 'Bad area ID specified' }, code=400) else: area = get_object_or_404(Area, id=area_id) if isinstance(area, HttpResponse): return area return output_json( area.as_dict() )
def area_children(request, area_id, legacy=False, format='json'): area = get_object_or_404(Area, id=area_id) if isinstance(area, HttpResponse): return area generation = Generation.objects.current() children = add_codes(area.children.filter( generation_low__lte=generation, generation_high__gte=generation )) if legacy: return output_json( [ child.id for child in children ] ) if format == 'html': return output_html( children ) return output_json( dict( (child.id, child.as_dict() ) for child in children ) )
def area_touches(request, area_id, format='json'): area = get_object_or_404(Area, id=area_id) if isinstance(area, HttpResponse): return area all_areas = area.polygons.all() if len(all_areas) > 1: all_areas = all_areas.collect() elif len(all_areas) == 1: all_areas = all_areas[0].polygon else: return output_json({ 'error': 'No polygons found' }, code=404) areas = Area.objects.filter(polygons__polygon__touches=all_areas, type=area.type) if format == 'html': return output_html( areas ) return output_json( dict( (a.id, a.as_dict() ) for a in areas ) )
def deal_with_POST(request, call="areas"): url = request.POST.get("URL", "") if not url: return output_json({"error": "No content specified"}, code=400) view, args, kwargs = resolve("/%s/%s" % (call, url)) kwargs["request"] = request return view(*args, **kwargs)
def _area_geometry(area_id): area = get_object_or_404(Area, id=area_id) all_areas = area.polygons.all().collect() if not all_areas: return output_json({"error": "No polygons found"}, code=404) out = {"parts": all_areas.num_geom} if settings.MAPIT_AREA_SRID != 4326: out["srid_en"] = settings.MAPIT_AREA_SRID out["area"] = all_areas.area out["min_e"], out["min_n"], out["max_e"], out["max_n"] = all_areas.extent out["centre_e"], out["centre_n"] = all_areas.centroid all_areas.transform(4326) out["min_lon"], out["min_lat"], out["max_lon"], out["max_lat"] = all_areas.extent out["centre_lon"], out["centre_lat"] = all_areas.centroid else: out["min_lon"], out["min_lat"], out["max_lon"], out["max_lat"] = all_areas.extent out["centre_lon"], out["centre_lat"] = all_areas.centroid if hasattr(countries, "area_geometry_srid"): srid = countries.area_geometry_srid all_areas.transform(srid) out["srid_en"] = srid out["area"] = all_areas.area out["min_e"], out["min_n"], out["max_e"], out["max_n"] = all_areas.extent out["centre_e"], out["centre_n"] = all_areas.centroid return out
def deal_with_POST(request, call='areas'): url = request.POST.get('URL', '') if not url: return output_json({ 'error': 'No content specified' }, code=400) view, args, kwargs = resolve('/%s/%s' % (call, url)) kwargs['request'] = request return view(*args, **kwargs)
def nearest(request, srid, x, y, format='json'): location = Point(float(x), float(y), srid=int(srid)) set_timeout(format) try: postcode = Postcode.objects.filter( location__distance_gte=(location, D(mi=0))).distance(location).order_by('distance')[0] except QueryCanceledError: raise ViewException(format, 'That query was taking too long to compute.', 500) except DatabaseError as e: if 'canceling statement due to statement timeout' not in e.args[0]: raise raise ViewException(format, 'That query was taking too long to compute.', 500) except: raise ViewException(format, 'No postcode found near %s,%s (%s)' % (x, y, srid), 404) if format == 'html': return render(request, 'mapit/postcode.html', { 'postcode': postcode.as_dict(), 'json_view': 'mapit.views.postcodes.postcode', }) pc = postcode.as_dict() pc['distance'] = round(postcode.distance.m) return output_json({ 'postcode': pc, })
def areas_by_name(request, name, legacy=False, format='json'): generation = Generation.objects.current() try: min_generation = int(request.REQUEST['min_generation']) except: min_generation = generation type = request.REQUEST.get('type', '') args = { 'name__istartswith': name, 'generation_low__lte': generation, 'generation_high__gte': min_generation, } if ',' in type: args['type__in'] = type.split(',') elif type: args['type'] = type areas = add_codes(Area.objects.filter(**args)) if legacy: out = dict( (area.id, { 'area_id': area.id, 'name': area.name, 'type': area.type, 'parent_area_id': area.parent_area_id, }) for area in areas ) else: out = dict( ( area.id, area.as_dict() ) for area in areas ) if format == 'html': return output_html(request, 'Areas starting with %s' % name, areas) return output_json(out)
def _area_geometry(area_id): area = get_object_or_404(Area, id=area_id) if isinstance(area, HttpResponse): return area all_areas = area.polygons.all().collect() if not all_areas: return output_json({ 'error': 'No polygons found' }, code=404) out = { 'parts': all_areas.num_geom, } if int(mysociety.config.get('AREA_SRID')) != 4326: out['srid_en'] = mysociety.config.get('AREA_SRID') out['area'] = all_areas.area out['min_e'], out['min_n'], out['max_e'], out['max_n'] = all_areas.extent out['centre_e'], out['centre_n'] = all_areas.centroid all_areas.transform(4326) out['min_lon'], out['min_lat'], out['max_lon'], out['max_lat'] = all_areas.extent out['centre_lon'], out['centre_lat'] = all_areas.centroid elif mysociety.config.get('COUNTRY') == 'NO': out['min_lon'], out['min_lat'], out['max_lon'], out['max_lat'] = all_areas.extent out['centre_lon'], out['centre_lat'] = all_areas.centroid all_areas.transform(32633) out['srid_en'] = 32633 out['area'] = all_areas.area out['min_e'], out['min_n'], out['max_e'], out['max_n'] = all_areas.extent out['centre_e'], out['centre_n'] = all_areas.centroid return out
def partial_postcode(request, postcode, format='json'): postcode = re.sub(r'\s+', '', postcode.upper()) if is_valid_postcode(postcode): postcode = re.sub(r'\d[A-Z]{2}$', '', postcode) if not is_valid_partial_postcode(postcode): raise ViewException(format, "Partial postcode '%s' is not valid." % postcode, 400) location = Postcode.objects.filter(postcode__startswith=postcode).extra( where=['length(postcode) = %d' % (len(postcode) + 3)]).aggregate( Collect('location'))['location__collect'] if not location: raise ViewException(format, 'Postcode not found', 404) postcode = Postcode(postcode=postcode, location=location.centroid) if format == 'html': return render( request, 'mapit/postcode.html', { 'postcode': postcode.as_dict(), 'json_view': 'mapit-postcode-partial', }) return output_json(postcode.as_dict())
def areas_by_name(request, name, format='json'): generation = request.REQUEST.get('generation', Generation.objects.current()) if not generation: generation = Generation.objects.current() try: min_generation = int(request.REQUEST['min_generation']) except: min_generation = generation type = request.REQUEST.get('type', '') args = { 'name__istartswith': name, 'generation_low__lte': generation, 'generation_high__gte': min_generation, } if ',' in type: args['type__code__in'] = type.split(',') elif type: args['type__code'] = type areas = add_codes(Area.objects.filter(**args)) if format == 'html': return output_html(request, 'Areas starting with %s' % name, areas) out = dict((area.id, area.as_dict()) for area in areas) return output_json(out)
def _area_geometry(area_id): area = get_object_or_404(Area, id=area_id) all_areas = area.polygons.all().collect() if not all_areas: return output_json({'error': 'No polygons found'}, code=404) out = { 'parts': all_areas.num_geom, } if settings.MAPIT_AREA_SRID != 4326: out['srid_en'] = settings.MAPIT_AREA_SRID out['area'] = all_areas.area out['min_e'], out['min_n'], out['max_e'], out['max_n'] = all_areas.extent out['centre_e'], out['centre_n'] = all_areas.centroid all_areas.transform(4326) out['min_lon'], out['min_lat'], out['max_lon'], out['max_lat'] = all_areas.extent out['centre_lon'], out['centre_lat'] = all_areas.centroid else: out['min_lon'], out['min_lat'], out['max_lon'], out['max_lat'] = all_areas.extent out['centre_lon'], out['centre_lat'] = all_areas.centroid if hasattr(countries, 'area_geometry_srid'): srid = countries.area_geometry_srid all_areas.transform(srid) out['srid_en'] = srid out['area'] = all_areas.area out['min_e'], out['min_n'], out['max_e'], out['max_n'] = all_areas.extent out['centre_e'], out['centre_n'] = all_areas.centroid return out
def areas_by_type(request, type, format='json'): generation = request.REQUEST.get('generation', Generation.objects.current()) if not generation: generation = Generation.objects.current() try: min_generation = int(request.REQUEST['min_generation']) except: min_generation = generation args = {} if ',' in type: args['type__code__in'] = type.split(',') elif type: args['type__code'] = type if min_generation == -1: areas = add_codes(Area.objects.filter(**args)) else: args['generation_low__lte'] = generation args['generation_high__gte'] = min_generation areas = add_codes(Area.objects.filter(**args)) if format == 'html': return output_html(request, 'Areas in %s' % type, areas) return output_json(dict((a.id, a.as_dict()) for a in areas))
def get_voting_areas_info(request, area_ids): area_ids = area_ids.split(',') out = {} for id in area_ids: area = _get_voting_area_info(id) out[id] = {} if isinstance(area, HttpResponse) else area return output_json(out)
def deal_with_POST(request, call='areas'): url = request.POST.get('URL', '') if not url: return output_json({'error': 'No content specified'}, code=400) view, args, kwargs = resolve('/%s/%s' % (call, url)) kwargs['request'] = request return view(*args, **kwargs)
def _area_geometry(area_id): area = get_object_or_404(Area, id=area_id) if isinstance(area, HttpResponse): return area all_areas = area.polygons.all().collect() if not all_areas: return output_json({ 'error': 'No polygons found' }, code=404) out = { 'parts': all_areas.num_geom, } if settings.MAPIT_AREA_SRID != 4326: out['srid_en'] = settings.MAPIT_AREA_SRID out['area'] = all_areas.area out['min_e'], out['min_n'], out['max_e'], out['max_n'] = all_areas.extent out['centre_e'], out['centre_n'] = all_areas.centroid all_areas.transform(4326) out['min_lon'], out['min_lat'], out['max_lon'], out['max_lat'] = all_areas.extent out['centre_lon'], out['centre_lat'] = all_areas.centroid else: out['min_lon'], out['min_lat'], out['max_lon'], out['max_lat'] = all_areas.extent out['centre_lon'], out['centre_lat'] = all_areas.centroid if hasattr(countries, 'area_geometry_srid'): srid = countries.area_geometry_srid all_areas.transform(srid) out['srid_en'] = srid out['area'] = all_areas.area out['min_e'], out['min_n'], out['max_e'], out['max_n'] = all_areas.extent out['centre_e'], out['centre_n'] = all_areas.centroid return out
def nearest(request, srid, x, y, format='json'): location = Point(float(x), float(y), srid=int(srid)) set_timeout(format) try: postcode = Postcode.objects.filter( location__distance_gte=(location, D( mi=0))).distance(location).order_by('distance')[0] except DatabaseError as e: if 'Cannot find SRID' in e.args[0]: raise ViewException(format, e.args[0], 400) if 'canceling statement due to statement timeout' not in e.args[0]: raise raise ViewException(format, 'That query was taking too long to compute.', 500) except: raise ViewException(format, 'No postcode found near %s,%s (%s)' % (x, y, srid), 404) if format == 'html': return render(request, 'mapit/postcode.html', { 'postcode': postcode.as_dict(), 'json_view': 'mapit-postcode', }) pc = postcode.as_dict() pc['distance'] = round(postcode.distance.m) return output_json({ 'postcode': pc, })
def postcode(request, postcode, format=None): if hasattr(countries, 'canonical_postcode'): canon_postcode = countries.canonical_postcode(postcode) postcode = canon_postcode # if (postcode != canon_postcode and format is None) or format == 'json': # return redirect('mapit.views.postcodes.postcode', postcode=canon_postcode) if format is None: format = 'json' if not is_valid_postcode(postcode): raise ViewException(format, "Postcode '%s' is not valid." % postcode, 400) postcode = get_object_or_404(Postcode, format=format, postcode=postcode) try: generation = int(request.GET['generation']) except: generation = Generation.objects.current() if not hasattr(countries, 'is_special_postcode') or not countries.is_special_postcode( postcode.postcode): areas = list(add_codes(Area.objects.by_postcode(postcode, generation))) else: areas = [] # Shortcuts shortcuts = {} for area in areas: if area.type.code in ('COP', 'LBW', 'LGE', 'MTW', 'UTE', 'UTW'): shortcuts['ward'] = area.id shortcuts['council'] = area.parent_area_id elif area.type.code == 'CED': shortcuts.setdefault('ward', {})['county'] = area.id shortcuts.setdefault('council', {})['county'] = area.parent_area_id elif area.type.code == 'DIW': shortcuts.setdefault('ward', {})['district'] = area.id shortcuts.setdefault('council', {})['district'] = area.parent_area_id elif area.type.code in ('WMC', ): # XXX Also maybe 'EUR', 'NIE', 'SPC', 'SPE', 'WAC', 'WAE', 'OLF', 'OLG', 'OMF', 'OMG'): shortcuts[area.type.code] = area.id # Add manual enclosing areas. extra = [] for area in areas: if area.type.code in enclosing_areas.keys(): extra.extend(enclosing_areas[area.type.code]) areas = itertools.chain(areas, Area.objects.filter(id__in=extra)) if format == 'html': return render( request, 'mapit/postcode.html', { 'postcode': postcode.as_dict(), 'areas': areas, 'json_view': 'mapit-postcode', }) out = postcode.as_dict() out['areas'] = dict((area.id, area.as_dict()) for area in areas) if shortcuts: out['shortcuts'] = shortcuts return output_json(out)
def area_polygon(request, srid='', area_id='', format='kml'): if not srid: srid = 4326 if format in ('kml', 'json', 'geojson') else int(mysociety.config.get('AREA_SRID')) srid = int(srid) area = get_object_or_404(Area, id=area_id) if isinstance(area, HttpResponse): return area all_areas = area.polygons.all() if len(all_areas) > 1: all_areas = all_areas.collect() elif len(all_areas) == 1: all_areas = all_areas[0].polygon else: return output_json({ 'error': 'No polygons found' }, code=404) if srid != int(mysociety.config.get('AREA_SRID')): all_areas.transform(srid) if format=='kml': out = '''<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Placemark> <name>%s</name> %s </Placemark> </kml>''' % (area.name, all_areas.kml) content_type = 'application/vnd.google-earth.kml+xml' elif format in ('json', 'geojson'): out = all_areas.json content_type = 'application/json' elif format=='wkt': out = all_areas.wkt content_type = 'text/plain' return HttpResponse(out, content_type='%s; charset=utf-8' % content_type)
def output_areas(request, title, format, areas, **kwargs): areas = add_codes(areas) if format == 'map.html': format = 'html' kwargs['show_map'] = True if format == 'html': return output_html(request, title, areas, **kwargs) return output_json(iterdict((area.id, area.as_dict()) for area in areas))
def postcode(request, postcode, legacy=False, format='json'): postcode = check_postcode(format, postcode) if isinstance(postcode, HttpResponse): return postcode try: generation = int(request.REQUEST['generation']) except: generation = Generation.objects.current() areas = Area.objects.by_postcode(postcode, generation) # Shortcuts shortcuts = {} for area in areas: if area.type in ('COP','LBW','LGE','MTW','UTE','UTW'): shortcuts['ward'] = area.id shortcuts['council'] = area.parent_area_id elif area.type == 'CED': shortcuts.setdefault('ward', {})['county'] = area.id shortcuts.setdefault('council', {})['county'] = area.parent_area_id elif area.type == 'DIW': shortcuts.setdefault('ward', {})['district'] = area.id shortcuts.setdefault('council', {})['district'] = area.parent_area_id elif area.type in ('WMC'): # XXX Also maybe 'EUR', 'NIE', 'SPC', 'SPE', 'WAC', 'WAE', 'OLF', 'OLG', 'OMF', 'OMG'): shortcuts[area.type] = area.id # Add manual enclosing areas. extra = [] for area in areas: if area.type in enclosing_areas.keys(): extra.extend(enclosing_areas[area.type]) areas = itertools.chain(areas, Area.objects.filter(id__in=extra)) if legacy: areas = dict( (area.type, area.id) for area in areas ) return output_json(areas) if format == 'html': return render_to_response('postcode.html', { 'postcode': postcode.as_dict(), 'areas': areas, 'json': '/postcode/', }) out = postcode.as_dict() out['areas'] = dict( ( area.id, area.as_dict() ) for area in areas ) if shortcuts: out['shortcuts'] = shortcuts return output_json(out)
def areas_by_point(request, srid, x, y, bb=False, format='json'): type = request.REQUEST.get('type', '') generation = request.REQUEST.get('generation', Generation.objects.current()) if not generation: generation = Generation.objects.current() location = Point(float(x), float(y), srid=int(srid)) gdal.UseExceptions() try: location.transform(settings.MAPIT_AREA_SRID, clone=True) except: raise ViewException(format, 'Point outside the area geometry', 400) method = 'box' if bb and bb != 'polygon' else 'polygon' args = { 'generation_low__lte': generation, 'generation_high__gte': generation } if ',' in type: args['type__code__in'] = type.split(',') elif type: args['type__code'] = type if type and method == 'polygon': args = dict(("area__%s" % k, v) for k, v in args.items()) # So this is odd. It doesn't matter if you specify types, PostGIS will # do the contains test on all the geometries matching the bounding-box # index, even if it could be much quicker to filter some out first # (ie. the EUR ones). args['polygon__bbcontains'] = location shapes = Geometry.objects.filter(**args).defer('polygon') areas = [] for shape in shapes: try: areas.append( Area.objects.get(polygons__id=shape.id, polygons__polygon__contains=location)) except: pass else: if method == 'box': args['polygons__polygon__bbcontains'] = location else: geoms = list( Geometry.objects.filter( polygon__contains=location).defer('polygon')) args['polygons__in'] = geoms areas = Area.objects.filter(**args) areas = add_codes(areas) if format == 'html': return output_html(request, 'Areas covering the point (%s,%s)' % (x, y), areas, indent_areas=True) return output_json(dict((area.id, area.as_dict()) for area in areas))
def areas_geometry(request, area_ids): area_ids = area_ids.split(',') out = {} for id in area_ids: area = _area_geometry(id) if isinstance(area, HttpResponse): area = {} out[id] = area return output_json(out)
def area_polygon(request, srid='', area_id='', format='kml'): if not srid and hasattr(countries, 'area_code_lookup'): resp = countries.area_code_lookup(area_id, format) if resp: return resp if not re.match('\d+$', area_id): return output_error(format, 'Bad area ID specified', 400) if not srid: srid = 4326 if format in ('kml', 'json', 'geojson') else settings.MAPIT_AREA_SRID srid = int(srid) area = get_object_or_404(Area, id=area_id) if isinstance(area, HttpResponse): return area all_areas = area.polygons.all() if len(all_areas) > 1: all_areas = all_areas.collect() elif len(all_areas) == 1: all_areas = all_areas[0].polygon else: return output_json({ 'error': 'No polygons found' }, code=404) if srid != settings.MAPIT_AREA_SRID: all_areas.transform(srid) try: simplify_tolerance = float(request.GET.get('simplify_tolerance', 0)) except: return output_error(format, 'Badly specified tolerance', 400) if simplify_tolerance: all_areas = all_areas.simplify(simplify_tolerance) if format=='kml': out = '''<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Style id="transBluePoly"> <LineStyle> <color>70ff0000</color> <width>2</width> </LineStyle> <PolyStyle> <color>3dff5500</color> </PolyStyle> </Style> <Placemark> <styleUrl>#transBluePoly</styleUrl> <name>%s</name> %s </Placemark> </kml>''' % (escape(area.name), all_areas.kml) content_type = 'application/vnd.google-earth.kml+xml' elif format in ('json', 'geojson'): out = all_areas.json content_type = 'application/json' elif format=='wkt': out = all_areas.wkt content_type = 'text/plain' return HttpResponse(out, content_type='%s; charset=utf-8' % content_type)
def area_polygon(request, srid='', area_id='', format='kml'): if not srid and hasattr(countries, 'area_code_lookup'): resp = countries.area_code_lookup(request, area_id, format) if resp: return resp args = query_args_polygon(request, format, srid, [area_id]) area = get_object_or_404(Area, id=area_id) try: output, content_type = area.export(args['srid'], format, simplify_tolerance=args['simplify_tolerance']) if output is None: return output_json({'error': _('No polygons found')}, code=404) except TransformError as e: return output_json({'error': e.args[0]}, code=400) return output_polygon(content_type, output)
def areas_polygon(request, area_ids, srid='', format='kml'): area_ids = area_ids.split(',') args = query_args_polygon(request, format, srid, area_ids) areas = list(Area.objects.filter(id__in=area_ids)) if not areas: return output_json({'error': _('No areas found')}, code=404) serialiser = GeometrySerialiser(areas, args['srid'], args['simplify_tolerance']) try: if format == 'kml': output, content_type = serialiser.kml('full') elif format == 'geojson': output, content_type = serialiser.geojson() except TransformError as e: return output_json({'error': e.args[0]}, code=400) return output_polygon(content_type, output)
def areas_polygon(request, area_ids, srid='', format='kml'): area_ids = area_ids.split(',') check_area_ids(format, area_ids) areas = list(Area.objects.filter(id__in=area_ids)) if not areas: return output_json({'error': _('No areas found')}, code=404) return _areas_polygon(request, format, areas, srid)
def area_polygon(request, srid='', area_id='', format='kml'): if not srid and hasattr(countries, 'area_code_lookup'): resp = countries.area_code_lookup(area_id, format) if resp: return resp if not re.match('\d+$', area_id): raise ViewException(format, 'Bad area ID specified', 400) if not srid: srid = 4326 if format in ('kml', 'json', 'geojson') else settings.MAPIT_AREA_SRID srid = int(srid) area = get_object_or_404(Area, id=area_id) all_areas = area.polygons.all() if len(all_areas) > 1: all_areas = all_areas.collect() elif len(all_areas) == 1: all_areas = all_areas[0].polygon else: return output_json({ 'error': 'No polygons found' }, code=404) if srid != settings.MAPIT_AREA_SRID: all_areas.transform(srid) try: simplify_tolerance = float(request.GET.get('simplify_tolerance', 0)) except: raise ViewException(format, 'Badly specified tolerance', 400) if simplify_tolerance: all_areas = all_areas.simplify(simplify_tolerance) if format=='kml': out = '''<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> <Style id="transBluePoly"> <LineStyle> <color>70ff0000</color> <width>2</width> </LineStyle> <PolyStyle> <color>3dff5500</color> </PolyStyle> </Style> <Placemark> <styleUrl>#transBluePoly</styleUrl> <name>%s</name> %s </Placemark> </kml>''' % (escape(area.name), all_areas.kml) content_type = 'application/vnd.google-earth.kml+xml' elif format in ('json', 'geojson'): out = all_areas.json content_type = 'application/json' elif format=='wkt': out = all_areas.wkt content_type = 'text/plain' return HttpResponse(out, content_type='%s; charset=utf-8' % content_type)
def postcode(request, postcode, format=None): if hasattr(countries, 'canonical_postcode'): canon_postcode = countries.canonical_postcode(postcode) postcode = canon_postcode # if (postcode != canon_postcode and format is None) or format == 'json': # return redirect('mapit.views.postcodes.postcode', postcode=canon_postcode) if format is None: format = 'json' if not is_valid_postcode(postcode): raise ViewException(format, "Postcode '%s' is not valid." % postcode, 400) postcode = get_object_or_404(Postcode, format=format, postcode=postcode) try: generation = int(request.GET['generation']) except: generation = Generation.objects.current() if not hasattr(countries, 'is_special_postcode') or not countries.is_special_postcode(postcode.postcode): areas = list(add_codes(Area.objects.by_postcode(postcode, generation))) else: areas = [] # Shortcuts shortcuts = {} for area in areas: if area.type.code in ('COP', 'LBW', 'LGE', 'MTW', 'UTE', 'UTW'): shortcuts['ward'] = area.id shortcuts['council'] = area.parent_area_id elif area.type.code == 'CED': shortcuts.setdefault('ward', {})['county'] = area.id shortcuts.setdefault('council', {})['county'] = area.parent_area_id elif area.type.code == 'DIW': shortcuts.setdefault('ward', {})['district'] = area.id shortcuts.setdefault('council', {})['district'] = area.parent_area_id elif area.type.code in ('WMC',): # XXX Also maybe 'EUR', 'NIE', 'SPC', 'SPE', 'WAC', 'WAE', 'OLF', 'OLG', 'OMF', 'OMG'): shortcuts[area.type.code] = area.id # Add manual enclosing areas. extra = [] for area in areas: if area.type.code in enclosing_areas.keys(): extra.extend(enclosing_areas[area.type.code]) areas = itertools.chain(areas, Area.objects.filter(id__in=extra)) if format == 'html': return render(request, 'mapit/postcode.html', { 'postcode': postcode.as_dict(), 'areas': areas, 'json_view': 'mapit-postcode', }) out = postcode.as_dict() out['areas'] = dict((area.id, area.as_dict()) for area in areas) if shortcuts: out['shortcuts'] = shortcuts return output_json(out)
def partial_postcode(request, postcode, format='json'): postcode = re.sub('\s+', '', postcode.upper()) if is_valid_postcode(postcode): postcode = re.sub('\d[A-Z]{2}$', '', postcode) if not is_valid_partial_postcode(postcode): return bad_request("Partial postcode '%s' is not valid." % postcode) try: postcode = Postcode( postcode = postcode, location = Postcode.objects.filter(postcode__startswith=postcode).collect().centroid ) except: return output_json({ 'error': 'Postcode not found' }, code=404) if format == 'html': return render_to_response('postcode.html', { 'postcode': postcode.as_dict(), }) return output_json(postcode.as_dict())
def area_children(request, area_id, legacy=False, format='json'): area = get_object_or_404(Area, format=format, id=area_id) if isinstance(area, HttpResponse): return area generation = Generation.objects.current() args = { 'generation_low__lte': generation, 'generation_high__gte': generation, } type = request.REQUEST.get('type', '') if ',' in type: args['type__in'] = type.split(',') elif type: args['type'] = type children = add_codes(area.children.filter(**args)) if legacy: return output_json( [ child.id for child in children ] ) if format == 'html': return output_html(request, 'Children of %s' % area.name, children) return output_json( dict( (child.id, child.as_dict() ) for child in children ) )
def example_postcode_for_area(request, area_id, legacy=False): area = get_object_or_404(Area, id=area_id) if isinstance(area, HttpResponse): return area try: pc = Postcode.objects.filter(areas=area).order_by('?')[0] except: try: pc = Postcode.objects.filter(location__contained=area.polygons.all().collect()).order_by('?')[0] except: pc = None if pc: pc = pc.get_postcode_display() return output_json(pc)
def areas_by_point(request, srid, x, y, bb=False, legacy=False, format='json'): type = request.REQUEST.get('type', '') generation = request.REQUEST.get('generation', Generation.objects.current()) if not generation: generation = Generation.objects.current() location = Point(float(x), float(y), srid=int(srid)) method = 'box' if bb and bb != 'polygon' else 'polygon' args = { 'generation_low__lte': generation, 'generation_high__gte': generation } if ',' in type: args['type__in'] = type.split(',') elif type: args['type'] = type if type and method == 'polygon': args = dict( ("area__%s" % k, v) for k, v in args.items() ) # So this is odd. It doesn't matter if you specify types, PostGIS will # do the contains test on all the geometries matching the bounding-box # index, even if it could be much quicker to filter some out first # (ie. the EUR ones). args['polygon__bbcontains'] = location shapes = Geometry.objects.filter(**args).defer('polygon') areas = [] for shape in shapes: try: areas.append( Area.objects.get(polygons__id=shape.id, polygons__polygon__contains=location) ) except: pass else: if method == 'box': args['polygons__polygon__bbcontains'] = location else: geoms = list(Geometry.objects.filter(polygon__contains=location).defer('polygon')) args['polygons__in'] = geoms areas = Area.objects.filter(**args) if legacy: return output_json( dict( (area.id, area.type) for area in areas ) ) if format == 'html': return output_html(request, 'Areas containing (%s,%s)' % (x,y), areas) return output_json( dict( (area.id, area.as_dict() ) for area in areas ) )
def _areas_polygon(request, format, areas, srid=None): args = query_args_polygon(request, format, srid) serialiser = GeometrySerialiser(list(areas), args['srid'], args['simplify_tolerance']) try: if format == 'kml': output, content_type = serialiser.kml('full') elif format == 'geojson': output, content_type = serialiser.geojson() except TransformError as e: return output_json({'error': e.args[0]}, code=400) return output_polygon(content_type, output)
def areas_by_type(request, type, legacy=False, format='json'): generation = Generation.objects.current() try: min_generation = int(request.REQUEST['min_generation']) except: min_generation = generation args = {} if ',' in type: args['type__in'] = type.split(',') elif type: args['type'] = type if min_generation == -1: areas = add_codes(Area.objects.filter(**args)) else: args['generation_low__lte'] = generation args['generation_high__gte'] = min_generation areas = add_codes(Area.objects.filter(**args)) if format == 'html': return output_html(request, 'Areas in %s' % type, areas) elif legacy: return output_json( [ a.id for a in areas ] ) return output_json( dict( (a.id, a.as_dict() ) for a in areas ) )
def postcode(request, postcode, format='json'): postcode = check_postcode(format, postcode) if isinstance(postcode, HttpResponse): return postcode try: generation = int(request.REQUEST['generation']) except: generation = Generation.objects.current() if not hasattr(countries, 'is_special_postcode') or not countries.is_special_postcode( postcode.postcode): areas = Area.objects.by_postcode(postcode, generation) else: areas = [] # Shortcuts shortcuts = {} for area in areas: if area.type.code in ('COP', 'LBW', 'LGE', 'MTW', 'UTE', 'UTW'): shortcuts['ward'] = area.id shortcuts['council'] = area.parent_area_id elif area.type.code == 'CED': shortcuts.setdefault('ward', {})['county'] = area.id shortcuts.setdefault('council', {})['county'] = area.parent_area_id elif area.type.code == 'DIW': shortcuts.setdefault('ward', {})['district'] = area.id shortcuts.setdefault('council', {})['district'] = area.parent_area_id elif area.type.code in ( 'WMC' ): # XXX Also maybe 'EUR', 'NIE', 'SPC', 'SPE', 'WAC', 'WAE', 'OLF', 'OLG', 'OMF', 'OMG'): shortcuts[area.type.code] = area.id # Add manual enclosing areas. extra = [] for area in areas: if area.type.code in enclosing_areas.keys(): extra.extend(enclosing_areas[area.type.code]) areas = itertools.chain(areas, Area.objects.filter(id__in=extra)) if format == 'html': return render_to_response('mapit/postcode.html', { 'postcode': postcode.as_dict(), 'areas': areas, 'json': '/postcode/', }) out = postcode.as_dict() out['areas'] = dict((area.id, area.as_dict()) for area in areas) if shortcuts: out['shortcuts'] = shortcuts return output_json(out)
def process_exception(self, request, exception): if not isinstance(exception, ViewException): return None format, message, code = exception.args if format == 'html': types = { 400: http.HttpResponseBadRequest, 404: http.HttpResponseNotFound, 500: http.HttpResponseServerError, } response_type = types.get(code, http.HttpResponse) return response_type( render_to_string('mapit/%s.html' % code, {'error': message}, request=request)) return output_json({'error': message}, code=code)
def area_intersect(query_type, title, request, area_id, format): area = get_object_or_404(Area, format=format, id=area_id) if isinstance(area, HttpResponse): return area if not area.polygons.count(): return output_error(format, 'No polygons found', 404) generation = Generation.objects.current() args = { 'generation_low__lte': generation, 'generation_high__gte': generation, } type = request.REQUEST.get('type', '') if ',' in type: args['type__code__in'] = type.split(',') elif type: args['type__code'] = type elif area.type.code in ('EUR'): args['type__code'] = area.type.code set_timeout(format) areas = Area.objects.intersect( query_type, area).exclude(id=area.id).filter(**args).distinct() try: if format == 'html': return output_html(request, title % ('<a href="/area/%d.html">%s</a>' % (area.id, area.name)), areas, norobots=True) return output_json(dict((a.id, a.as_dict()) for a in areas)) except QueryCanceledError: return output_error( format, 'That query was taking too long to compute - try restricting to a specific type, if you weren\'t already doing so.', 500) except DatabaseError, e: # Django 1.2+ catches QueryCanceledError and throws its own DatabaseError instead if 'canceling statement due to statement timeout' not in e.args[0]: raise return output_error( format, 'That query was taking too long to compute - try restricting to a specific type, if you weren\'t already doing so.', 500)
def area(request, area_id, format='json'): if hasattr(countries, 'area_code_lookup'): resp = countries.area_code_lookup(area_id, format) if resp: return resp if not re.match('\d+$', area_id): return output_error(format, 'Bad area ID specified', 400) area = get_object_or_404(Area, format=format, id=area_id) if isinstance(area, HttpResponse): return area if format == 'html': return render( request, 'mapit/area.html', { 'area': area, 'show_geometry': (area.type.code not in ('EUR', 'SPE', 'WAE')) }) return output_json(area.as_dict())
def example_postcode_for_area(request, area_id, format='json'): area = get_object_or_404(Area, format=format, id=area_id) try: pc = Postcode.objects.filter(areas=area).order_by()[0] except: set_timeout(format) try: pc = Postcode.objects.filter_by_area(area).order_by()[0] except DatabaseError as e: if 'canceling statement due to statement timeout' not in e.args[0]: raise raise ViewException(format, 'That query was taking too long to compute.', 500) except: pc = None if pc: pc = pc.get_postcode_display() if format == 'html': return render(request, 'mapit/example-postcode.html', {'area': area, 'postcode': pc}) return output_json(pc)
def area(request, area_id, format=''): if hasattr(countries, 'area_code_lookup'): resp = countries.area_code_lookup(request, area_id, format) if resp: return resp if not re.match(r'\d+$', area_id): raise ViewException(format, _('Bad area ID specified'), 400) area = get_object_or_404(Area, format=format, id=area_id) codes = [] for code_type, code in sorted(area.all_codes.items()): code_link = None if code_type in ('osm', 'osm_rel'): code_link = 'http://www.openstreetmap.org/browse/relation/' + code elif code_type == 'osm_way': code_link = 'http://www.openstreetmap.org/browse/way/' + code codes.append((code_type, code, code_link)) # Sort any alternative names by the description of the name (the # English name of the language for global MapIt) and exclude the # default OSM name, since if that exists, it'll already be # displayed as the page title. names = Name.objects.filter(area=area).select_related() alternative_names = sorted((n.type.description, n.name) for n in names if n.type.code != "default") geotype = {} if hasattr(countries, 'restrict_geo_html'): geotype = countries.restrict_geo_html(area) if format == 'html': return render( request, 'mapit/area.html', { 'area': area, 'codes': codes, 'alternative_names': alternative_names, 'geotype': geotype, }) return output_json(area.as_dict(names))
def area_children(request, area_id, format='json'): area = get_object_or_404(Area, format=format, id=area_id) generation = request.REQUEST.get('generation', Generation.objects.current()) if not generation: generation = Generation.objects.current() args = { 'generation_low__lte': generation, 'generation_high__gte': generation, } type = request.REQUEST.get('type', '') if ',' in type: args['type__code__in'] = type.split(',') elif type: args['type__code'] = type children = add_codes(area.children.filter(**args)) if format == 'html': return output_html(request, 'Children of %s' % area.name, children) return output_json( dict( (child.id, child.as_dict() ) for child in children ) )
def nearest(request, srid, x, y, format='json'): location = Point(float(x), float(y), srid=int(srid)) set_timeout(format) try: # Transform to database SRID for comparison (GeometryCentroidDistance does not yet do this) location.transform(4326) except: raise ViewException(format, _('Point outside the area geometry'), 400) try: # Ordering will be in 'degrees', so fetch a few and sort by actual distance postcodes = Postcode.objects.annotate( centroid_distance=GeometryCentroidDistance( 'location', location)).annotate(distance=Distance( 'location', location)).order_by('centroid_distance')[:100] postcodes = sorted(postcodes, key=attrgetter('distance')) postcode = postcodes[0] except DatabaseError as e: if 'Cannot find SRID' in e.args[0]: raise ViewException(format, e.args[0], 400) if 'canceling statement due to statement timeout' not in e.args[0]: raise raise ViewException(format, 'That query was taking too long to compute.', 500) except: raise ViewException(format, 'No postcode found near %s,%s (%s)' % (x, y, srid), 404) if format == 'html': return render(request, 'mapit/postcode.html', { 'postcode': postcode.as_dict(), 'json_view': 'mapit-postcode', }) pc = postcode.as_dict() pc['distance'] = round(postcode.distance.m) return output_json({ 'postcode': pc, })
def partial_postcode(request, postcode, format='json'): postcode = re.sub('\s+', '', postcode.upper()) if is_valid_postcode(postcode): postcode = re.sub('\d[A-Z]{2}$', '', postcode) if not is_valid_partial_postcode(postcode): return bad_request(format, "Partial postcode '%s' is not valid." % postcode) try: postcode = Postcode( postcode=postcode, location=Postcode.objects.filter( postcode__startswith=postcode).extra( where=['length(postcode) = %d' % (len(postcode) + 3)]).collect().centroid) except: return output_error(format, 'Postcode not found', 404) if format == 'html': return render_to_response('mapit/postcode.html', { 'postcode': postcode.as_dict(), 'json': '/postcode/partial/', }) return output_json(postcode.as_dict())
def generations(request): generations = Generation.objects.all() return output_json(dict((g.id, g.as_dict()) for g in generations))
raise ViewException( format, 'That query was taking too long to compute - try restricting to a specific type, if you weren\'t already doing so.', 500) except InternalError: raise ViewException( format, 'There was an internal error performing that query.', 500) if format == 'html': return output_html(request, title % ('<a href="%sarea/%d.html">%s</a>' % (reverse('mapit_index'), area.id, area.name)), areas, norobots=True) return output_json(dict((a.id, a.as_dict()) for a in areas)) @ratelimit(minutes=3, requests=100) def area_touches(request, area_id, format='json'): return area_intersect('touches', 'Areas touching %s', request, area_id, format) @ratelimit(minutes=3, requests=100) def area_overlaps(request, area_id, format='json'): return area_intersect('overlaps', 'Areas overlapping %s', request, area_id, format) @ratelimit(minutes=3, requests=100)
def generations(request, format='json'): generations = Generation.objects.all() if format == 'html': return render(request, 'mapit/generations.html', {'generations': generations}) return output_json(dict((g.id, g.as_dict()) for g in generations))
def areas(request, area_ids, format='json'): area_ids = area_ids.split(',') areas = add_codes(Area.objects.filter(id__in=area_ids)) if format == 'html': return output_html(request, 'Areas ID lookup', areas) return output_json(dict((area.id, area.as_dict()) for area in areas))
def area_geometry(request, area_id): area = _area_geometry(area_id) if isinstance(area, HttpResponse): return area return output_json(area)