Esempio n. 1
0
def routeToCSV(lat1,lon1,lat2,lon2, transport):
  """Format a route (as list of nodes)"""
  data = LoadOsm(transport)

  node1 = data.findNode(lat1,lon1)
  node2 = data.findNode(lat2,lon2)

  router = Router(data)
  result, route = router.doRoute(node1, node2)
  if result != 'success':
    return("Fail")

  output = ''
  distance = 0
  for i in route:
    try:
      old_node = new_node
      new_node = data.rnodes[i]
      distance+=geopy.distance.vincenty((new_node[0], new_node[1]), (old_node[0], old_node[1])).km
      print(distance)
    except UnboundLocalError:
      new_node = data.rnodes[i]
    """output = output + "%d,%f,%f\n" % ( \
                  i,
                  node[0],
                  node[1])"""
  return(distance)
Esempio n. 2
0
def routeToGpx(lat1,
               lon1,
               lat2,
               lon2,
               transport,
               description="",
               style="track"):
    """Format a route (as list of nodes) into a GPX file"""
    data = LoadOsm(transport)

    node1 = data.findNode(lat1, lon1)
    node2 = data.findNode(lat2, lon2)
    print("Nodes: {}, {}".format(node1, node2))

    router = Router(data)
    result, route = router.doRoute(node1, node2)
    if result != 'success':
        return

    output = ''
    output = output + "<?xml version='1.0'?>\n"

    output = (output + "<gpx version='1.1' creator='pyroute' "
              "xmlns='http://www.topografix.com/GPX/1/1' "
              "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
              "xsi:schemaLocation='http://www.topografix.com/GPX/1/1 "
              "http://www.topografix.com/GPX/1/1/gpx.xsd'>\n")

    if (style == 'track'):
        output = output + " <trk>\n"
        output = output + "  <name>%s</name>\n" % description
        output = output + "  <trkseg>\n"
        count = 0
        for i in route:
            node = data.rnodes[i]
            output = output + "   <trkpt lat='%f' lon='%f'>\n" % (node[0],
                                                                  node[1])
            output = output + "   </trkpt>\n"
            count = count + 1
        output = output + "  </trkseg>\n  </trk>\n</gpx>\n"

    elif (style == 'route'):
        output = output + " <rte>\n"
        output = output + "  <name>%s</name>\n" % description

        count = 0
        for i in route:
            node = data.rnodes[i]
            output = output + "   <rtept lat='%f' lon='%f'>\n" % (node[0],
                                                                  node[1])
            output = output + "    <name>%d</name>\n" % count
            output = output + "   </rtept>\n"
            count = count + 1
        output = output + " </rte>\n</gpx>\n"

    return (output)
Esempio n. 3
0
def routeToGpx(lat1,lon1,lat2,lon2, transport, description="", style="track"):
  """Format a route (as list of nodes) into a GPX file"""
  data = LoadOsm(transport)

  node1 = data.findNode(lat1,lon1)
  node2 = data.findNode(lat2,lon2)

  router = Router(data)
  result, route = router.doRoute(node1, node2)
  if result != 'success':
    return

  output = ''
  output = output + "<?xml version='1.0'?>\n";
  
  output = output + "<gpx version='1.1' creator='pyroute' xmlns='http://www.topografix.com/GPX/1/1' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd'>\n"
    
  if(style == 'track'):
    output = output + " <trk>\n"
    output = output + "  <name>%s</name>\n" % description
    output = output + "  <trkseg>\n"
    count = 0;
    for i in route:
      node = data.rnodes[i]
      output = output + "   <trkpt lat='%f' lon='%f'>\n" % ( \
        node[0],
        node[1])
      output = output + "   </trkpt>\n"
      count = count + 1
    output = output + "  </trkseg>\n  </trk>\n</gpx>\n"

  elif(style == 'route'):
    output = output + " <rte>\n"
    output = output + "  <name>%s</name>\n" % description
    
    count = 0;
    for i in route:
      node = data.rnodes[i]
      output = output + "   <rtept lat='%f' lon='%f'>\n" % ( \
        node[0],
        node[1])
      output = output + "    <name>%d</name>\n" % count
      output = output + "   </rtept>\n"
      count = count + 1
    output = output + " </rte>\n</gpx>\n"
  
  return(output)
