Created
October 20, 2017 16:11
-
-
Save giohappy/f35b8ec39833e8c19c2db2c2b3811c77 to your computer and use it in GitHub Desktop.
MVT Django view snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import shutil | |
import logging | |
import psycopg2 | |
from django.conf import settings | |
from django.shortcuts import render, render_to_response | |
from django.http import HttpResponse | |
import mercantile as mc | |
def _create(z,x,y): | |
bounds = mc.bounds(float(x),float(y),float(z)) | |
xmin = bounds[0] | |
ymin = bounds[1] | |
xmax = bounds[2] | |
ymax = bounds[3] | |
tile = None | |
tilefolder = os.path.join(settings.MVT_CACHEDIR,z,x) | |
tilepath = os.path.join(tilefolder,y+'.pbf') | |
if not os.path.exists(tilepath): | |
logger.info("CACHE MISS") | |
conn = psycopg2.connect('dbname=geo24 user=geo password=geo host=localhost') | |
cur = conn.cursor() | |
query = "SELECT ST_AsMVT(q,'comuni',4096,'geom') FROM (SELECT id,nome,ST_AsMVTGeom(geom,ST_Makebox2d(ST_transform(ST_SetSrid(ST_MakePoint(%s,%s),4326),3857),ST_transform(ST_SetSrid(ST_MakePoint(%s,%s),4326),3857)),4096,0,false) AS geom FROM comuni3857) AS q" | |
cur.execute(query,(xmin,ymin,xmax,ymax)) | |
tile = cur.fetchone()[0] | |
if not os.path.exists(tilefolder): | |
os.makedirs(tilefolder) | |
with open(tilepath, 'wb') as f: | |
f.write(tile) | |
f.close() | |
cur.close() | |
conn.close() | |
else: | |
logger.info("CACHE HIT") | |
tile = open(tilepath, 'rb').read() | |
return tile | |
def view(request): | |
return render_to_response('mvt.html',{}) | |
logger = logging.getLogger('django') | |
def tile(request, z, x, y): | |
tile = _create(z, x, y) | |
return HttpResponse(tile, content_type='application/octet-stream') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment