def probability(request,ltlat, ltlong, rblat, rblong ,poslat, poslong, dayindex, hourindex):
#dayindex starts with 1 for sunday, see https://docs.djangoproject.com/en/dev/ref/models/querysets/#week-day
loc = Point(float(poslong),float(poslat),srid=4326 ) #fixme: check that srid=4326 is right
print(loc)
result = Bikes.objects.filter(timestamp__week_day=dayindex).filter(timestamp__hour=hourindex).filter(bikes__gt=0)\
.extra({'date_found' : "date(timestamp)"}).values('date_found')\
.annotate(min_distance=Min(Distance('place_coords', loc))).order_by('min_distance')
result_count = len(result)
result_ranges = {}
percentages = [0.25,0.50,0.75,0.90]
p_ind = 0
for i in range(result_count): # this finds the minimum distance for which the percentages from the list are fullfiled for bike availability
percentage_sum = (i+1)/result_count
while p_ind < len(percentages):
if percentages[p_ind] <= percentage_sum:
result_ranges[str(percentages[p_ind])]=result[i]["min_distance"]
p_ind+=1
else:
break
return HttpResponse(json.dumps(result_ranges), content_type='application/json')
python类Point()的实例源码
def _set_geom(self):
xform = self.xform
data_dictionary = xform.data_dictionary()
geo_xpaths = data_dictionary.geopoint_xpaths()
doc = self.get_dict()
points = []
if len(geo_xpaths):
for xpath in geo_xpaths:
geometry = [float(s) for s in doc.get(xpath, u'').split()]
if len(geometry):
lat, lng = geometry[0:2]
points.append(Point(lng, lat))
if not xform.instances_with_geopoints and len(points):
xform.instances_with_geopoints = True
xform.save()
self.geom = GeometryCollection(points)
def update(self, instance, validated_data):
data = self.context['request'].data
type_id = data.pop('type')
site_type = ProjectType.objects.get(pk=type_id)
verify_survey = data.pop('is_survey')
if verify_survey:
validated_data.update({'is_survey': False})
validated_data.update({'is_active': True})
else:
validated_data.update({'is_survey': True})
validated_data.update({'is_active': False})
p = Point(float(validated_data.pop('longitude')), float(validated_data.pop('latitude')), srid=4326)
validated_data.update({'location':p})
Site.objects.filter(pk=instance.pk).update(**validated_data)
site = Site.objects.get(pk=instance.id)
site.type = site_type
site.save()
return site
def test_update_timezone(self):
event, l = Event.parse_text(EXAMPLE)
timezone = event.timezone
latitude = event.latitude
longitude = event.longitude
event.coordinates = None
event.timezone = None
event.save()
self.assert_(event.update_timezone())
self.assertEquals(event.timezone, timezone)
event.timezone = None
event.address = None
event.coordinates = Point(longitude, latitude)
event.save()
self.assert_(event.update_timezone())
self.assertEquals(event.timezone, timezone)
event.delete()
def form_valid(self, form):
# Get data
latitude = form.cleaned_data['latitude']
longitude = form.cleaned_data['longitude']
# Get today's date
now = timezone.now()
# Get next week's date
next_week = now + timezone.timedelta(weeks=1)
# Get Point
location = Point(longitude, latitude, srid=4326)
# Look up events
events = Event.objects.filter(datetime__gte=now).filter(datetime__lte=next_week).annotate(distance=Distance('venue__location', location)).order_by('distance')[0:5]
# Render the template
return render_to_response('gigs/lookupresults.html', {
'events': events
})
def get_queryset(self):
queryset = Service.objects.all()
#Order all the services by distance to the requester user location
if 'lat' in self.request.query_params and 'lon' in self.request.query_params:
# Brings lat and lon in request parameters
ref_location = Point(float(self.request.query_params['lon']),float(self.request.query_params['lat']),srid=4326)
if not self.request.user.is_anonymous():
# If user is logged in, save his location
self.request.user.location = ref_location
self.request.user.save()
elif not self.request.user.is_anonymous and (self.request.user.location is not None):
# User has a location previously saved
ref_location = self.request.user.location
else:
# if no location at all
geoip = GeoIP2()
ip = self.request.META['REMOTE_ADDR']
try:
ref_location = Point(geoip.lon_lat(ip),srid=4326)
except AddressNotFoundError:
ref_location = Point((-3.8196228, 40.4378698), srid=4326) # Madrid
if not self.request.user.is_anonymous:
self.request.user.location = ref_location
self.request.user.save()
return queryset.annotate(dist = Distance('author__location', ref_location)).order_by('dist')
def _create_test_query(self):
"""
Helper method that returns an example ReservoirQuery.
"""
accounts = [Account(username='twitter')]
locations = [Location(geom=Point(-76.6653729, 39.4904058), buffer_m=1000)]
searchterms = [
SearchTerm(term='photos'),
SearchTerm(term='media')
]
timeframe = self._create_example_timeframe()
return ReservoirQuery(
accounts=accounts,
locations=locations,
searchterms=searchterms,
timeframe=timeframe
)
def convert_circle_to_rectangle(point, radius_m):
"""
(tuple(int or float, int or float), int or float) -> GEOSGeometry Polygon
Takes a circle as a (lng, lat) tuple and a radius in meters. Returns the
smallest rectangular Polygon that encompasses the circle.
"""
# reverse the lng, lat order to convert to geopy Point format
center = reverse_coordinate_order(point)
# create a geopy coordinate calculator for the given distance
calculator = vincenty(meters=radius_m)
# calculate points at the given distance in the cardinal directions
n_pt = calculator.destination(point=center, bearing=0)
s_pt = calculator.destination(point=center, bearing=180)
e_pt = calculator.destination(point=center, bearing=90)
w_pt = calculator.destination(point=center, bearing=270)
bounds = Bounds(n_lat=n_pt.latitude, s_lat=s_pt.latitude,
e_lng=e_pt.longitude, w_lng=w_pt.longitude)
return bounds.bounding_box
def convert_to_point(location, location_format):
"""
Takes a dict, tuple, or list of coordinates and converts them to a
Point.
"""
if isinstance(location, Point):
return location
try:
if (isinstance(location, dict) and
'lat' in location and 'lon' in location):
return Point(location['lon'], location['lat'])
if location_format.lower().startswith('lat'):
location = reverse_coordinate_order(location)
return Point(location)
except Exception as error:
LOGGER.error('There was an error processing the location %s: %s',
location, error)
def _process_parameters(self, coord, radius_m):
"""
Helper function to process test parameters through
the factor_polygon_into_circles function.
"""
radius_km = units.meters_to_km(radius_m)
polygon = Polygon(coord)
points = shapes.factor_polygon_into_circles(polygon, radius_km)
# take the generated points and turn them into "circles" (polygons)
radius_in_deg = units.convert_meters_to_degrees(radius_m)
circles = [Point(point).buffer(radius_in_deg) for point in points]
# convert the list of circles into a multipolyon and merge them
merged_circles = MultiPolygon(circles).cascaded_union
# make sure the merged circles have no holes and completely cover
# the original polygon
self.assertTrue(merged_circles.num_interior_rings == 0,
'The merged circles had %s holes but should have none'
% merged_circles.num_interior_rings)
self.assertTrue(merged_circles.prepared.covers(polygon),
'The merged circles do not cover the polygon')
def shape(self):
"""
Returns a string indicating the feature type. If the feature type is not
a Point, Polygon, or Multipolygon, returns 'Other'.
"""
if isinstance(self.geom, Point):
if self.has_buffer():
return 'Circle'
else:
return 'Point'
elif isinstance(self.geom, Polygon):
if shapes.is_rectangle(self.geom.exterior_ring):
return 'Rectangle'
else:
return 'Polygon'
elif isinstance(self.geom, MultiPolygon):
return 'MultiPolygon'
else:
return 'Other'
def test_put_update_coordinates(self):
self.assertEqual(self.location_model.objects.count(), 0)
dl = self._create_object_location()
url = reverse(self.url_name, args=[dl.device.pk])
url = '{0}?key={1}'.format(url, dl.device.key)
self.assertEqual(self.location_model.objects.count(), 1)
coords = json.loads(Point(2, 23).geojson)
feature = json.dumps({'type': 'Feature', 'geometry': coords})
r = self.client.put(url, feature, content_type='application/json')
self.assertEqual(r.status_code, 200)
self.assertDictEqual(r.json(), {
'type': 'Feature',
'geometry': coords,
'properties': {'name': dl.location.name}
})
self.assertEqual(self.location_model.objects.count(), 1)
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))
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)
def to_python(self, value):
if value in self.empty_values:
return None
try:
obj = json.loads(value)
except JSONDecodeError:
raise DjangoValidationError(self.default_error_messages['invalid_json'], code='invalid_json')
if set(obj) != {'max_distance', 'coordinates'}:
raise DjangoValidationError(self.default_error_messages['invalid_fields'], code='invalid_fields')
max_distance = obj['max_distance']
coordinates = obj['coordinates']
try:
max_distance = float(max_distance)
except ValueError:
raise DjangoValidationError(self.default_error_messages['invalid_max_distance'], code='invalid_max_distance')
if not check_coordinates(coordinates):
raise DjangoValidationError(self.default_error_messages['invalid_coordinates'], code='invalid_coordinates')
return Point(*coordinates), Distance(m=max_distance)
def create(self,validated_data):
request = self.context['request']
book_data = validated_data.pop('BookId')
book = Book.objects.create(**book_data)
advert = Advert.objects.create(**validated_data)
advert.save()
advert.BookId = book
advert.SellerId_id = self.context['request'].user.id
json = self.context['request'].data
if 'Image' in json.keys():
photo = PhotoUser.objects.get(token=json['Image'])
advert.Photo = photo.Photo
advert.save()
tuple_x_y = (advert.Latitude,advert.Longitude)
advert.Point = Point(tuple_x_y)
seller_adverts = Advert.objects.filter(Q(SellerId_id=request.user.id,IsSold=False))
for seller_advert in seller_adverts:
if seller_advert.BookId.Name in book.Name:
book.delete()
advert.delete()
return {'IsSuccess':False,context:'same advert'}
advert.save()
data = {'IsSuccess':True,'context':''}
#self.context['request'].user.id
return data
def distance(self,obj):
if 'location' in self.context.keys():
request = self.context['request']
tuple_x_y = (float(request.query_params['Latitude']),float(request.query_params['Longitude']))
point = Point(tuple_x_y,srid=4326)
result = distance(obj.Point,point).km
if result < 5:
return '5 km içerisinde'
elif result > 5 and result < 10:
return '10 km içerisinde'
elif result > 10 and result < 25:
return '25 km içerisinde'
elif result > 25 and result < 50:
return '50 km içerisinde'
else:
return obj.City + ' çevresinde'
return obj.City + ' çevresinde'
def _set_geom(self):
xform = self.xform
data_dictionary = xform.data_dictionary()
geo_xpaths = data_dictionary.geopoint_xpaths()
doc = self.get_dict()
points = []
if len(geo_xpaths):
for xpath in geo_xpaths:
geometry = [float(s) for s in doc.get(xpath, u'').split()]
if len(geometry):
lat, lng = geometry[0:2]
points.append(Point(lng, lat))
if not xform.instances_with_geopoints and len(points):
xform.instances_with_geopoints = True
xform.save()
self.geom = GeometryCollection(points)
def polygon_requires_clipping(wgs84_polygon):
geom_type = wgs84_polygon.geom_type
if geom_type == 'MultiPolygon':
polygons = wgs84_polygon.coords
elif geom_type == 'Polygon':
polygons = [wgs84_polygon.coords]
else:
raise Exception("Unknown geom_type {0}".format(geom_type))
for polygon in polygons:
for t in polygon:
for x, y in t:
point = Point(x, y)
if not uk_multipolygon.contains(point):
return True
return False
# ------------------------------------------------------------------------
# Make sure the output directory exists:
def generate_point():
return Point(
24.915 + fake.random.uniform(0, 0.040),
60.154 + fake.random.uniform(0, 0.022),
srid=4326,
)
def generate_polygon():
center = generate_point()
points = [
Point(
center.x + fake.random.uniform(-0.001, 0.001),
center.y + fake.random.uniform(-0.001, 0.001),
srid=4326,
).transform(3879, clone=True)
for _ in range(3)
]
points.append(points[0])
return Polygon(points)
def create_parking(operator_id=1, registration_number='ABC-123', **kwargs):
return Parking(
location=Point(60.193609, 24.951394),
operator_id=operator_id,
registration_number=registration_number,
time_end=now() + datetime.timedelta(days=1),
time_start=now(),
zone=3,
**kwargs
)
def test_location_set_from_terminal(admin_user):
operator = Operator.objects.get_or_create(user=admin_user)[0]
terminal = ParkingTerminal.objects.get_or_create(
number=4567, defaults={
'location': Point(61, 25), 'name': "Test terminal"})[0]
parking = create_parking(operator_id=operator.pk, terminal_number=4567)
parking.location = None
parking.save()
assert parking.location == terminal.location
def test_location_not_overridden_from_terminal(admin_user):
operator = Operator.objects.get_or_create(user=admin_user)[0]
terminal = ParkingTerminal.objects.get_or_create(
number=4567, defaults={
'location': Point(61, 25), 'name': "Test terminal"})[0]
parking = create_parking(operator_id=operator.pk, terminal_number=4567)
location = parking.location
parking.save()
assert parking.location == location
assert parking.location != terminal.location
def _get_polygons(self, geom):
"""
Turns the XML containing coordinates into a multipolygon
"""
polygons = []
for pos in geom.iter('*'):
# get leaf nodes. Treat LinearRing and MultiSurface the same way
if len(pos) == 0:
positions = list(filter(None, pos.text.split(' ')))
points = []
points_as_pairs = zip(positions[1::2], positions[::2])
for latitude, longitude in points_as_pairs:
points.append(Point(float(latitude), float(longitude)))
polygons.append(Polygon(points))
return MultiPolygon(polygons)
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
# #### GeoIP Database Information Routines ####
def get_lon_lat(self, lonlat):
"Unpacks longitude, latitude from GEOS Points and 2-tuples."
if isinstance(lonlat, Point):
lon, lat = lonlat.coords
else:
lon, lat = lonlat
return lon, lat
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
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
# #### GeoIP Database Information Routines ####
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
# #### GeoIP Database Information Routines ####