Advertisement
Guest User

Untitled

a guest
Mar 29th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. import psycopg2
  2. import random, string
  3. hostname = 'localhost'
  4. username = 'postgres'
  5. password = '*****'
  6. database = 'pgroute'
  7. myConnection = psycopg2.connect(host=hostname, user=username, password=password, dbname=database )
  8.  
  9. # Simple routine to run a query on a database and print the results:
  10. def doQuery( conn, query ) :
  11. cur = conn.cursor()
  12. cur.execute(query)
  13. if cur.rowcount>0:
  14. return cur.fetchall()
  15. cur.close()
  16.  
  17.  
  18. def doQueryv2( conn, query ) :
  19. cur = conn.cursor()
  20. cur.execute(query)
  21. cur.close()
  22.  
  23. def distance_between_latlongs(long_s, lat_s,long_t, lat_t):
  24. s_geom = 'POINT({} {})'.format(long_s, lat_s)
  25. t_geom = 'POINT({} {})'.format(long_t, lat_t)
  26. doQuery(myConnection,"DROP TABLE IF EXISTS DD")
  27. s_query = "SELECT source FROM ways WHERE source_osm in (SELECT osm_id FROM ways_vertices_pgr ORDER BY the_geom <-> ST_GeometryFromText('{}',4326) LIMIT 1) LIMIT 1".format(s_geom)
  28. source = doQuery( myConnection, s_query )
  29. t_query = "SELECT target FROM ways WHERE target_osm in (SELECT osm_id FROM ways_vertices_pgr ORDER BY the_geom <-> ST_GeometryFromText('{}',4326) LIMIT 1) LIMIT 1 ".format(t_geom)
  30. target = doQuery( myConnection, t_query )
  31. dist_query = "SELECT * INTO DD FROM pgr_dijkstra('SELECT gid AS id, source, target, length AS cost FROM ways',{}, {},directed := false)".format(source[0][0], target[0][0])
  32. doQueryv2( myConnection, dist_query )
  33. length_query = "SELECT SUM(length_m) FROM ways WHERE gid IN (SELECT edge FROM DD)"
  34. distance = doQuery( myConnection, length_query) # GETTING TOTAL DISTANCE
  35. return (distance[0][0]/1000)
  36.  
  37. print(distance_between_latlongs(77.6271,12.9279,77.5643, 13.0031))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement