本文整理汇总了Python中pyproj.Geod.fwd方法的典型用法代码示例。如果您正苦于以下问题:Python Geod.fwd方法的具体用法?Python Geod.fwd怎么用?Python Geod.fwd使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyproj.Geod
的用法示例。
在下文中一共展示了Geod.fwd方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MeetingPlaceAroundGeo
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
class MeetingPlaceAroundGeo(object):
def __init__(self, debug=2):
self._debug = debug
self._dist_obj = Distance()
self._geod = Geod(ellps='WGS84')
############################################################
# POI-DB
############################################################
opdb = OSM_POIDb()
for f in [ "bar.sfbayarea.xml", "restaurant.sfbayarea.xml", "cafe.sfbayarea.xml" ]:
opdb.make_fromOSMXml(os.path.join("osm_data_xml", f))
self._opdb = opdb
def get_lon_lat_box(self, lon, lat, radius=10, in_miles=False):
distance_in_metres = radius*1000
if in_miles: distance_in_metres = distance_in_metres*1.60934
nesw_ll = self._geod.fwd([lon]*4, [lat]*4, [0,90,180,270], [distance_in_metres]*4)
### print nesw_ll
return ( (min(nesw_ll[0]), max(nesw_ll[0])), (min(nesw_ll[1]), max(nesw_ll[1])) )
def get_amenities_around_city(self, city, country='us', region=None, radius=10, in_miles=False):
bb_arr = self._dist_obj.get_city_lon_lat(city, country, region)
### print dll_arr
xbb_arr = [ self.get_lon_lat_box(t[0], t[1], radius, in_miles) for t in bb_arr]
#
#
for bb in xbb_arr:
if self._debug >= 2: print "Bounding box: ", bb
a = self._opdb.get_pois_in_lon_lat_box(bb[0][0], bb[1][0], bb[0][1], bb[1][1])
yield a
示例2: midpoint_longest
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
def midpoint_longest(north_lat, west_lon, south_lat, east_lon):
g = Geod(ellps='WGS84')
af, ab, dist = g.inv(west_lon, north_lat, east_lon, south_lat)
rlon, rlat, az = g.fwd(west_lon, north_lat, af, dist/2)
rlon += 180 if rlon < 0 else -180
rlon = round(rlon, 6)
rlat = round(rlat, 6)
return rlat, rlon
示例3: center
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
def center (self, lon, lat, dst):
"""Set the bbox given a center and a size in meter"""
from pyproj import Geod
g = Geod(ellps='WGS84')
# go dst/2 east to find lon_max
lon_max = g.fwd(lon, lat, 90.0, dst/2, radians=False)[0]
# go dst/2 west to find lon_min
lon_min = g.fwd(lon, lat, 270., dst/2, radians=False)[0]
# go dst/2 north to find lat_max
lat_max = g.fwd(lon, lat, 0., dst/2, radians=False)[1]
# go dst/2 south to find lat_min
lat_min = g.fwd(lon, lat, 180., dst/2, radians=False)[1]
self.set (lon_min, lat_min, lon_max, lat_max)
示例4: test_geod_inverse_transform
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
def test_geod_inverse_transform():
gg = Geod(ellps="clrk66")
lat1pt = 42.0 + (15.0 / 60.0)
lon1pt = -71.0 - (7.0 / 60.0)
lat2pt = 45.0 + (31.0 / 60.0)
lon2pt = -123.0 - (41.0 / 60.0)
"""
distance between boston and portland, clrk66:
-66.531 75.654 4164192.708
distance between boston and portland, WGS84:
-66.530 75.654 4164074.239
testing pickling of Geod instance
distance between boston and portland, clrk66 (from pickle):
-66.531 75.654 4164192.708
distance between boston and portland, WGS84 (from pickle):
-66.530 75.654 4164074.239
inverse transform
from proj.4 invgeod:
b'-66.531\t75.654\t4164192.708\n'
"""
print("from pyproj.Geod.inv:")
az12, az21, dist = gg.inv(lon1pt, lat1pt, lon2pt, lat2pt)
assert_almost_equal((az12, az21, dist), (-66.531, 75.654, 4164192.708), decimal=3)
print("forward transform")
print("from proj.4 geod:")
endlon, endlat, backaz = gg.fwd(lon1pt, lat1pt, az12, dist)
assert_almost_equal((endlon, endlat, backaz), (-123.683, 45.517, 75.654), decimal=3)
print("intermediate points:")
print("from geod with +lat_1,+lon_1,+lat_2,+lon_2,+n_S:")
npts = 4
lonlats = gg.npts(lon1pt, lat1pt, lon2pt, lat2pt, npts)
lonprev = lon1pt
latprev = lat1pt
print(dist / (npts + 1))
print("%6.3f %7.3f" % (lat1pt, lon1pt))
result_dists = (
(-66.53059478766238, 106.79071710136431, 832838.5416198927),
(-73.20928289863558, 99.32289055927389, 832838.5416198935),
(-80.67710944072617, 91.36325611787134, 832838.5416198947),
(-88.63674388212858, 83.32809401477382, 832838.5416198922),
)
for (lon, lat), (res12, res21, resdist) in zip(lonlats, result_dists):
az12, az21, dist = gg.inv(lonprev, latprev, lon, lat)
assert_almost_equal((az12, az21, dist), (res12, res21, resdist))
latprev = lat
lonprev = lon
az12, az21, dist = gg.inv(lonprev, latprev, lon2pt, lat2pt)
assert_almost_equal(
(lat2pt, lon2pt, dist), (45.517, -123.683, 832838.542), decimal=3
)
示例5: getPoint
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
def getPoint(self, horizontal_distance, vertical_distance, azimuth):
"""
Get point with given horizontal, and vertical distances (in km,
vertical distance: positive-downward, negative-upward)
and azimuth (in degrees) from current point.
"""
# TODO: check horizontal distance is positive
g = Geod(ellps="sphere")
longitude, latitude, back_azimuth = g.fwd(
self.longitude, self.latitude, azimuth, horizontal_distance * 1e3
) # 1e3 is needed to convert from km to m
depth = self.depth + vertical_distance
return Point(longitude, latitude, depth)
示例6: test_geod_nans
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
def test_geod_nans(self):
g = Geod(ellps='clrk66')
(azi1, azi2, s12) = g.inv(43, 10, float('nan'), 20)
self.assertTrue(azi1 != azi1)
self.assertTrue(azi2 != azi2)
self.assertTrue(s12 != s12)
(azi1, azi2, s12) = g.inv(43, 10, 53, float('nan'))
self.assertTrue(azi1 != azi1)
self.assertTrue(azi2 != azi2)
self.assertTrue(s12 != s12)
# Illegal latitude is treated as NaN
(azi1, azi2, s12) = g.inv(43, 10, 53, 91)
self.assertTrue(azi1 != azi1)
self.assertTrue(azi2 != azi2)
self.assertTrue(s12 != s12)
(lon2, lat2, azi2) = g.fwd(43, 10, float('nan'), 1e6)
self.assertTrue(lon2 != lon2)
self.assertTrue(lat2 != lat2)
self.assertTrue(azi2 != azi2)
(lon2, lat2, azi2) = g.fwd(43, 10, 20, float('nan'))
self.assertTrue(lon2 != lon2)
self.assertTrue(lat2 != lat2)
self.assertTrue(azi2 != azi2)
(lon2, lat2, azi2) = g.fwd(43, float('nan'), 20, 1e6)
self.assertTrue(lon2 != lon2)
self.assertTrue(lat2 != lat2)
self.assertTrue(azi2 != azi2)
# Illegal latitude is treated as NaN
(lon2, lat2, azi2) = g.fwd(43, 91, 20, 1e6)
self.assertTrue(lon2 != lon2)
self.assertTrue(lat2 != lat2)
self.assertTrue(azi2 != azi2)
# Only lon2 is NaN
(lon2, lat2, azi2) = g.fwd(float('nan'), 10, 20, 1e6)
self.assertTrue(lon2 != lon2)
self.assertTrue(lat2 == lat2)
self.assertTrue(azi2 == azi2)
示例7: divide_line
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
def divide_line(pts, spacing=6.25, runin=0.,
ellps='WGS84', isegment0=0):
"""
Divide a line into equally spaced segments.
Parameters
----------
pts : list of tuples
List of point coordinates in longitude and latitude that define the
line. Format is: ``[(lon_0, lat_0), (lon_1, lat_1), ...,
(lon_n, lat_n)]``.
spacing : float, optional
Spacing between line segments in meters.
runin : float, optional
Length of a "run-in" segment prepended to the line.
ellps : str, optional
Name of the ellipse to use in geodetic calculations. Must be
recognized by :class:`pyproj.Geod`.
isegment0 : int, optional
Sequence number of the first bin.
Returns
-------
bins : list
List of (lon, lat, offset, sequence) tuples.
"""
gd = Geod(ellps=ellps)
x = -runin
_x = -runin
ibin = isegment0
bins = []
for i in range(0, len(pts) - 1):
_x0 = _x
lon0, lat0 = pts[i]
lon1, lat1 = pts[i + 1]
faz, baz, dist = gd.inv(lon0, lat0, lon1, lat1)
while _x <= dist:
lon, lat, _ = gd.fwd(lon0, lat0, faz, _x)
bins += [(lon, lat, x, ibin)]
_x += spacing
x += spacing
ibin += 1
_x -= dist
x -= _x
if _x > 0:
x += _x
bins += [(lon1, lat1, x, ibin - 1)]
return bins
示例8: midpoint_shortest
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
def midpoint_shortest(north_lat, west_lon, south_lat, east_lon):
g = Geod(ellps='WGS84')
af, ab, dist = g.inv(west_lon, north_lat, east_lon, south_lat)
rlon, rlat, az = g.fwd(west_lon, north_lat, af, dist/2)
# decimal places degrees distance
# 0 1 111 km
# 1 0.1 11.1 km
# 2 0.01 1.11 km
# 3 0.001 111 m
# 4 0.0001 11.1 m
# 5 0.00001 1.11 m
# 6 0.000001 0.111 m
# 7 0.0000001 1.11 cm
# 8 0.00000001 1.11 mm
rlon = round(rlon, 6)
rlat = round(rlat, 6)
return rlat, rlon
示例9: get_stat_lat_lon
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
def get_stat_lat_lon(self, print_msg=True):
"""Get station lat/lon"""
if print_msg:
print('calculating station lat/lon')
if not os.path.isfile(self.file):
self.dload_site(print_msg=print_msg)
data = np.loadtxt(self.file, dtype=bytes, skiprows=1).astype(str)
ref_lon, ref_lat = float(data[0, 6]), 0.
e0, e_off, n0, n_off = data[0, 7:11].astype(np.float)
e0 += e_off
n0 += n_off
az = np.arctan2(e0, n0) / np.pi * 180.
dist = np.sqrt(e0**2 + n0**2)
g = Geod(ellps='WGS84')
self.site_lon, self.site_lat = g.fwd(ref_lon, ref_lat, az, dist)[0:2]
return self.site_lat, self.site_lon
示例10: GET
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
#.........这里部分代码省略.........
with_limit = Q(capacity__gte=limit)
with_limit |= Q(capacity__isnull=True)
query = query.filter(with_limit)
has_valid_search_param = True
except ValueError:
# This we don't care about - if someone passes "", or "twenty", just ignore it
pass
except Exception as e:
# Do something to complain??
pass
elif key == "type":
type_values = request.GET.getlist(key)
q_obj = Q()
type_qs = [Q(spottypes__name__exact=v) for v in type_values]
for type_q in type_qs:
q_obj |= type_q
query = query.filter(q_obj).distinct()
has_valid_search_param = True
elif key == "building_name":
building_names = request.GET.getlist(key)
q_obj = Q()
type_qs = [Q(building_name__exact=v) for v in building_names]
for type_q in type_qs:
q_obj |= type_q
query = query.filter(q_obj).distinct()
has_valid_search_param = True
elif re.search('^extended_info:', key):
kwargs = {
'spotextendedinfo__key': key[14:],
'spotextendedinfo__value__in': request.GET.getlist(key)
}
query = query.filter(**kwargs)
has_valid_search_param = True
elif key == "id":
query = query.filter(id__in=request.GET.getlist(key))
has_valid_search_param = True
else:
try:
kwargs = {
'%s__icontains' % key: request.GET[key]
}
query = query.filter(**kwargs)
has_valid_search_param = True
except Exception as e:
if not request.META['SERVER_NAME'] == 'testserver':
print >> sys.stderr, "E: ", e
limit = 20
if 'limit' in request.GET:
if request.GET['limit'] == '0':
limit = 0
else:
limit = int(request.GET['limit'])
if 'distance' in request.GET and 'center_longitude' in request.GET and 'center_latitude' in request.GET:
try:
g = Geod(ellps='clrk66')
top = g.fwd(request.GET['center_longitude'], request.GET['center_latitude'], 0, request.GET['distance'])
right = g.fwd(request.GET['center_longitude'], request.GET['center_latitude'], 90, request.GET['distance'])
bottom = g.fwd(request.GET['center_longitude'], request.GET['center_latitude'], 180, request.GET['distance'])
left = g.fwd(request.GET['center_longitude'], request.GET['center_latitude'], 270, request.GET['distance'])
top_limit = "%.8f" % top[1]
bottom_limit = "%.8f" % bottom[1]
left_limit = "%.8f" % left[0]
right_limit = "%.8f" % right[0]
distance_query = query.filter(longitude__gte=left_limit)
distance_query = distance_query.filter(longitude__lte=right_limit)
distance_query = distance_query.filter(latitude__gte=bottom_limit)
distance_query = distance_query.filter(latitude__lte=top_limit)
has_valid_search_param = True
if len(distance_query) > 0 or 'expand_radius' not in request.GET:
query = distance_query
else:
# If we're querying everything, let's make sure we only return a limited number of spaces...
limit = 10
except Exception as e:
if not request.META['SERVER_NAME'] == 'testserver':
print >> sys.stderr, "E: ", e
#query = Spot.objects.all()
if not has_valid_search_param:
return HttpResponse('[]')
if limit > 0 and limit < len(query):
sorted_list = list(query)
sorted_list.sort(lambda x, y: cmp(self.distance(x, request.GET['center_longitude'], request.GET['center_latitude']), self.distance(y, request.GET['center_longitude'], request.GET['center_latitude'])))
query = sorted_list[:limit]
response = []
for spot in query:
response.append(spot.json_data_structure())
return HttpResponse(json.dumps(response))
示例11: TestRadians
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
class TestRadians(unittest.TestCase):
"""Tests issue #84"""
def setUp(self):
self.g = Geod(ellps='clrk66')
self.boston_d = (-71. - (7. / 60.), 42. + (15. / 60.))
self.boston_r = (math.radians(self.boston_d[0]), math.radians(self.boston_d[1]))
self.portland_d = (-123. - (41. / 60.), 45. + (31. / 60.))
self.portland_r = (math.radians(self.portland_d[0]), math.radians(self.portland_d[1]))
def test_inv_radians(self):
# Get bearings and distance from Boston to Portland in degrees
az12_d, az21_d, dist_d = self.g.inv(
self.boston_d[0],
self.boston_d[1],
self.portland_d[0],
self.portland_d[1],
radians=False)
# Get bearings and distance from Boston to Portland in radians
az12_r, az21_r, dist_r = self.g.inv(
self.boston_r[0],
self.boston_r[1],
self.portland_r[0],
self.portland_r[1],
radians=True)
# Check they are equal
self.assertAlmostEqual(az12_d, math.degrees(az12_r))
self.assertAlmostEqual(az21_d, math.degrees(az21_r))
self.assertAlmostEqual(dist_d, dist_r)
def test_fwd_radians(self):
# Get bearing and distance to Portland
az12_d, az21_d, dist = self.g.inv(
self.boston_d[0],
self.boston_d[1],
self.portland_d[0],
self.portland_d[1],
radians=False)
# Calculate Portland's lon/lat from bearing and distance in degrees
endlon_d, endlat_d, backaz_d = self.g.fwd(
self.boston_d[0],
self.boston_d[1],
az12_d,
dist,
radians=False)
# Calculate Portland's lon/lat from bearing and distance in radians
endlon_r, endlat_r, backaz_r = self.g.fwd(
self.boston_r[0],
self.boston_r[1],
math.radians(az12_d),
dist,
radians=True)
# Check they are equal
self.assertAlmostEqual(endlon_d, math.degrees(endlon_r))
self.assertAlmostEqual(endlat_d, math.degrees(endlat_r))
self.assertAlmostEqual(backaz_d, math.degrees(backaz_r))
# Check to make sure we're back in Portland
self.assertAlmostEqual(endlon_d, self.portland_d[0])
self.assertAlmostEqual(endlat_d, self.portland_d[1])
def test_npts_radians(self):
# Calculate 10 points between Boston and Portland in degrees
points_d = self.g.npts(
lon1=self.boston_d[0],
lat1=self.boston_d[1],
lon2=self.portland_d[0],
lat2=self.portland_d[1],
npts=10,
radians=False)
# Calculate 10 points between Boston and Portland in radians
points_r = self.g.npts(
lon1=self.boston_r[0],
lat1=self.boston_r[1],
lon2=self.portland_r[0],
lat2=self.portland_r[1],
npts=10,
radians=True)
# Check they are equal
for index, dpoint in enumerate(points_d):
self.assertAlmostEqual(dpoint[0], math.degrees(points_r[index][0]))
self.assertAlmostEqual(dpoint[1], math.degrees(points_r[index][1]))
示例12: len
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
lat=lat.replace(' ','')
longi=longi.replace(' ','')
lat=lat.replace(',','')
longi=longi.replace(',','')
# MODIF ERIC => sert a virer 2 derniers 0
if len(lat)>7 :
lat=lat[:-2].decode('ascii', 'ignore')
longi=longi[:-2].decode('ascii', 'ignore')
radius=1000
if frequency in listValeurFreq2100:
radius=4400
frequency="2100"
elif frequency in listValeurFreq900:
radius=9000
frequency="900"
orig_x,orig_y=pyproj.transform(e, wgs84,lat,longi)
left_x,left_y,trash= g.fwd(orig_x,orig_y, int(azimut)-60, radius*0.8)
right_x,right_y,trash= g.fwd(orig_x,orig_y, int(azimut)+60, radius*0.8)
center_x,center_y,trash= g.fwd(orig_x,orig_y, azimut, radius)
#creation ligne dans fichier JSON SANS complement adresse
file_json.write("{\"TAC\" : "+ str(TAC) +",\"LAC\" : "+ str(LAC) +", \"CI\" :"+str(CellID)+", \"dbTime\" : "+ str(dbTime) + ", \"frequency\" : \""+ str(frequency) + "\", \"RAT\" : \""+sys.argv[2]+"\", \"name\" : \""+cellName+"\",\"addr\" :\""+str(address).replace("\"", "").replace("\\", "-")+"\", \"code\" :\""+postalCode+"\", \"city\" :\""+str(city)+"\", \"antenna\" :["+str(orig_x)+","+str(orig_y)+"], \"loc\" : { \"type\" : \"Polygon\", \"coordinates\" : [[["+str(orig_x)+","+str(orig_y)+ "],["+str(left_x)+","+str(left_y)+ "],["+str(center_x)+","+str(center_y)+ "],["+str(right_x)+","+str(right_y)+ "],["+str(orig_x)+","+str(orig_y)+ "]]] } }\n")
finally:
print ("dbTime = ", dbTime)
print ("nbRowCSV =", nbRowCSV)
print ("nbRowWithoutLati =", nbRowWithoutLati)
print ("nbAzimutNotDigit", nbAzimutNotDigit)
f.close() # closing
file_json.close()
file_badRecords.close()
print("Fin traitement fichier CSV")
示例13: filter_on_request
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
#.........这里部分代码省略.........
has_valid_search_param = True
elif key == "id":
query = query.filter(id__in=get_request.getlist(key))
has_valid_search_param = True
else:
try:
kwargs = {
'%s__icontains' % key: get_request[key]
}
query = query.filter(**kwargs)
has_valid_search_param = True
except Exception as e:
if not request_meta['SERVER_NAME'] == 'testserver':
print >> sys.stderr, "E: ", e
for or_q in or_qs:
or_q_obj |= or_q
# This handles all of the OR queries on extended_info we've collected.
query = query.filter(or_q_obj).distinct()
# Always prefetch the related extended info
query = query.prefetch_related('spotextendedinfo_set')
query = chain.filter_query(query)
if chain.has_valid_search_param:
has_valid_search_param = True
limit = int(get_request.get('limit', 20))
if ('distance' in get_request and
'center_longitude' in get_request and
'center_latitude' in get_request):
try:
g = Geod(ellps='clrk66')
lon = get_request['center_longitude']
lat = get_request['center_latitude']
dist = get_request['distance']
# Get coordinates above/right/below/left our location
top = g.fwd(lon, lat, 0, dist)
right = g.fwd(lon, lat, 90, dist)
bottom = g.fwd(lon, lat, 180, dist)
left = g.fwd(lon, lat, 270, dist)
# Get relevant lat or long from these points
top_limit = "%.8f" % top[1]
bottom_limit = "%.8f" % bottom[1]
left_limit = "%.8f" % left[0]
right_limit = "%.8f" % right[0]
distance_query = query.filter(longitude__gte=left_limit,
longitude__lte=right_limit,
latitude__gte=bottom_limit,
latitude__lte=top_limit)
has_valid_search_param = True
if distance_query or 'expand_radius' not in get_request:
query = distance_query
else:
# If we're querying everything, let's make sure we only
# return a limited number of spaces...
limit = 10
except Exception as e:
if not request_meta['SERVER_NAME'] == 'testserver':
print >> sys.stderr, "E: ", e
# query = Spot.objects.all()
elif ('distance' in get_request or
'center_longitude' in get_request or
'center_latitude' in get_request):
if ('distance' not in get_request or
'center_longitude' not in get_request or
'center_latitude' not in get_request):
# If distance, lat, or long are specified in the server
# request; all 3 must be present.
raise RESTException(
"Must specify latitude, longitude, and distance", 400)
# Only do this if spot api because buildings api
# is able to not pass any valid filters
if not has_valid_search_param and api == 'spot':
raise RESTException(
"missing required parameters for this type of search", 400)
# Do this when spot api because building api is not required
# to pass these parameters
if limit > 0 and limit < len(query) and api == 'spot':
try:
lat = get_request['center_latitude']
lon = get_request['center_longitude']
except KeyError:
raise RESTException(
"missing required parameters for this type of search", 400)
def sortfunc(spot):
return self.distance(spot, lon, lat)
sorted_list = sorted(query, key=sortfunc)
query = sorted_list[:limit]
spots = set(query)
spots = chain.filter_results(spots)
return spots
示例14: GET
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
#.........这里部分代码省略.........
query = query.filter(q_obj).distinct()
has_valid_search_param = True
elif re.search('^extended_info:', key):
kwargs = {
'spotextendedinfo__key': key[14:],
'spotextendedinfo__value__in': request.GET.getlist(key)
}
query = query.filter(**kwargs)
has_valid_search_param = True
elif key == "id":
query = query.filter(id__in=request.GET.getlist(key))
has_valid_search_param = True
else:
try:
kwargs = {
'%s__icontains' % key: request.GET[key]
}
query = query.filter(**kwargs)
has_valid_search_param = True
except Exception as e:
if not request.META['SERVER_NAME'] == 'testserver':
print >> sys.stderr, "E: ", e
limit = 20
if 'limit' in request.GET:
if request.GET['limit'] == '0':
limit = 0
else:
limit = int(request.GET['limit'])
if 'distance' in request.GET and 'center_longitude' in request.GET and 'center_latitude' in request.GET:
try:
g = Geod(ellps='clrk66')
top = g.fwd(request.GET['center_longitude'], request.GET['center_latitude'], 0, request.GET['distance'])
right = g.fwd(request.GET['center_longitude'], request.GET['center_latitude'], 90, request.GET['distance'])
bottom = g.fwd(request.GET['center_longitude'], request.GET['center_latitude'], 180, request.GET['distance'])
left = g.fwd(request.GET['center_longitude'], request.GET['center_latitude'], 270, request.GET['distance'])
top_limit = "%.8f" % top[1]
bottom_limit = "%.8f" % bottom[1]
left_limit = "%.8f" % left[0]
right_limit = "%.8f" % right[0]
distance_query = query.filter(longitude__gte=left_limit)
distance_query = distance_query.filter(longitude__lte=right_limit)
distance_query = distance_query.filter(latitude__gte=bottom_limit)
distance_query = distance_query.filter(latitude__lte=top_limit)
has_valid_search_param = True
if len(distance_query) > 0 or 'expand_radius' not in request.GET:
query = distance_query
else:
# If we're querying everything, let's make sure we only return a limited number of spaces...
limit = 10
except Exception as e:
if not request.META['SERVER_NAME'] == 'testserver':
print >> sys.stderr, "E: ", e
#query = Spot.objects.all()
elif 'distance' in request.GET or 'center_longitude' in request.GET or 'center_latitude' in request.GET:
if 'distance' not in request.GET or 'center_longitude' not in request.GET or 'center_latitude' not in request.GET:
# If distance, lat, or long are specified in the server request; all 3 must be present.
return HttpResponseBadRequest("Bad Request")
if not has_valid_search_param:
return HttpResponse('[]')
示例15: GET
# 需要导入模块: from pyproj import Geod [as 别名]
# 或者: from pyproj.Geod import fwd [as 别名]
#.........这里部分代码省略.........
for type_q in type_qs:
q_obj |= type_q
query = query.filter(q_obj).distinct()
has_valid_search_param = True
elif key == "building_name":
building_names = request.GET.getlist(key)
q_obj = Q()
type_qs = [Q(building_name__exact=v) for v in building_names]
for type_q in type_qs:
q_obj |= type_q
query = query.filter(q_obj).distinct()
has_valid_search_param = True
elif key.startswith('extended_info:'):
kwargs = {
'spotextendedinfo__key': key[14:],
'spotextendedinfo__value__in': request.GET.getlist(key)
}
query = query.filter(**kwargs)
has_valid_search_param = True
elif key == "id":
query = query.filter(id__in=request.GET.getlist(key))
has_valid_search_param = True
else:
try:
kwargs = {
'%s__icontains' % key: request.GET[key]
}
query = query.filter(**kwargs)
has_valid_search_param = True
except Exception as e:
if not request.META['SERVER_NAME'] == 'testserver':
print >> sys.stderr, "E: ", e
# Always prefetch the related extended info
query = query.select_related('SpotExtendedInfo')
query = chain.filter_query(query)
if chain.has_valid_search_param:
has_valid_search_param = True
limit = 20
if 'limit' in request.GET:
if request.GET['limit'] == '0':
limit = 0
else:
limit = int(request.GET['limit'])
if 'distance' in request.GET and 'center_longitude' in request.GET and 'center_latitude' in request.GET:
try:
g = Geod(ellps='clrk66')
top = g.fwd(request.GET['center_longitude'], request.GET['center_latitude'], 0, request.GET['distance'])
right = g.fwd(request.GET['center_longitude'], request.GET['center_latitude'], 90, request.GET['distance'])
bottom = g.fwd(request.GET['center_longitude'], request.GET['center_latitude'], 180, request.GET['distance'])
left = g.fwd(request.GET['center_longitude'], request.GET['center_latitude'], 270, request.GET['distance'])
top_limit = "%.8f" % top[1]
bottom_limit = "%.8f" % bottom[1]
left_limit = "%.8f" % left[0]
right_limit = "%.8f" % right[0]
distance_query = query.filter(longitude__gte=left_limit)
distance_query = distance_query.filter(longitude__lte=right_limit)
distance_query = distance_query.filter(latitude__gte=bottom_limit)
distance_query = distance_query.filter(latitude__lte=top_limit)
has_valid_search_param = True
if len(distance_query) > 0 or 'expand_radius' not in request.GET:
query = distance_query
else:
# If we're querying everything, let's make sure we only return a limited number of spaces...
limit = 10
except Exception as e:
if not request.META['SERVER_NAME'] == 'testserver':
print >> sys.stderr, "E: ", e
#query = Spot.objects.all()
elif 'distance' in request.GET or 'center_longitude' in request.GET or 'center_latitude' in request.GET:
if 'distance' not in request.GET or 'center_longitude' not in request.GET or 'center_latitude' not in request.GET:
# If distance, lat, or long are specified in the server request; all 3 must be present.
raise RESTException("Must specify latitude, longitude, and distance", 400)
if not has_valid_search_param:
return JSONResponse([])
if limit > 0 and limit < len(query):
sorted_list = list(query)
try:
sorted_list.sort(lambda x, y: cmp(self.distance(x, request.GET['center_longitude'], request.GET['center_latitude']), self.distance(y, request.GET['center_longitude'], request.GET['center_latitude'])))
query = sorted_list[:limit]
except KeyError:
raise RESTException("missing required parameters for this type of search", 400)
response = []
spots = set(query)
spots = chain.filter_results(spots)
for spot in spots:
response.append(spot.json_data_structure())
return JSONResponse(response)