Guest User

Untitled

a guest
Oct 23rd, 2017
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import os
  4. import shutil
  5. import math
  6. import psycopg2
  7.  
  8. from flask import Flask, render_template, make_response
  9. app = Flask(__name__)
  10.  
  11. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  12. CACHE_DIR = os.path.join(BASE_DIR,'cache')
  13.  
  14. def tile_ul(x, y, z):
  15. n = 2.0 ** z
  16. lon_deg = x / n * 360.0 - 180.0
  17. lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * y / n)))
  18. lat_deg = math.degrees(lat_rad)
  19. return lon_deg,lat_deg
  20.  
  21. def get_tile(z,x,y):
  22. xmin,ymin = tile_ul(x, y, z)
  23. xmax,ymax = tile_ul(x + 1, y + 1, z)
  24.  
  25. tile = None
  26.  
  27. tilefolder = "{}/{}/{}".format(CACHE_DIR,z,x)
  28. tilepath = "{}/{}.pbf".format(tilefolder,y)
  29. if not os.path.exists(tilepath):
  30. conn = psycopg2.connect('dbname=geo24 user=geo password=geo host=localhost')
  31. cur = conn.cursor()
  32.  
  33. query = "SELECT ST_AsMVT(tile) FROM (SELECT id, name, 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 admin_areas) AS tile"
  34. cur.execute(query,(xmin,ymin,xmax,ymax))
  35. tile = str(cur.fetchone()[0])
  36.  
  37. if not os.path.exists(tilefolder):
  38. os.makedirs(tilefolder)
  39.  
  40. with open(tilepath, 'wb') as f:
  41. f.write(tile)
  42. f.close()
  43.  
  44. cur.close()
  45. conn.close()
  46. else:
  47. tile = open(tilepath, 'rb').read()
  48.  
  49. return tile
  50.  
  51. @app.route('/')
  52. def index():
  53. return render_template('index.html')
  54.  
  55. @app.route('/tiles')
  56. @app.route('/tiles/<int:z>/<int:x>/<int:y>', methods=['GET'])
  57. def tiles(z=0, x=0, y=0):
  58. tile = get_tile(z, x, y)
  59. response = make_response(tile)
  60. response.headers['Content-Type'] = "application/octet-stream"
  61. return response
Add Comment
Please, Sign In to add comment