在我的web应用程序中,我使用psycopg2来查询包含数千个位置点的postgreSQL数据库。假设他们可以被归类为办公室和学校。根据用户当前地图视图显示Google地图标记
约有5500个办公室和550所学校。一次获取所有结果会重载它并导致我的查询被取消。因此,根据用户当前正在查看的地图部分,我只想显示大约100个结果。
我的地图的默认视图是美国。我希望数据库在任何时候只能得到100个结果(100个办公室和100所学校)。如果用户放大,它会更加详细 - 不同的标记会出现。
这是我到目前为止有:
@app.route('/_ajax', methods= ['GET'])
def points():
myConnection = psycopg2.connect(host=hostname, user=username,
password=password, dbname=database)
cur = myConnection.cursor()
bounds = request.args.get('bounds')
officeID = []
office_info = []
cur.execute("""SELECT DISTINCT(o.office_id) from db_office o
WHERE o.location && ST_MakeEnvelope(left, bottom, right, top, 4326)
GROUP BY o.office_id LIMIT 100""")
for row in cur:
officeID.append(row[0])
for o in officeID:
cur.execute("""SELECT ST_Y(o.location::geometry),
ST_X(o.location::geometry),
o.owner, o.office_name from db_office o""".format(o))
for row in cur:
office_info.append([row[0], row[1], row[2], row[3]])
offices = dict(zip(officeID, office_info))
schoolID = []
school_info = []
cur.execute("""SELECT DISTINCT(s.school_id) from db_school s
WHERE s.location && ST_MakeEnvelope(left, bottom, right, top, 4326)
GROUP BY s.school_id LIMIT 100""")
for row in cur:
schoolID.append(row[0])
for s in schoolID:
cur.execute("""SELECT ST_Y(s.location::geometry),
ST_X(s.location::geometry),
s.owner, s.school_name from db_school s""".format(s))
for row in cur:
school_info.append([row[0], row[1], row[2], row[3]])
schools = dict(zip(schoolID, school_info))
return jsonify(offices=offices, schools=schools)
我的AJAX调用,绘制了标记,看起来像这样:
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$(function() {
$.getJSON($SCRIPT_ROOT + '/_ajax?bounds=' + map.getBounds().toUrlValue(),
function(data) {
var places = [];
var marker;
Object.keys(data.offices).forEach(function(key) {
var offices = data.offices[key];
places.push(new google.maps.LatLng(offices[0], offices[1]))
marker = new google.maps.Marker({
position: {lat: offices[0], lng: offices[1]},
map: map
});
});
Object.keys(data.schools).forEach(function(key) {
var schools = data.schools[key];
places.push(new google.maps.LatLng(schools[0], schools[1]))
marker = new google.maps.Marker({
position: {lat: schools[0], lng: schools[1]},
map: map,
});
});
});
总之,这段代码获取办事处的100和100个学校并将其放入字典中,其中ID是键和值是诸如经度和纬度等信息。
这可以工作并显示100个结果,但每个都是不依赖于用户的位置。如何根据用户对地图的看法更改数据库获取的结果?
,我想我需要添加一个'WHERE'参数在我的查询,并做涉及'ST_Within'也许什么?但我不知道究竟是什么 – Sarah