def get_distance(self, obj): lat = self.context['request'].GET.get('lat') lon = self.context['request'].GET.get('lon') if lat and lon: mobile_point = GEOSGeometry('SRID=4326;POINT(%s %s)' % (lat, lon)) company_point = GEOSGeometry('SRID=4326;POINT(%s %s)' % (obj.company.address.location.x, obj.company.address.location.y)) distance = mobile_point.distance(company_point) * 100 return "%.2f" % distance return None
def test_edit(self): c = self.client self.assertTrue(c.login(username='******', password='******')) r = c.post('/admin/testolwidget/googprojmodel/add/', { 'point': 'SRID=900913;POINT(10 10)' }, follow=True) self.assertEquals(r.status_code, 200) self.assertEquals(len(GoogProjModel.objects.all()), 1) a = GEOSGeometry('SRID=900913;POINT(10 10)') b = GoogProjModel.objects.all()[0].point # Floating point comparison -- ensure distance is minuscule. self.assertTrue(a.distance(b) < 1.0e-9)
def get(self, lat, lng): ids = list() url = self.VELOV_API_URL_PATTERN velov = json.loads(urllib.urlopen(url).read()) for station in velov['values']: station_pos = GEOSGeometry('POINT(%s %s)' % ( station['lng'], station['lat'])) current_pos = GEOSGeometry('POINT(%f %f)' % (lng, lat)) if station_pos.distance(current_pos) * 100 < 0.8: yield Item(station['name'], 'velov', '%s: %s disponibles, %s places' % ( station['address'], station['available_bikes'], station['available_bike_stands']), station['lat'], station['lng'])
def test_edit(self): c = self.client self.assertTrue(c.login(username='******', password='******')) r = c.post('/admin/testolwidget/googprojmodel/add/', { "point": 'SRID=900913;POINT(10 10)' }, follow=True) self.assertEquals(r.status_code, 200) self.assertEquals(len(GoogProjModel.objects.all()), 1) a = GEOSGeometry("SRID=900913;POINT(10 10)") b = GoogProjModel.objects.all()[0].point # Floating point comparison -- ensure distance is miniscule. self.assertTrue(a.distance(b) < 1.0e-9)
def calculate_price(shipment): price_base = shipment.shipmenttype.price price_package = shipment.packagetype.price if shipment.insured: price_insured_value = shipment.shipmenttype.price else: price_insured_value = Decimal(0) pnt1 = GEOSGeometry(shipment.origin) pnt2 = GEOSGeometry(shipment.destination) distance = pnt1.distance(pnt2) * 100 price_km = Decimal(int(distance * 50)) price_total = price_base + price_package + price_insured_value + price_km return price_total
def create(self, validated_data): price = validated_data['price'] user = validated_data['user'] title = validated_data['title'] pickup_for = validated_data['pickup_for'] description = validated_data['description'] phone_number = validated_data['phone_number'] destination_a = validated_data['destination_a'] destination_b = validated_data['destination_b'] image_url = validated_data['image_url'] ga = geocoder.google(destination_a) gb = geocoder.google(destination_b) a_lat = ga.latlng[0] a_lng = ga.latlng[1] b_lat = gb.latlng[0] b_lng = gb.latlng[1] point_a = GEOSGeometry('POINT(' + str(a_lng) + ' ' + str(a_lat) + ')', srid=4326) point_b = GEOSGeometry('POINT(' + str(b_lng) + ' ' + str(b_lat) + ')', srid=4326) trip_distance = int(point_a.distance(point_b) * 100 * 0.62137) job = Job.objects.create(user=user, price=price, title=title, pickup_for=pickup_for, description=description, image_url=image_url, phone_number=phone_number, destination_a=destination_a, destination_b=destination_b, point_a=point_a, point_b=point_b, trip_distance=trip_distance) if not user.profile.phone_number: user.profile.phone_number = phone_number user.profile.save() if not user.profile.display_name: user.profile.display_name = pickup_for user.profile.save() job.job_posted() return job
def test_view(request): params = request.query_params if 'lat' and 'lon' in params: if params['lat'] and params['lon']: lat = int(params['lat']) lon = int(params['lon']) target_point = GEOSGeometry(f'SRID=4326;POINT({lon} {lat})') distances = dict() for branch in Branch.objects.all(): branch_point = GEOSGeometry( f'SRID=4326;POINT({branch.longitude} {branch.latitude})') distance = target_point.distance(branch_point) distances[distance] = branch.pk min_distance = min(distances.keys()) closest_branch = Branch.objects.get( pk=distances[min_distance]).to_json() return Response(closest_branch, status=status.HTTP_200_OK) else: return Response(status=status.HTTP_404_NOT_FOUND)
def addRunlet(run, old, new): if ((old.lat == new.lat) and (old.lon == new.lon) and (run['runlets'] == 0)): return path_id = getNearestPath(old) if (path_id == None): path_id = -1 old_lat = old.lat old_lon = old.lon t0 = old.t new_lat = new.lat new_lon = new.lon tn = new.t if (old.dirTag != new.dirTag): old_lat = new_lat old_lon = new_lon t0 = tn sql = "insert into runlet (run_id,lat0,lon0,loc0,t0,latn,lonn,locn,tn,path_id,distance) values (" + str( run['id']) + "," + str(old_lat) + "," + str( old_lon) + ", ST_SetSRID(ST_MakePoint(" + str(old_lon) + "," + str( old_lat ) + " )," + srid + ")," + str(t0) + "," + str(new_lat) + "," + str( new_lon) + ",ST_SetSRID(ST_MakePoint(" + str( new_lon) + "," + str(new_lat) + " )," + srid + ") ," + str( tn) + "," + str(path_id) + ",0) returning id" cur = old.db.cursor() cur.execute(sql) old.db.commit() id = cur.fetchone()[0] GEOSGeom0 = GEOSGeometry("POINT(" + str(old.lon) + " " + str(old.lat) + ")") GEOSGeom0.srid = 4326 GEOSGeomn = GEOSGeometry("POINT(" + str(new.lon) + " " + str(new.lat) + ")") GEOSGeomn.srid = 4326 GEOSGeom0.transform(ct) GEOSGeomn.transform(ct) dist = GEOSGeom0.distance(GEOSGeomn) sql = "update runlet set distance=%s where id=%s" cur.execute(sql, ( dist, id, )) old.db.commit() freq = int((t - run['startTime']) / (run['runlets'] + 1)) sql = "update run set distance = distance + %s, runlets = runlets + 1, freq = %s where id = " + str( run['id']) cur.execute(sql, ( dist, freq, )) old.db.commit() """
def near_by_posts(request): user_details = User.objects.get(id=request.user.id) user_location = GEOSGeometry(request.user.location) print(request.user.id) posts = Activity.objects.filter( post_type='NB', location__distance_lte=(user_details.location, D(m=16093)))[:20] temp_posts = [] for post in posts: post_comments = [] posted_user = User.objects.get(id=post.user_id) likes = Like.objects.filter(post_id=post.id) comments = Comment.objects.filter(post_id=post.id) for comment in comments: commented_user_details = User.objects.get(id=comment.user_id) temp_comment = { 'user': commented_user_details.username, 'comment': comment.body } post_comments.append(temp_comment) post_comments.reverse() temp_user_like = Like.objects.filter(post_id=post.id, user_id=request.user.id) post_location = GEOSGeometry(post.location) if not post.image: if not post.video: temp_post = { 'post_id': post.id, 'user': posted_user.username, 'first_name': posted_user.first_name, 'last_name': posted_user.last_name, 'profile_pic': None if not posted_user.profile_picture else posted_user.profile_picture.url, 'datetime': post.datetime, 'body': post.body, 'distance': user_location.distance(post_location) * 100000, 'likes': len(likes), 'user_liked': False if len(temp_user_like) == 0 else True, 'comments': post_comments[0:2], 'comments_length': len(post_comments), } temp_posts.append(temp_post) elif post.video: temp_post = { 'user': posted_user.username, 'id': post.id, 'first_name': posted_user.first_name, 'last_name': posted_user.last_name, 'profile_pic': None if not posted_user.profile_picture else posted_user.profile_picture.url, 'datetime': post.datetime, 'body': post.body, 'video': None if not post.video else post.video.url, 'distance': user_location.distance(post_location) * 100000, 'likes': len(likes), 'user_liked': False if len(temp_user_like) == 0 else True, 'comments': post_comments[0:2], 'comments_length': len(post_comments), } temp_posts.append(temp_post) # else: # temp_post = { # 'user': friend.username, # 'profile_pic': None if not friend.profile_picture else friend.profile_picture.url, # 'datetime': activity.datetime, # 'body': activity.body, # 'video' : activity.video.url, # } # friend_posts.append(temp_post) elif post.image: temp_post = { 'user': post.user_id, 'id': post.id, 'first_name': posted_user.first_name, 'last_name': posted_user.last_name, 'profile_pic': None if not posted_user.profile_picture else posted_user.profile_picture.url, 'datetime': post.datetime, 'body': post.body, 'image': None if not post.image else post.image.url, 'distance': user_location.distance(post_location) * 100000, 'likes': len(likes), 'user_liked': False if len(temp_user_like) == 0 else True, 'comments': post_comments[0:2], 'comments_length': len(post_comments), } temp_posts.append(temp_post) else: temp_post = { 'user': posted_user.username, 'id': post.id, 'first_name': posted_user.first_name, 'last_name': posted_user.last_name, 'profile_pic': None if not posted_user.profile_picture else posted_user.profile_picture.url, 'datetime': post.datetime, 'body': post.body, 'image': None if not post.image else post.image.url, 'video': None if not post.video else post.video.url, 'distance': user_location.distance(post_location) * 100000, 'likes': len(likes), 'user_liked': False if len(temp_user_like) == 0 else True, 'comments': post_comments[0:2], 'comments_length': len(post_comments), } temp_posts.append(temp_post) return Response(temp_posts)
def get_distance(lat1, lon1, lat2, lon2): pnt = GEOSGeometry(f'SRID=4326;POINT({lat1} -{lon1})') pnt2 = GEOSGeometry(f'SRID=4326;POINT( {lat2} {lon2} )') return pnt.distance(pnt2) * 100
def homepage(request): response = requests.get( 'http://api.openweathermap.org/data/2.5/weather?q=kathmandu,np&appid=8d2de98e089f1c28e1a22fc19a24ef04' ) weather_data = response.json() print(weather_data["weather"]) # weather_dict={weather_data["weather"][i] for i in [0,]} source_latitude = 0 source_longitude = 0 destination_latitude = 0 destination_longitude = 0 travel_distance = 0 if request.method == 'POST': form = DestinationForm(request.POST) if form.is_valid(): form_data = form.save() address = "%s, %s" % (form_data.source, form_data.destination) geolocator = MapBox( api_key= 'pk.eyJ1IjoicmFuamFuNDM1IiwiYSI6ImNrNWIzdnNqeTE2ZjgzZG82OG40aG82ejcifQ.nrFTVyOERu6YhgS66Gxr8A' ) location_source = geolocator.geocode(form_data.source) location_destination = geolocator.geocode(form_data.destination) source_latitude = location_source.latitude source_longitude = location_source.longitude destination_latitude = location_destination.latitude destination_longitude = location_destination.longitude source = (source_latitude, source_longitude) destination = (destination_latitude, destination_longitude) str_geo = str(distance.distance(source, destination)) travel_distance = round(float(str_geo[:-3]), 2) print(travel_distance) pnt1 = GEOSGeometry('SRID=4326;POINT(%s %s)' % (source_latitude, source_longitude)) pnt2 = GEOSGeometry('SRID=4326;POINT(%s %s)' % (destination_latitude, destination_longitude)) print(pnt1.distance(pnt2) * 100) # location.destination = geolocator.geocode(form_data.destination) form = DestinationForm() #showing database information in map post_list = Post.objects.all() print(post_list[0].location.wkt) loc_list = [str(post.location) for post in post_list] temp = [loc.split(";") for loc in loc_list] point_list = [i[1] for i in temp] final = [(point[7:(len(point) - 1)]) for point in point_list] tempo = [a.split(" ") for a in final] lat = [i[0] for i in tempo] lon = [i[1] for i in tempo] latlon = [(float(lat[i]), float(lon[i])) for i in range(len(lon))] #showing sensor data sensor_data = SensorModel.objects.latest('id') #showing the number of vehicles vehicle_num = VehicleModel.objects.latest('id') return render( request, 'map/base_map.html', { 'form': form, 'source_latitude': source_latitude, 'source_longitude': source_longitude, 'destination_latitude': destination_latitude, 'destination_longitude': destination_longitude, 'distance': travel_distance, 'posts': post_list, 'location': latlon, 'weather_data': weather_data, 'sensor_data': sensor_data, 'vehicle_num': vehicle_num, }, ) # def databaseshow(request): # #showing post objects # post_list=Post.objects.all() # print (post_list[0].location.wkt) # loc_list=[str(post.location) for post in post_list] # temp=[loc.split(";") for loc in loc_list] # point_list=[i[1] for i in temp] # final=[(point[7:(len(point)-1)]) for point in point_list] # tempo=[a.split(" ") for a in final] # lat=[i[0] for i in tempo] # lon=[i[1] for i in tempo] # latlon=[(float(lat[i]),float(lon[i])) for i in range(len(lon))] # return render(request,'map/base_map.html',{'posts':post_list,'location':latlon})