def test04b_related_union_aggregate(self): "Testing the `unionagg` GeoQuerySet aggregates on related geographic models." # This combines the Extent and Union aggregates into one query aggs = City.objects.aggregate(Union('location__point')) # These are the points that are components of the aggregate geographic # union that is returned. Each point # corresponds to City PK. p1 = Point(-104.528056, 33.387222) p2 = Point(-97.516111, 33.058333) p3 = Point(-79.460734, 40.18476) p4 = Point(-96.801611, 32.782057) p5 = Point(-95.363151, 29.763374) # Creating the reference union geometry depending on the spatial backend, # as Oracle will have a different internal ordering of the component # geometries than PostGIS. The second union aggregate is for a union # query that includes limiting information in the WHERE clause (in other # words a `.filter()` precedes the call to `.unionagg()`). if oracle: ref_u1 = MultiPoint(p4, p5, p3, p1, p2, srid=4326) ref_u2 = MultiPoint(p3, p2, srid=4326) else: # Looks like PostGIS points by longitude value. ref_u1 = MultiPoint(p1, p2, p4, p5, p3, srid=4326) ref_u2 = MultiPoint(p2, p3, srid=4326) u1 = City.objects.unionagg(field_name='location__point') u2 = City.objects.exclude(name__in=('Roswell', 'Houston', 'Dallas', 'Fort Worth')).unionagg( field_name='location__point') u3 = aggs['location__point__union'] self.assertEqual(ref_u1, u1) self.assertEqual(ref_u2, u2) self.assertEqual(ref_u1, u3)
def get_search_context(radius, obj_type=None, from_date=None, to_date=None, points=None): points_list = [] multi_points = MultiPoint(Point(55.752071, 48.744513)) if points: points_list = json.loads(points) multi_points = MultiPoint( *[Point(x=long, y=lat) for long, lat in points_list], srid=4326 ) kwargs = dict( multi_point=multi_points, radius=radius, obj_type=obj_type, fields=['point', 'active', 'date', 'image_url', 'description', 'contacts'] ) if from_date: kwargs.update(from_date=datetime.date.fromisoformat(from_date)) if to_date: kwargs.update(to_date=datetime.date.fromisoformat(to_date)) images = Image.get_objects(**kwargs) image_count, not_active_image_count = update_images_for_context(images) message = get_message(image_count) message = message + f' из них на модерации: {not_active_image_count}' return { "images": images, "from_date": from_date, "to_date": to_date, "radius": float(radius), "points": points_list, "message": message, "opencage_key": OPENCAGE_KEY, }
class MultiPointFieldDefinitionTest(GeometryFieldDefinitionTestMixin, BaseModelDefinitionTestCase): field_definition_cls_name = 'MultiPointFieldDefinition' field_values = ( MultiPoint(Point(0, 0), Point(1, 1)), MultiPoint(Point(5, 23), Point(13, 37), Point(13, 58)), )
def test_related_union_aggregate(self): "Testing the `unionagg` GeoQuerySet aggregates on related geographic models." # This combines the Extent and Union aggregates into one query aggs = City.objects.aggregate(Union('location__point')) # These are the points that are components of the aggregate geographic # union that is returned. Each point # corresponds to City PK. p1 = Point(-104.528056, 33.387222) p2 = Point(-97.516111, 33.058333) p3 = Point(-79.460734, 40.18476) p4 = Point(-96.801611, 32.782057) p5 = Point(-95.363151, 29.763374) # The second union aggregate is for a union # query that includes limiting information in the WHERE clause (in other # words a `.filter()` precedes the call to `.unionagg()`). ref_u1 = MultiPoint(p1, p2, p4, p5, p3, srid=4326) ref_u2 = MultiPoint(p2, p3, srid=4326) u1 = City.objects.unionagg(field_name='location__point') u2 = City.objects.exclude( name__in=('Roswell', 'Houston', 'Dallas', 'Fort Worth'), ).unionagg(field_name='location__point') u3 = aggs['location__point__union'] self.assertEqual(type(u1), MultiPoint) self.assertEqual(type(u3), MultiPoint) # Ordering of points in the result of the union is not defined and # implementation-dependent (DB backend, GEOS version) self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u1}) self.assertSetEqual({p.ewkt for p in ref_u2}, {p.ewkt for p in u2}) self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u3})
def _get_geometry_wkt(self, dataset): longitudes = dataset.variables[self.longitude_attribute] latitudes = dataset.variables[self.latitude_attribute] lonlat_dependent_data = False for nc_variable_name, nc_variable_value in dataset.variables.items(): if (nc_variable_name not in dataset.dimensions and self.longitude_attribute in nc_variable_value.dimensions and self.latitude_attribute in nc_variable_value.dimensions): lonlat_dependent_data = True break #read the fill_value just one time for usage in below loop lat_fil_value = latitudes[:].fill_value if np.ma.isMaskedArray( latitudes[:]) else None lon_fil_value = longitudes[:].fill_value if np.ma.isMaskedArray( longitudes[:]) else None # If at least a variable is dependent on latitude and # longitude, the longitude and latitude arrays are combined to # find all the data points if lonlat_dependent_data: points = [] for lon in longitudes: for lat in latitudes: if lon_fil_value == lon or lat_fil_value == lat: continue # Don't add the points that have the default value inside them points.append(Point(float(lon), float(lat), srid=4326)) geometry = MultiPoint(points, srid=4326).convex_hull # If the longitude and latitude variables have the same shape, # we assume that they contain the coordinates for each data # point elif longitudes.shape == latitudes.shape: points = [] # in this case numpy.nditer() works like zip() for # multi-dimensional arrays for lon, lat in np.nditer((longitudes, latitudes), flags=['buffered']): if lon_fil_value == lon or lat_fil_value == lat: continue # Don't add the points that have the default value inside them new_point = Point(float(lon), float(lat), srid=4326) # Don't add duplicate points in trajectories if not points or new_point != points[-1]: points.append(new_point) if len(longitudes.shape) == 1: if len(points) == 1: geometry = points[0] else: geometry = LineString(points, srid=4326) else: geometry = MultiPoint(points, srid=4326).convex_hull else: raise ValueError("Could not determine the spatial coverage") return geometry.wkt
def test06_Collection(self): 'Testing Collection mutations' for mp in (MultiPoint(*map(Point, ((3, 4), (-1, 2), (5, -4), (2, 8)))), fromstr('MULTIPOINT (3 4,-1 2,5 -4,2 8)')): self.assertEqual(mp._get_single_external(2), Point(5, -4), 'Collection _get_single_external') mp._set_list(3, map(Point, ((5, 5), (3, -2), (8, 1)))) self.assertEqual(mp.coords, ((5.0, 5.0), (3.0, -2.0), (8.0, 1.0)), 'Collection _set_list') lsa = MultiPoint(*map(Point, ((5, 5), (3, -2), (8, 1)))) for f in geos_function_tests: self.assertEqual(f(lsa), f(mp), 'MultiPoint ' + f.__name__)
def get_trip_geometry_from_details(self, trip_details=None, departure_slug=None, departure_zip=None, arrival_slug=None, arrival_zip=None): """Compute and return a GIS multipoint geometry, based on trip_type and additional data provided in parameters. If trip_details is not known when doing the call, you can pass departure and arrival slug and zipcode, the lib can find them the right way. """ if (not trip_details and departure_slug and departure_zip and arrival_slug and arrival_zip): trip_details = self.get_trip_details(departure_slug, departure_zip, arrival_slug, arrival_zip) try: mpoints = MultiPoint([ GEOSGeometry(trip_details['departure']['point']), GEOSGeometry(trip_details['arrival']['point']) ]) except: raise ErrorException() return mpoints.envelope.wkt
def mean_center(geoqueryset, point_attribute_name='point'): """ Accepts a geoqueryset, expected to contain objects with Point properties, and returns a Point object with the mean center of the provided points. The mean center is the average x and y of all those points. By default, the function expects the Point field on your model to be called 'point'. If the point field is called something else, change the kwarg 'point_attribute_name' to whatever your field might be called. h3. Example usage >> import calculate >> calculate.mean_center(qs) <Point object at 0x77a1694> h3. Dependencies * "django":http://www.djangoproject.com/ * "geodjango":http://www.geodjango.org/ h3. Documentation * "mean center":http://en.wikipedia.org/wiki/Geostatistics#Descriptive_spatial_statistics """ if not isinstance(geoqueryset, GeoQuerySet): raise TypeError( 'First parameter must be a Django GeoQuerySet. You submitted a %s object' % type(geoqueryset)) multipoint = MultiPoint( [getattr(p, point_attribute_name) for p in geoqueryset]) return multipoint.centroid
def process_feature_geoms(self, resource, geom_field): """ Reduces an instances geometries from a geometry collection, that potentially has any number of points, lines and polygons, down to a list containing a MultiPoint and/or a MultiLine, and/or a MultiPolygon object. """ result = [] sorted_geoms = {"points": [], "lines": [], "polys": []} for geom in resource[geom_field]: if geom.geom_typeid == 0: sorted_geoms["points"].append(geom) if geom.geom_typeid == 1: sorted_geoms["lines"].append(geom) if geom.geom_typeid == 3: sorted_geoms["polys"].append(geom) if geom.geom_typeid == 4: for feat in geom: sorted_geoms["points"].append(feat) if geom.geom_typeid == 5: for feat in geom: sorted_geoms["lines"].append(feat) if geom.geom_typeid == 6: for feat in geom: sorted_geoms["polys"].append(feat) if len(sorted_geoms["points"]) > 0: result.append(MultiPoint(sorted_geoms["points"])) if len(sorted_geoms["lines"]) > 0: result.append(MultiLineString(sorted_geoms["lines"])) if len(sorted_geoms["polys"]) > 0: result.append(MultiPolygon(sorted_geoms["polys"])) return result
def set_control_points_remove_spillovers(user_map, upper): """ Set control features for user by removing points which are near treated points and fall within a specified radius :param user_map: Map instance associated with the logged in user :param upper: Number to set radius that bounds the spillover region :return: None, do database I/O """ treated = fs_manager.get_treated(user_map) point_rows = list( models.Feature.objects.filter(pk__in=treated).values_list('geom_point', flat=True)) METER_TO_ARC = 111195.0 # Divide meters by this value to get degree arcs in SRID 4326 mpoints = MultiPoint(point_rows) controlled = fs_manager.get_controlled(user_map) bounded = list( models.Feature.objects.filter( pk__in=controlled, geom_point__distance_lte=(mpoints, D(km=upper))).values_list('id', flat=True)) fs_manager.delete_controlled(user_map, bounded)
def setUp(self): self.login() self.trek = TrekFactory.create() self.trek.points_reference = MultiPoint( [Point(0, 0), Point(1, 1)], srid=settings.SRID) self.trek.save()
def _coerce_multipoint(self, geometry, dimensions=2, z_value=0): new_points = [] for p in geometry: new_points.append(self._coerce_point(p, dimensions, z_value)) return MultiPoint(new_points, srid=geometry.srid)
def do_send(user, cleaned): title = cleaned["title"] title_markup = ("<h3>" + escape(title) + "</h3>\n") if title else "" message = cleaned["message"] subscribers = UserNotificationForm._get_subscribers(cleaned) for sub, related in subscribers.items(): boilerplate = replace_boilerplate(cleaned["greeting"], related, cleaned["region"]) send_staff_notification.delay( sub.pk, title, f"{title_markup}{message}<br/><hr/><br/>{boilerplate}<br/>") points = MultiPoint(*chain((p.location for p in cleaned["proposals"]), ( a[1] for a in cleaned["coded_addresses"]))) return StaffNotification.objects.create( title=cleaned["title"], sender=user, addresses=cleaned["addresses"], proposals=",".join(p.pk for p in cleaned["proposals"]), radius=cleaned["notification_radius"].m, points=points, message=cleaned["message"], subscribers=len(subscribers), region=cleaned["region"])
def split_bygeom(self, iterable, geom_getter=lambda x: x.geom): """Split an iterable in two list (points, linestring)""" points, linestrings, polygons, multipoints, multilinestrings, multipolygons = [], [], [], [], [], [] for x in iterable: geom = geom_getter(x) if geom is None: pass elif isinstance(geom, GeometryCollection): # Duplicate object, shapefile do not support geometry collections ! subpoints, sublines, subpolygons, pp, ll, yy = self.split_bygeom( geom, geom_getter=lambda geom: geom) if subpoints: clone = x.__class__.objects.get(pk=x.pk) clone.geom = MultiPoint(subpoints, srid=geom.srid) multipoints.append(clone) if sublines: clone = x.__class__.objects.get(pk=x.pk) clone.geom = MultiLineString(sublines, srid=geom.srid) multilinestrings.append(clone) if subpolygons: clone = x.__class__.objects.get(pk=x.pk) clone.geom = MultiPolygon(subpolygons, srid=geom.srid) multipolygons.append(clone) elif isinstance(geom, Point): points.append(x) elif isinstance(geom, LineString): linestrings.append(x) elif isinstance(geom, Polygon): polygons.append(x) else: raise ValueError( "Only LineString, Point and Polygon should be here. Got %s for pk %d" % (geom, x.pk)) return points, linestrings, polygons, multipoints, multilinestrings, multipolygons
def geocode(address, jurisdictions, required_precision_km=1., limit=5): """ Find jurisdictions that match a given address Identifies the coordinates of an address. It will ignore the input if it is only digits and less than 5 digits. If the input is only 5 digits the function assumes that is is a zipcode and search for zipcodes :param address: the address to be geocoded :type value: String :param required_precision_km: the maximum permissible geographic uncertainty for the geocoding :type required_precision_km: float :returns: dict :example: >>> geocode('1600 Pennsylvania Ave NW, Washington, DC 20500') {'lat': 38.89767579999999, 'lon': -77.0364827} """ try: key = 'pk.eyJ1IjoiZGV2c2VlZCIsImEiOiJnUi1mbkVvIn0.018aLhX0Mb0tdtaT2QNe2Q' geocoded = NewMapboxQuery(address, key=key, country='us', limit=limit) results = [] if len(geocoded) > 0: for item in geocoded: multipoints = MultiPoint([GEOSGeometry(item.wkt)]) for jurisdiction in jurisdictions.filter( geometry__intersects=multipoints): if not jurisdiction in results: results.append(jurisdiction) return results return [] except: print("Unexpected error:", sys.exc_info()[0]) return []
def setUp(self): self.trek = TrekFactory.create( no_path=True, points_reference=MultiPoint([Point(0, 0), Point(1, 1)], srid=settings.SRID), parking_location=Point(0, 0, srid=settings.SRID), )
def GasUpload(request): from django.core.files.storage import FileSystemStorage from django.contrib.gis.geos import MultiPoint, Point import os survey_id = request.session['survey_id'] survey = SurveyDate.objects.get(pk=survey_id) if request.method == "POST" and request.FILES['gasfile']: gasfile = request.FILES['gasfile'] fs = FileSystemStorage() filename = fs.save(gasfile.name, gasfile) filename = os.path.join("media/", filename) with open (filename, 'r') as gas: gas = gas.readlines() gasdata = [] for line in gas: if not line.startswith("L"): line = line.strip().split(",") lat, long, gasvalue = line[0], line[1], line[2] gas_point = Point(x=float(long), y=float(lat), z=float(gasvalue)) gasdata.append(gas_point) else: continue gas_mp = MultiPoint(gasdata) survey.survey_gas_point_geom = gas_mp survey.save() return redirect("edit_report", survey_id=survey_id) return render(request, "gasupload.html")
def process_mapdata(): # We create the MapData models here. We can't create them until the # Page objects are created. global mapdata_objects_to_create from maps.models import MapData from pages.models import Page, slugify from django.contrib.gis.geos import Point, MultiPoint for item in mapdata_objects_to_create: print "Adding mapdata for", item['pagename'] p = Page.objects.get(slug=slugify(item['pagename'])) mapdata = MapData.objects.filter(page=p) y = float(item['lat']) x = float(item['lon']) point = Point(x, y) if mapdata: m = mapdata[0] points = m.points points.append(point) m.points = points else: points = MultiPoint(point) m = MapData(page=p, points=points) m.save()
def calc_composite_geometry(self): geometries = [] if not self.is_composite: return False for relation in self.relationships: if relation["type"] == "comprised_by": relation_geometry = Place.objects.get(relation["id"]).geometry if relation_geometry: geos_geom = GEOSGeometry(json.dumps(relation_geometry)) if geos_geom.geom_type == "MultiPolygon" or geos_geom.geom_type == "MutliPoint": for indiv_geom in geos_geom: geometries.append(indiv_geom) elif geos_geom.geom_type == "Polygon" or geos_geom.geom_type == "Point": geometries.append(geos_geom) else: pass if not geometries: return False if geometries[0].geom_type == "Polygon": union = MultiPolygon(geometries).cascaded_union elif geometries[0].geom_type == "Point": union = MultiPoint(geometries) self.geometry = json.loads(union.json) self.centroid = union.centroid.coords return True
def search_trip(request, trip_type): """Search for a trip Get information on the trip from session, and request the model to fetch departure and arrival points. If there is no information in session, nor proposed adresses aren't found in database, redirect the user to the homepage. """ # check session search_trip_details = request.session.get('search_trip_details', None) if not search_trip_details: return HttpResponseRedirect(reverse('carpool:home')) try: mpoints = MultiPoint([GEOSGeometry(search_trip_details['departure']['point']), GEOSGeometry(search_trip_details['arrival']['point'])]) except: return HttpResponseRedirect(reverse('carpool:home')) response_dict = { 'current_item': 1, 'gmapkey': settings.GOOGLE_MAPS_API_KEY, 'geometry': mpoints.envelope.wkt, 'trip_details': search_trip_details, 'trip_type': trip_type, 'places': FavoritePlace.objects.filter(design=settings.THEME_USED).order_by('name'), 'OFFER': Trip.OFFER, } template = loader.get_template('carpool/search_trip.html') context = RequestContext(request, response_dict) return HttpResponse(template.render(context))
def process_feature_geoms(self, properties, resource, geo_process="collection"): geoms = [] result = None for g in resource["_source"]["geometries"]: geom = GEOSGeometry(JSONSerializer().serialize(g["value"], ensure_ascii=False)) geoms.append(geom) if geo_process == "collection": geometry = GeometryCollection(geoms) result = { "type": "Feature", "geometry": geometry, "properties": properties } elif geo_process == "sorted": result = [] sorted_geoms = {"points": [], "lines": [], "polys": []} for geom in geoms: if geom.geom_typeid == 0: sorted_geoms["points"].append(geom) if geom.geom_typeid == 1: sorted_geoms["lines"].append(geom) if geom.geom_typeid == 3: sorted_geoms["polys"].append(geom) if geom.geom_typeid == 4: for feat in geom: sorted_geoms["points"].append(feat) if geom.geom_typeid == 5: for feat in geom: sorted_geoms["lines"].append(feat) if geom.geom_typeid == 6: for feat in geom: sorted_geoms["polys"].append(feat) if len(sorted_geoms["points"]) > 0: result.append({ "type": "Feature", "geometry": MultiPoint(sorted_geoms["points"]), "properties": properties, }) if len(sorted_geoms["lines"]) > 0: result.append({ "type": "Feature", "geometry": MultiLineString(sorted_geoms["lines"]), "properties": properties, }) if len(sorted_geoms["polys"]) > 0: result.append({ "type": "Feature", "geometry": MultiPolygon(sorted_geoms["polys"]), "properties": properties, }) return result
def process_feature_geoms(self, properties, resource, geo_process='collection'): geoms = [] result = None for g in resource['_source']['geometries']: geom = GEOSGeometry(JSONSerializer().serialize(g['value'], ensure_ascii=False)) geoms.append(geom) if geo_process == 'collection': geometry = GeometryCollection(geoms) result = { 'type': 'Feature', 'geometry': geometry, 'properties': properties } elif geo_process == 'sorted': result = [] sorted_geoms = {'points': [], 'lines': [], 'polys': []} for geom in geoms: if geom.geom_typeid == 0: sorted_geoms['points'].append(geom) if geom.geom_typeid == 1: sorted_geoms['lines'].append(geom) if geom.geom_typeid == 3: sorted_geoms['polys'].append(geom) if geom.geom_typeid == 4: for feat in geom: sorted_geoms['points'].append(feat) if geom.geom_typeid == 5: for feat in geom: sorted_geoms['lines'].append(feat) if geom.geom_typeid == 6: for feat in geom: sorted_geoms['polys'].append(feat) if len(sorted_geoms['points']) > 0: result.append({ 'type': 'Feature', 'geometry': MultiPoint(sorted_geoms['points']), 'properties': properties }) if len(sorted_geoms['lines']) > 0: result.append({ 'type': 'Feature', 'geometry': MultiLineString(sorted_geoms['lines']), 'properties': properties }) if len(sorted_geoms['polys']) > 0: result.append({ 'type': 'Feature', 'geometry': MultiPolygon(sorted_geoms['polys']), 'properties': properties }) return result
def add_return_trip(request, trip_id): """Create a new back trip based on information of an existing trip """ trip = get_object_or_404(Trip, pk=trip_id, user=request.user) new_trip = Trip(user=request.user) new_trip.name = _('%(trip_name)s - Return') % {'trip_name': trip.name} new_trip.trip_type = trip.trip_type new_trip.departure_city = trip.arrival_city new_trip.departure_address = trip.arrival_address new_trip.departure_point = trip.arrival_point new_trip.arrival_city = trip.departure_city new_trip.arrival_address = trip.departure_address new_trip.arrival_point = trip.departure_point new_trip.regular = trip.regular if new_trip.regular: new_trip.dows = trip.dows new_offer = None if trip.offer: new_offer = TripOffer() new_offer.checkpointlist = trip.offer.checkpointlist new_offer.checkpointlist.reverse() new_offer.radius = trip.offer.radius new_trip.offer = new_offer new_demand = None if trip.demand: new_demand = TripDemand() new_demand.radius = trip.demand.radius new_trip.demand = new_demand userprofiledata = model_to_dict(request.user.get_profile()) form_trip = EditTripForm(initial=userprofiledata, instance=new_trip) form_offer = EditTripOfferOptionsForm(initial=userprofiledata, instance=new_offer, prefix='offer') form_demand = EditTripDemandOptionsForm(initial=userprofiledata, instance=new_demand, prefix='demand') points = [cp['point'] for cp in trip.offer.checkpointlist] if trip.offer else [] points.append(trip.departure_point) points.append(trip.arrival_point) mpoints = MultiPoint(points) response_dict = { 'form_trip': form_trip, 'form_offer_options': form_offer, 'form_demand_options': form_demand, 'default_center': settings.DEFAULT_MAP_CENTER_POINT, 'default_zoom': settings.DEFAULT_MAP_CENTER_ZOOM, 'return_trip': True, } template = loader.get_template('carpool/add_modify_trip.html') context = RequestContext(request, response_dict) return HttpResponse(template.render(context))
def get(self, request, format=None): results = self.apply_filter(request, ignore_bbox=True) multipoint = MultiPoint([result.location_center for result in results]) if multipoint: extents = multipoint.extent extents = [extents[1], extents[0], extents[3], extents[2]] return Response(extents) else: return Response([])
def value_from_datadict(self, data, files, name): """ Given a dictionary of data and this widget's name, return the value of this widget or None if it's not provided. """ geos_obj = fromstr(data.get(name).strip()) if isinstance(geos_obj, GeometryCollection): geos_obj = MultiPoint([p for p in geos_obj]) return geos_obj.wkt
def geoadmin_initial(self, request, queryset, fields): """Geoadmin API default parameters""" # TODO if queryset: instance = queryset[0] else: return 0, 0 bb = MultiPoint([getattr(instance, f).centroid for f in fields]).extent return (bb[3] + bb[1]) / 2., (bb[2] + bb[0]) / 2.
def add_trip_from_search(request): """Add a trip from a previous search (stored in session) """ def _get_favorite_place(json, key): try: favorite_place_id = int(json.get(key).get('favoriteplace')) return FavoritePlace.objects.get(pk=favorite_place_id) except (ValueError, FavoritePlace.DoesNotExist): return None if request.method != 'POST' or 'trip_details' not in request.POST: return HttpResponseRedirect('carpool:add_trip') trip = Trip(user=request.user) try: json = simplejson.loads(request.POST['trip_details']) trip.trip_type = int(json.get('type')) trip.trip_radius = int(json.get('radius')) departure_favoriteplace = _get_favorite_place(json, 'departure') if departure_favoriteplace: trip.departure_city = departure_favoriteplace.city trip.departure_address = departure_favoriteplace.address trip.departure_point = departure_favoriteplace.point else: trip.departure_city = json.get('departure').get('city') trip.departure_point = GEOSGeometry(json.get('departure').get('point')) arrival_favoriteplace = _get_favorite_place(json, 'arrival') if arrival_favoriteplace: trip.arrival_city = arrival_favoriteplace.city trip.arrival_address = arrival_favoriteplace.address trip.arrival_point = arrival_favoriteplace.point else: trip.arrival_city = json.get('arrival').get('city') trip.arrival_point = GEOSGeometry(json.get('arrival').get('point')) trip.interval_min = min(abs(int(json.get('interval_min'))), MAX_INTERVAL) trip.interval_max = min(abs(int(json.get('interval_max'))), MAX_INTERVAL) trip.date = get_date(json.get('date'), FRENCH_DATE_INPUT_FORMATS) form = AddModifyTripOptionsForm(initial=model_to_dict(request.user.get_profile()), instance=trip) except: return HttpResponseRedirect(reverse('carpool:add_trip')) mpoints = MultiPoint([trip.departure_point, trip.arrival_point]) response_dict = { 'current_item': 10, 'gmapkey': settings.GOOGLE_MAPS_API_KEY, 'trip': trip, 'form': form, 'geometry': mpoints.envelope.wkt, 'trip_from_search': True, 'hours': range(24), } template = loader.get_template('carpool/add_modify_trip.html') context = RequestContext(request, response_dict) return HttpResponse(template.render(context))
def get_paginated_response(self, data): if len(data) >= 2: points = [Point(memorial['position']) for memorial in data] bbox = MultiPoint(points).envelope else: bbox = MultiPoint( Point(12.1898, 49.9664), Point(15.5079, 49.9664), Point(15.5079, 51.4444), Point(12.1898, 51.4444), ).envelope return Response( OrderedDict([ ('count', self.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data), ('bbox', (bbox.coords[0][0], bbox.coords[0][2])), ]))
def test06_Collection(self): "Testing Collection mutations" points = ( MultiPoint(*map(Point, ((3, 4), (-1, 2), (5, -4), (2, 8)))), fromstr("MULTIPOINT (3 4,-1 2,5 -4,2 8)"), ) for mp in points: self.assertEqual( mp._get_single_external(2), Point(5, -4), "Collection _get_single_external", ) mp._set_list(3, map(Point, ((5, 5), (3, -2), (8, 1)))) self.assertEqual(mp.coords, ((5.0, 5.0), (3.0, -2.0), (8.0, 1.0)), "Collection _set_list") lsa = MultiPoint(*map(Point, ((5, 5), (3, -2), (8, 1)))) for f in geos_function_tests: self.assertEqual(f(lsa), f(mp), "MultiPoint " + f.__name__)
class PuzzleFactory(GameFactory): default_positions = MultiPoint((Point(0, 0), Point(1, 1))) class Meta: model = Puzzle @factory.post_generation def translations(self, create, extracted, **kwargs): for translation in self.translations.all(): translation.name = f'{translation.name}-{translation.language_code}' translation.save()