Esempio n. 4
0
def routeToCSV(lat1, lon1, lat2, lon2, transport):
    """Format a route (as list of nodes)"""
    data = LoadOsm(transport)

    node1 = data.findNode(lat1, lon1)
    node2 = data.findNode(lat2, lon2)

    router = Router(data)
    result, route = router.doRoute(node1, node2)
    if result != 'success':
        return ("Fail")

    output = ''
    for i in route:
        node = data.rnodes[i]
        output = output + "%d,%f,%f\n" % ( \
          i,
          node[0],
          node[1])
    return (output)
Esempio n. 5
0
def routeToCSV(lat1,lon1,lat2,lon2, transport):
  """Format a route (as list of nodes)"""
  data = LoadOsm(transport)

  node1 = data.findNode(lat1,lon1)
  node2 = data.findNode(lat2,lon2)

  router = Router(data)
  result, route = router.doRoute(node1, node2)
  if result != 'success':
    return("Fail")

  output = ''
  for i in route:
    node = data.rnodes[i]
    output = output + "%d,%f,%f\n" % ( \
      i,
      node[0],
      node[1])
  return(output)
Esempio n. 6
0
class osmData(pyrouteModule):
  def __init__(self, modules):
    pyrouteModule.__init__(self,modules)
    self.data = LoadOsm(None)
  
  def defaultFilename(self):
    return("data/routing.osm")
  
  def loadDefault(self):
    self.load(self.defaultFilename())
    
  def load(self,filename):
    print "Loading OSM data from %s"%filename
    self.data.loadOsm(filename)
  
  def download(self,params):
    ownpos = self.get('ownpos')
    if(not ownpos['valid']):
      print "Can only download around own position"
      return

    lat = ownpos['lat']
    lon = ownpos['lon']
    size = 0.2
    
    url = "http://informationfreeway.org/api/0.5/way[bbox=%1.4f,%1.4f,%1.4f,%1.4f][highway|railway|waterway=*]" % (lon-size,lat-size,lon+size,lat+size)
    
    print "downloading %s" % url
    
    filename = self.defaultFilename()
    
    if(os.path.exists(filename)):
      print "Removing existing file"
      os.remove(filename)
      
    urllib.urlretrieve(url, filename)
    
    print "Finished downloading"
    self.load(filename)
Esempio n. 7
0
def load_osm(osm_path):
    """ 
    Use pyroutelib to load OSM data into native data structures. 

    Needed fields from LoadOsm object:
    .nodes -- locations of nodes
    .routeTypes -- use to check that 'foot' exists
    .routeableNodes -- use to populate Quadtree
    .routing -- the graph itself
    """
    osm = LoadOsm(osm_path)
    assert 'foot' in osm.routeTypes, "This OSM data has no walking routes!"
    return osm
Esempio n. 8
0
class osmData(pyrouteModule):
  def __init__(self, modules):
    pyrouteModule.__init__(self,modules)
    self.data = LoadOsm('cycle')

  def defaultFilename(self):
    return("data/routing.osm")

  def loadDefault(self):
    self.load(self.defaultFilename())

  def load(self,filename):
    print "Loading OSM data from %s"%filename
    self.data.loadOsm(filename)

  def download(self,params):
    ownpos = self.get('ownpos')
    if(not ownpos['valid']):
      print "Can only download around own position"
      return

    lat = ownpos['lat']
    lon = ownpos['lon']
    size = 0.2

    url = "http://open.mapquestapi.com/xapi/api/0.6/way[bbox=%1.4f,%1.4f,%1.4f,%1.4f][highway|railway|waterway=*]" % (lon-size,lat-size,lon+size,lat+size)

    print "downloading %s" % url

    filename = self.defaultFilename()

    if(os.path.exists(filename)):
      print "Removing existing file"
      os.remove(filename)

    urllib.urlretrieve(url, filename)

    print "Finished downloading"
    self.load(filename)
