summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorStefan Hansson <steha708@student.liu.se>2021-01-09 11:27:26 +0100
committerStefan Hansson <steha708@student.liu.se>2021-01-09 11:27:26 +0100
commit978fed58df8322d4195ae112d33a4da193deccc2 (patch)
tree0723e8b92e34371b130b1e1a579a872fad1bad6a
parentff702dfc656b289223e3700e66872c371e365a25 (diff)
parenta526d6b7ce8c2e506dfc0a6356e9e2ce470bc3e4 (diff)
downloadtdde25-978fed58df8322d4195ae112d33a4da193deccc2.tar.gz
Merge branch 'small-fixes' into 'master'
Small fixes See merge request tdde25-2020/tdde25-2020-projekt-sg3-maps-05!18
-rw-r--r--algorithms.py51
-rw-r--r--lib.py2
-rw-r--r--osm_parser.py3
-rw-r--r--server.py46
-rw-r--r--store.py4
-rw-r--r--templates/index.js23
6 files changed, 46 insertions, 83 deletions
diff --git a/algorithms.py b/algorithms.py
index 9f3fd78..8c63968 100644
--- a/algorithms.py
+++ b/algorithms.py
@@ -1,8 +1,14 @@
import heapq
import math
+import store
def length_haversine(p1, p2):
+ """
+ The distance in meters between two coordinates on a sphere.
+
+ Assumes p1=(lat1, lng1) and p2=(lat2, lng2) in degrees.
+ """
lat1 = p1.lat
lng1 = p1.lng
lat2 = p2.lat
@@ -10,67 +16,62 @@ def length_haversine(p1, p2):
lat1, lng1, lat2, lng2 = map(math.radians, [lat1, lng1, lat2, lng2])
dlat = lat2 - lat1
dlng = lng2 - lng1
- a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(
- dlng / 2) ** 2
+ a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlng / 2) ** 2
c = 2 * math.asin(math.sqrt(a))
return 6372797.560856 * c # return the distance in meters
-def grid_search(grid, source_node):
+def grid_search(grid, lat, lng):
"""
Finds closest node to source node by comparing distance to nodes within
nearest tiles in the grid.
"""
- closest_nodes = []
-
- source_key = (int(round(source_node.lat, 3) * 1000), int(round(
- source_node.lng, 3) * 1000))
-
- closest_tiles = find_nodes(0, grid, source_key)
-
- for tile_nodes in closest_tiles:
- closest_nodes.append(get_closest_node(tile_nodes, source_node))
-
+ source_node = store.Node(-1, lat, lng)
+ source_key = (
+ int(round(source_node.lat, 3) * 1000),
+ int(round(source_node.lng, 3) * 1000),
+ )
+
+ closest_tiles = find_nodes(grid, source_key)
+ closest_nodes = [get_closest_node(tile_nodes, source_node)
+ for tile_nodes in closest_tiles]
closest_node_id = get_closest_node(closest_nodes, source_node).id
-
return closest_node_id
-def find_nodes(offset, grid, source_key):
+def find_nodes(grid, source_key, offset=0):
"""
Searches a grid in an outward "spiral" from source node fetching all tiles
which contain nodes.
"""
tiles = None
+ # search further out until we find nodes
while not tiles:
- tiles = look_for_nodes(offset, grid, source_key)
+ tiles = look_for_nodes(grid, source_key, offset)
offset += 1
- return tiles + look_for_nodes(offset + 1, grid, source_key)
+ # include another layer since they might contain closer nodes
+ return tiles + look_for_nodes(grid, source_key, offset + 1)
-def look_for_nodes(offset, grid, source_key):
- """Search for nearest tile containing nodes in an outward spiral."""
+def look_for_nodes(grid, source_key, offset):
+ """Search for nearest tile containing nodes in a spiral."""
tiles = []
for i in range(-offset, offset + 1):
for j in range(-offset, offset + 1):
-
if i in (-offset, offset) or j in (-offset, offset):
-
key = (source_key[0] + j, source_key[1] + i)
-
if key in grid.keys():
tiles.append(grid[key])
-
return tiles
def get_closest_node(nodes, source_node):
"""
- Searches through all nodes in a specified grid and return node
- closes to source node.
+ Search through all nodes in a specified grid and return the node
+ closest to source_node.
"""
min_node = None
min_value = None
diff --git a/lib.py b/lib.py
index 8a31276..d00d7ee 100644
--- a/lib.py
+++ b/lib.py
@@ -162,4 +162,4 @@ def run_server(port=8314):
server_address = ('127.0.0.1', port) # Should make the port a command line argument
server = HTTPServer(server_address, Handler)
print('Starting server on http://{}:{}.'.format(*server_address))
- server.serve_forever() \ No newline at end of file
+ server.serve_forever()
diff --git a/osm_parser.py b/osm_parser.py
index 7145726..b3eed86 100644
--- a/osm_parser.py
+++ b/osm_parser.py
@@ -121,7 +121,8 @@ class OSMParser:
for node in el.iter(OSM_WAYNODE))
tags = {tag.get(OSM_TAG_KEY): tag.get(OSM_TAG_VALUE)
for tag in el.iter(OSM_TAG)
- if self.allow_all or tag.get(OSM_TAG_KEY) in self.way_tags}
+ if self.allow_all
+ or tag.get(OSM_TAG_KEY) in self.way_tags}
# Yield the edge id, the road and the tags
yield {
diff --git a/server.py b/server.py
index 8055e63..33372ba 100644
--- a/server.py
+++ b/server.py
@@ -8,28 +8,17 @@ grids = None
nodes = None
unconnected_nodes = None
+
@get('/')
def index():
global nodes
global grids
global unconnected_nodes
-
nodes, grids, unconnected_nodes = store.extract_osm_nodes("linkoping.osm")
return read_html('templates/index.html')
-@get('/show-area')
-def show_area():
- rect = dict()
- # FIXME: Don't hardcode bikes maybe? Maybe just remove this altogether
- for (k, node) in enumerate(
- store.select_nodes_in_rectangle(nodes['bike'], 58.3984, 58.3990,
- 15.5733, 15.576)):
- rect[node.id] = node.coord_tuple()
- return json.dumps(rect)
-
-
@get('/favicon.ico')
def favicon():
with open("data/favicon.ico", "rb") as image:
@@ -39,34 +28,27 @@ def favicon():
return image_bytes
-@get('/show-unconnected-nodes')
-def show_unconnected_nodes():
- print(f"Showing {len(unconnected_nodes)} unconnected nodes")
- return json.dumps({
- node.id: node.coord_tuple() for node in unconnected_nodes['bike']
- })
-
-
@post('/shortest-path')
def shortest_path(body):
body = json.loads(body)
- transport_mode = body['transport_mode']
+ transport_mode = body['transport_mode']
relevant_grid = grids[transport_mode]
+ relevant_nodes = nodes[transport_mode]
source_id = algorithms.grid_search(relevant_grid,
- store.Node(-1, body['lat1'],
- body['lng1']))
+ body['lat1'],
+ body['lng1'])
target_id = algorithms.grid_search(relevant_grid,
- store.Node(-1, body['lat2'],
- body['lng2']))
-
- relevant_nodes = nodes[transport_mode]
-
- path = algorithms.find_shortest_path(nodes[transport_mode], source_id, target_id)
- response = {"path": [(relevant_nodes[node].lat, relevant_nodes[node].lng) for node in path]}
-
- return json.dumps(response)
+ body['lat2'],
+ body['lng2'])
+
+ path = algorithms.find_shortest_path(nodes[transport_mode],
+ source_id,
+ target_id)
+ return json.dumps({"path": [(relevant_nodes[node].lat,
+ relevant_nodes[node].lng)
+ for node in path]})
run_server()
diff --git a/store.py b/store.py
index 4bca5ee..5438740 100644
--- a/store.py
+++ b/store.py
@@ -189,6 +189,7 @@ suitable_highway_types_bike = [
'path'
]
+
def suitable_bike(way):
tags = way['tags']
@@ -213,8 +214,9 @@ suitable_highway_types_car = [
'tertiary_link',
# Special road types
'living_street', 'service',
- 'pedestrian', 'road' # FIXME: Handle predestrian and road differently?
+ 'pedestrian', 'road' # FIXME: Handle predestrian and road differently?
]
+
def suitable_car(way):
return way['tags']['highway'] in suitable_highway_types_car
diff --git a/templates/index.js b/templates/index.js
index 1422fe6..2fbab55 100644
--- a/templates/index.js
+++ b/templates/index.js
@@ -47,26 +47,3 @@ function handleMapClick ({latlng}){
}
map.on('click', handleMapClick)
-
-
-function showMarker(){
- var marker = L.marker([58.3984, 15.5733]).addTo(map)
-}
-showMarker()
-
-async function showMarkers() {
- res = await fetch('/show-area');
- res = await res.json();
- for (let key in res) {
- var marker = L.marker(res[key]).addTo(map)
- }
-}
-showMarkers()
-
-async function showUnconnectedMarkers() {
- const res = await fetch('/show-unconnected-nodes').then(res => res.json());
- for (let key in res) {
- var marker = L.marker(res[key]).addTo(map)
- }
-}
-//showUnconnectedMarkers()