在我的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