Esempio n. 9
0
        # Try to insert, keeping the queue ordered by decreasing worst-case
        # distance
        count = 0
        for test in self.queue:
            if test['maxdistance'] > queueItem['maxdistance']:
                self.queue.insert(count, queueItem)
                break
            count = count + 1
        else:
            self.queue.append(queueItem)


if __name__ == "__main__":
    # Test suite - do a little bit of easy routing in birmingham
    data = LoadOsm("cycle")

    node1 = data.findNode(52.552394, -1.818763)
    node2 = data.findNode(52.563368, -1.818291)

    print(node1)
    print(node2)

    router = Router(data)
    result, route = router.doRoute(node1, node2)
    if result == 'success':
        # list the nodes
        print(route)

        # list the lat/long
        for i in route:
Esempio n. 10
0
      'nodes': queueSoFar['nodes'] + "," + str(end),
      'end': end}
    
    # Try to insert, keeping the queue ordered by decreasing worst-case distance
    count = 0
    for test in self.queue:
      if test['maxdistance'] > queueItem['maxdistance']:
        self.queue.insert(count,queueItem)
        break
      count = count + 1
    else:
      self.queue.append(queueItem)

if __name__ == "__main__":
  # Test suite - do a little bit of easy routing in birmingham
  data = LoadOsm("cycle")

  node1 = data.findNode(52.552394,-1.818763)
  node2 = data.findNode(52.563368,-1.818291)

  print(node1)
  print(node2)

  router = Router(data)
  result, route = router.doRoute(node1, node2)
  if result == 'success':
    # list the nodes
    print(route)

    # list the lat/long
    for i in route:
Esempio n. 11
0
def route_geojson(input_f, output_f, mode='foot', local_planet=None):
    osmdata = LoadOsm(mode)

    if local_planet is not None:
        osmdata.getArea = lambda lat, lon: None
        osmdata.api = None
        print('loading osm data (this may take a while)...')
        osmdata.loadOsm(local_planet)

    print('starting router...')
    router = Router(osmdata)

    print('processing shapes...')
    # First load up the shapes
    layer = geojson.load(input_f)
    non_linestring = 0
    not_two_points = 0
    unsuccessful = 0
    successful = 0
    very_long = 0
    first = True

    output_f.write('{"crs": {"type": "name", "properties": '
                   '{"name": "urn:ogc:def:crs:OGC:1.3:CRS84"}}, '
                   '"type": "FeatureCollection", "features": [\n')

    for feature in layer.features:
        if feature.geometry.type != 'LineString':
            # Not a LineString, skip!
            non_linestring += 1
            continue

        geometry = list(feature.geometry.coordinates)
        if len(geometry) != 2:
            # LineString with other than two points, skip!
            not_two_points += 1
            continue

        if pythagoras(*geometry[0] + geometry[1]) > 1.0:
            very_long += 1
            continue

        # Now find a route. Data has x,y coordinates, but function is y,x, so
        # reverse the parameters.
        start = osmdata.findNode(*geometry[0][::-1])
        end = osmdata.findNode(*geometry[1][::-1])

        result, route = router.doRoute(start, end)
        if result != 'success':
            unsuccessful += 1
            continue

        routed_geometry = []
        for node_id in route:
            node = osmdata.rnodes[node_id]
            routed_geometry.append((node[1], node[0]))

        new_feature = geojson.Feature(
            geometry=geojson.LineString(coordinates=routed_geometry),
            properties=feature.properties,
            id=feature.id,
        )

        if not first:
            output_f.write(',\n')
        first = False

        geojson.dump(new_feature, output_f)
        output_f.flush()
        successful += 1
    output_f.write('\n]}\n')
    output_f.close()

    print(
        '%d LineStrings routed. Errors: %d non-linestring(s), '
        '%d linestring(s) with !=2 points, %d very long, '
        '%d unsuccessful routings' %
        (successful, non_linestring, not_two_points, very_long, unsuccessful))
Esempio n. 12
0
 def __init__(self, modules):
   pyrouteModule.__init__(self,modules)
   self.data = LoadOsm(None)
Esempio n. 13
0
 def __init__(self, modules):
   pyrouteModule.__init__(self,modules)
   self.data = LoadOsm('cycle')