Esempio n. 1
0
    def __init__(self, min_lon, min_lat, max_lon, max_lat):
        self.__api = osmapi.OsmApi()
        self.__tmp = self.__api.Map(min_lon, min_lat, max_lon, max_lat)
        self.__ret = []

        for e in self.__tmp:
            try:
                try:
                    try:
                        type_ = e['type']
                        timestamp = e['data']['timestamp']
                        id = e['data']['id']
                        lat = e['data']['lat']
                        lon = e['data']['lon']
                        uid = e['data']['uid']
                        user = str(e['data']['user'])
                        tag = e['data']['tag']
                        delta_days = (osmapi.datetime.today() - timestamp).days

                        if type_ == 'node':
                            self.__ret.append(
                                [id, lat, lon, uid, timestamp, user])
                            # print(e)
                            # print('type:', type_)
                            # print('timestamp:', timestamp)
                            # print(self.__ret[-1])
                            # print('------------------------------------')
                    except KeyError:
                        pass
                except IndexError:
                    pass
            except UnicodeEncodeError as err:
                print(err, str(e) + '\n')
Esempio n. 2
0
def hours():
    center = request.args.get('center', '43.5744,7.0192').replace("%2C", ",")
    radius = 0.01
    rect = makeRect(center, radius)
    when = request.args.get('when', 'now')
    pinned = getPinned()

    if when == "now":
        now = datetime.datetime.today()  # TODO tz awareness
        day, hour = DAYS[now.weekday()], now.strftime("%H:%M")
    else:
        day, hour = when.split(" ")

    osm = osmapi.OsmApi()
    pinnedResults = []
    for p in pinned:
        node = osm.NodeGet(p)
        pinnedResults.append(
            makeNode(node['tag']['name'], node['lat'], node['lon'], node['id'],
                     getTypeFromTags(node['tag']),
                     node['tag']['opening_hours'], day, hour, center))

    o = overpy.Overpass()
    q = f"node[opening_hours]({rect});out;"  # TODO retrieve also ways (eg. a whole building is a shop)
    r = o.query(q)
    results = []
    for node in r.nodes:
        results.append(
            makeNode(node.tags.get('name'), node.lat, node.lon, node.id,
                     getTypeFromTags(node.tags), node.tags['opening_hours'],
                     day, hour, center))

    return render_template('tabla.html', nodes=results, pinned=pinnedResults)
def push_to_local_osm(ways):
    localApi = osmapi.OsmApi(api=LOCAL_OSM_URL,
                             username=LOCAL_OSM_USER,
                             password=LOCAL_OSM_PASS)
    localApi.ChangesetCreate({u"comment": u"%s" % CHANGESET_DESCRIPTION})

    currCount = 0
    for way in ways:
        createdNodes = []
        currCount += 1
        print(way)
        way = add_masterlist_info(way)
        for node in way.nodes:
            newNode = localApi.NodeCreate({
                u"lon": node.lon,
                u"lat": node.lat,
                u"tag": {}
            })
            createdNodes.append(newNode['id'])

        # add first node to the end so that it closes the way
        createdNodes.append(createdNodes[0])

        newWay = localApi.WayCreate({u"nd": createdNodes, u"tag": way.tags})
        print(f'newWay ({currCount}/{len(ways)}): {newWay}')

    localApi.ChangesetClose()
Esempio n. 4
0
def api():
    api_base = "http://api06.dev.openstreetmap.org"
    api = osmapi.OsmApi(api=api_base)
    api._session._sleep = mock.Mock()

    yield api
    api.close()
Esempio n. 5
0
def parse_osm(input_file_path, output_file_path):
    input_file = open(input_file_path, 'r')
    input_file_data = input_file.read()
    input_file.close()

    api = osmapi.OsmApi()
    osm_dictionary = api.ParseOsm(input_file_data)

    root = etree.fromstring(input_file_data)
    min_longitude = float(root[0].get('minlon'))
    min_latitude = float(root[0].get('minlat'))
    max_longitude = float(root[0].get('maxlon'))
    max_latitude = float(root[0].get('maxlat'))

    osm = Osm2Dict(min_longitude, min_latitude, max_longitude, max_latitude,
                   osm_dictionary)

    road_point_width_map, model_pose_map, building_location_map = osm.getMapDetails(
    )

    sdf_file = GetSDF()
    sdf_file.addSphericalCoords(osm.getLat(), osm.getLon())
    sdf_file.addScene(False, False)
    sdf_file.includeModel("sun")
    sdf_file.addGround(10000, 10000)

    for building_name in building_location_map.keys():
        location = building_location_map[building_name]
        mean = location['mean']
        points = location['points']
        color = location['color']
        sdf_file.addBuilding(mean, points, building_name, color)

    print('|-----------------------------------')
    print('| Number of Roads: ' + str(len(road_point_width_map.keys())))
    print('|-----------------------------------')

    for idx, road in enumerate(road_point_width_map.keys()):
        sdf_file.addRoad(road, road_point_width_map[road]['texture'])
        sdf_file.setRoadWidth(road_point_width_map[road]['width'], road)
        points = road_point_width_map[road]['points']

        print('| Road' + str(idx + 1) + ': ' + road.encode('utf-8').strip())
        print "|  -- Width: ", str(road_point_width_map[road]['width'])

        x_data = points[0, :]
        y_data = points[1, :]

        if len(x_data) < 3:
            for j in np.arange(len(x_data)):
                sdf_file.addRoadPoint([x_data[j], y_data[j], 0], road)
        else:
            x, y = catmull_rom(x_data, y_data, 10)
            for point in range(len(x)):
                sdf_file.addRoadPoint([x[point], y[point], 0], road)

    print('|')
    print('|-----------------------------------')
    print('| Generating the SDF world file...')
    sdf_file.writeToFile(output_file_path)
def get_coords_for_way(wid, prev_last_node=-1):
    osm = osmapi.OsmApi()
    lat = {}
    lon = {}
    coords_list = []
    way_details = osm.WayFull(wid)
    # print("Processing way %d with %d nodes" % (wid, len(way_details) - 1))
    for e in way_details:
        if e["type"] == "node":
            lat[e["data"]["id"]] = e["data"]["lat"]
            lon[e["data"]["id"]] = e["data"]["lon"]
        if e["type"] == "way":
            assert e["data"]["id"] == wid, "Way id mismatch! %d != %d" % (
                e["data"]["id"], wl[0])
            ordered_node_array = e["data"]["nd"]
            if prev_last_node != -1 and ordered_node_array[
                    -1] == prev_last_node:
                print(
                    "LAST entry %d matches prev_last_node %d, REVERSING order for %d"
                    % (ordered_node_array[-1], prev_last_node, wid))
                ordered_node_array = list(reversed(ordered_node_array))
            for on in ordered_node_array:
                # Returning lat,lon instead of lon,lat to be consistent with
                # the returned values from OSRM. Since we manually swap the
                # values later
                coords_list.append([lat[on], lon[on]])
    return ordered_node_array, coords_list
 def __init__(self, web_api, username, password):
     osm_api = osmapi.OsmApi(api=web_api,
                             username=username,
                             password=password)
     self.osm_api = osm_api
     # variable to keep track of buildings synced
     self.ways_added = {}
Esempio n. 8
0
def download_changesets(changeset_ids: list, last_id_dl=None):
    """

    :param changeset_ids:
    :param last_id_dl: If previous attempt to download failed due to request limiting etc.
                        Provide the last queried id to resume where you left off
    :return: None... Writes to a compressed pickle file.
    """
    num_cs = 46486
    N = 1000
    num_dl = 0

    if last_id_dl != None:
        changeset_ids = [
            cs_id[0] for cs_id in changeset_ids if cs_id[0] > last_id_dl
        ]

    batches = (changeset_ids[i:i + N] for i in range(0, len(changeset_ids), N))
    api = osmapi.OsmApi()
    for b in batches:
        cs_data = []
        for cs_id in b:
            cs_data.append(api.ChangesetGet(cs_id))

        print("{0:.2f}% Downloaded. Last ID: {1}".format(
            num_dl / num_cs, cs_data[-1]))
        write_pickle_zip("./data/changeset_data.pklz", cs_data)
        num_dl += N
        time.sleep(30)
Esempio n. 9
0
def getOsmFile(box, outputFile='map.osm', inputOsmFile=''):
    '''downloads the data file for the specified bounding box
       stores the file as outputFile, if inputOsmFile is not specified
       and also converts the data in the form of a dictionary'''
    if not box and not inputOsmFile:
        return None

    dataDict = {}
    if inputOsmFile:
        outputFile = inputOsmFile
    else:
        try:
            urlString = 'http://api.openstreetmap.org/api/0.6/map?bbox=' + str(
                box)[1:-1].replace(" ", "")
            print urlString
            osmFile = urllib2.urlopen(urlString)
        except urllib2.HTTPError:
            print("\nError:\tPlease check the bounding box input arguments" +
                  "\n\tFormat: MinLon MinLat MaxLon MaxLat")
            return {}
        osm = open(outputFile, 'w')

        osm.write(osmFile.read())

        osm.close()

    osmRead = open(outputFile, 'r')

    myapi = osmapi.OsmApi()

    dataDict = myapi.ParseOsm(osmRead.read())

    osmRead.close()

    return dataDict
Esempio n. 10
0
 def __init__(self, transport):
     """Initialise an OSM-file parser"""
     self.routing = {}
     self.rnodes = {}
     self.transport = transport
     self.tiles = {}
     self.weights = weights.RoutingWeights()
     self.api = osmapi.OsmApi(api="api.openstreetmap.org")
Esempio n. 11
0
def main():

    db = '../db.sqlite'
    connection = sqlite3.connect(db)
    connection.row_factory = sqlite3.Row
    connection.enable_load_extension(True)
    cursor = connection.cursor()
    cursor.execute('SELECT load_extension("mod_spatialite")')

    api = osmapi.OsmApi(passwordfile="/etc/osmpassword.txt")
    api.ChangesetCreate({u"comment": u"Inserted housenumbers"})

    query = """SELECT *,
            Y(Transform(Geometry, 4326)) AS LAT,
            X(Transform(Geometry, 4326)) AS LON
            FROM civici_prov_principali WHERE desvia = 'VIA A. APOLLONIO'"""
    cursor.execute(query)

    civici = cursor.fetchall()

    for civico in civici:

        if (civico["ingresso"] == "cancello"):
            node = {
                u"lon": round(civico["LON"], 6),
                u"lat": round(civico["LAT"], 6),
                u"tag": {
                    u"addr:housenumber":
                    str(civico["civico_alf"]).encode('utf-8'),
                    u"addr:street": get_via_osm(civico["desvia"]),
                    u"addr:postcode": str(civico["cap"]).encode('utf-8'),
                    u"addr:city": str(civico["sobborgo"]).encode('utf-8'),
                    u"barrier": u"gate"
                }
            }
        else:
            node = {
                u"lon": round(civico["LON"], 6),
                u"lat": round(civico["LAT"], 6),
                u"tag": {
                    u"addr:housenumber":
                    str(civico["civico_alf"]).encode('utf-8'),
                    u"addr:street": get_via_osm(civico["desvia"]),
                    u"addr:postcode": str(civico["cap"]).encode('utf-8'),
                    u"addr:city": str(civico["sobborgo"]).encode('utf-8')
                }
            }

        print api.NodeCreate(node)

        cursor.execute(
            """DELETE FROM civici_prov_principali WHERE PK_UID = """ +
            str(civico["PK_UID"]))
        connection.commit()

        time.sleep(10)

    api.ChangesetClose()
def traffic(SPEED,GPS):
  SPEED_ARR = np.array(SPEED)
  GPS_ARR = np.array(GPS)
  A = len(SPEED)
  for i in range(0, A):
      SPEED_ARR[i] = float(SPEED_ARR[i])
  LOW_CONGESTION_COUNT = 0
  MODERATE_CONGESTION_COUNT = 0
  HIGH_CONGESTION_COUNT = 0

  LOW_CONGESTION_LOC = []
  MODERATE_CONGESTION_LOC = []
  HIGH_CONGESTION_LOC = []

  for i in range(0, A):
      if SPEED_ARR[i] < 10.00:
          HIGH_CONGESTION_COUNT += 1
          HIGH_CONGESTION_LOC.append(GPS_ARR[i])
      elif SPEED_ARR[i] > 10.00 and SPEED_ARR[i] < 20.00:
          MODERATE_CONGESTION_COUNT += 1
          MODERATE_CONGESTION_LOC.append(GPS_ARR[i])
      elif SPEED_ARR[i] > 20.00:
          LOW_CONGESTION_COUNT += 1
          LOW_CONGESTION_LOC.append(GPS_ARR[i])

  print("No. Of High Congestion Areas:%.2f"%HIGH_CONGESTION_COUNT)
  print("No. Of Moderate Congestion Areas:%.2f"%MODERATE_CONGESTION_COUNT)
  print("No. Of Low Congestion Areas:%.2f"%LOW_CONGESTION_COUNT)
  print()

  api = osmapi.OsmApi()
  print(api.NodeGet(123))
  api = osmapi.OsmApi(api="https://api06.dev.openstreetmap.org", username="******", password="******")
  api.ChangesetCreate({u"comment": u"Traffic Congestion"})

  for i in range(len(LOW_CONGESTION_LOC)):
      print(api.NodeCreate({u"lon":LOW_CONGESTION_LOC[i][0], u"lat":LOW_CONGESTION_LOC[i][1], u"LCA": {}}))

  for i in range(len(MODERATE_CONGESTION_LOC)):
      print(api.NodeCreate({u"lon":MODERATE_CONGESTION_LOC[i][0], u"lat":MODERATE_CONGESTION_LOC[i][1], u"MCA": {}}))

  for i in range(len(HIGH_CONGESTION_LOC)):
      print(api.NodeCreate({u"lon":HIGH_CONGESTION_LOC[i][0], u"lat":HIGH_CONGESTION_LOC[i][1], u"HCA": {}}))
  api.ChangesetClose()
  print()
Esempio n. 13
0
 def test_passwordfile(self):
     path = os.path.join(
         __location__,
         'fixtures',
         'passwordfile.txt'
     )
     my_api = osmapi.OsmApi(passwordfile=path)
     self.assertEquals('testosm', my_api._username)
     self.assertEquals('testpass', my_api._password)
Esempio n. 14
0
def auth_api():
    api_base = "http://api06.dev.openstreetmap.org"
    api = osmapi.OsmApi(api=api_base,
                        username='******',
                        password='******')
    api._session._sleep = mock.Mock()

    yield api
    api.close()
    def GetData(self, src="api"):

        #get data
        if src == "api":
            Api = osmapi.OsmApi()
            try:
                DataRel = Api.RelationFull(self._relid)
                if not DataRel:
                    self.error("La relation n'existe pas")
            except:
                self.error("La relation n'existe pas")

        elif src == "bin":
            try:
                import Pyro.core
                bin = Pyro.core.getProxyForURI("PYROLOC://osm3/OsmBin")
                DataRel = bin.RelationFullRecur(self._relid)
                if not DataRel:
                    self.error("La relation n'existe pas")
            except:
                self.error("La relation n'existe pas")

        #
        self._relations = [
            c[u'data'] for c in DataRel if c[u'type'] == u'relation'
        ]
        self._relation = {}
        for rel in self._relations:
            self._relation[rel[u'id']] = rel

        self._ways = [c[u'data'] for c in DataRel if c[u'type'] == u'way']
        self._way = {}
        for way in self._ways:
            self._way[way[u'id']] = way

        self._nodes = [c[u'data'] for c in DataRel if c[u'type'] == u'node']
        self._node = {}
        for node in self._nodes:
            self._node[node[u'id']] = node

        #Bbox
        self._mLon = float(180)
        self._mLat = float(90)
        self._MLon = float(-180)
        self._MLat = float(-90)
        for node in self._nodes:
            self._mLon = min(self._mLon, node[u'lon'])
            self._mLat = min(self._mLat, node[u'lat'])
            self._MLon = max(self._MLon, node[u'lon'])
            self._MLat = max(self._MLat, node[u'lat'])
        self._mLon -= 0.001
        self._mLat -= 0.001
        self._MLon += 0.001
        self._MLat += 0.001
Esempio n. 16
0
def find(debug=False):
    """Display park data in the bounding box."""
    data = []
    parks = 0

    # Create an API connection
    log.info("connecting to OSM...")
    api = osmapi.OsmApi()

    for count, (out_bbox, sections) in enumerate(BBOXES, start=1):

        # Iterate through each section of the bounding box
        log.info("loading bounding box %s...", count)
        log.debug("outer bounding box: %s", out_bbox)
        height = (out_bbox['max_lat'] - out_bbox['min_lat']) / sections
        width = (out_bbox['max_lon'] - out_bbox['min_lon']) / sections
        for row in range(sections):
            if debug and row != int(sections / 2):
                continue
            for col in range(sections):
                if debug and col != int(sections / 2):
                    continue

                log.info("loading region (%s, %s) of (%s, %s) ...", row, col,
                         sections - 1, sections - 1)

                # define an inner bounding box
                bbox = {
                    'min_lat': out_bbox['min_lat'] + row * height,
                    'min_lon': out_bbox['min_lon'] + col * width,
                    'max_lat': out_bbox['min_lat'] + (row + 1) * height,
                    'max_lon': out_bbox['min_lon'] + (col + 1) * width
                }
                log.debug("inner bounding box: %s", bbox)

                # get a list of points in a given bounding box
                # http://osmapi.divshot.io/#OsmApi.OsmApi.Map
                points = api.Map(**bbox)

                # find all parks in the list of points
                for point in points:
                    if point['type'] == 'node':
                        data.append(point)
                    if point['type'] in ('way', 'relation'):
                        if any(
                            ((point['data']['tag'].get('leisure') == 'park'),
                             (point['data']['tag'].get('name')
                              in PARK_NAMES))):
                            log.debug("found park: %s", point['data'])
                            data.append(point)
                            parks += 1

    log.info("found %s parks", parks)
    return data
Esempio n. 17
0
 def run(self):
     api = osmapi.OsmApi(api="https://api06.dev.openstreetmap.org",
                         username=u"jlefebvre",
                         password=u"yY@o6LNDHM")
     api.ChangesetCreate({u"cinemas d'ile de france": u"MyCineMap"})
     all = pandas.read_sql("SELECT * FROM cine",
                           con=DB_ENGINES[self.engine_name])
     for index, row in all.iterrows():
         values = row["geo"].split(",")
         api.NodeCreate({u"lon": values[1], u"lat": values[0], u"tag": {}})
     api.ChangesetClose()
     self.task_complete = True
Esempio n. 18
0
def get_osm_geom(osm_type, osm_id):
    osm_api = osmapi.OsmApi()
    try:
        if osm_type == 'way':
            nodes = osm_api.WayFull(osm_id)
            ordered_node_list = []
            way_dict = {}
            way_order = []
            for item in nodes:
                if item.get('type') == 'node':
                    node = item.get('data')
                    lat = node.get('lat')
                    lon = node.get('lon')
                    way_dict[node.get('id')] = [lat, lon]
                elif item.get('type') == 'way':
                    way = item.get('data')
                    way_order = way.get('nd')
            for node_id in way_order:
                ordered_node_list.append(way_dict.get(node_id))
            return ordered_node_list
        elif osm_type == 'node':
            node = osm_api.NodeGet(osm_id)
            lat = node.get('lat')
            lon = node.get('lon')
            return [lat, lon]
        elif osm_type == 'relation':
            nodes = osm_api.RelationFull(osm_id)
            ordered_node_list = []
            way_dict = {}
            ways = {}
            members = []
            for item in nodes:
                if item.get('type') == 'node':
                    node = item.get('data')
                    lat = node.get('lat')
                    lon = node.get('lon')
                    way_dict[node.get('id')] = [lat, lon]
                elif item.get('type') == 'way':
                    way = item.get('data')
                    ways[way.get('id')] = way.get('nd')
                elif item.get('type') == 'relation':
                    relation = item.get('data')
                    members = relation.get('member')
            # choose only outer member since mapbox does not support multipolygons
            for rel_member in members:
                if rel_member.get('role') == 'outer': member = rel_member
            for node_id in ways.get(member.get('ref')):
                ordered_node_list.append(way_dict.get(node_id))
            return ordered_node_list
    except Exception as e:
        logger.error(traceback.format_exc())
        return []
Esempio n. 19
0
    def __init__(self, transport, localfile=""):
        """Initialise an OSM-file parser"""
        self.routing = {}
        self.rnodes = {}
        self.tiles = []
        self.transport = transport if transport != "cycle" else "bicycle" # Osm uses bicycle in tags
        self.localFile = localfile
        self.type = TYPES[transport]

        if self.localFile:
            self.loadOsm(self.localFile)
            self.api = None

        else:
            self.api = osmapi.OsmApi(api="api.openstreetmap.org")
Esempio n. 20
0
    def setupMock(self, status=200):
        mock_response = mock.Mock()
        mock_response.status_code = status
        mock_response.reason = "test reason"
        mock_response.content = 'test response'

        self.mock_session = mock.Mock()
        self.mock_session.request = mock.Mock(return_value=mock_response)
        self.mock_session.close = mock.Mock()
        self.mock_session.auth = ('testuser', 'testpassword')

        self.api = osmapi.OsmApi(api=self.api_base,
                                 session=self.mock_session,
                                 username='******',
                                 password='******')
Esempio n. 21
0
def get_overpass_way_feature(Pts, index_used, lat, lon, lim_dist, query_name):
    tree = ET.parse("Overpass.xml")
    root = tree.getroot()
    allways = root.findall('way')
    i_name = 1
    api = osmapi.OsmApi()

    for way in allways:

        for tag in way.findall('tag'):
            if tag.attrib['k'] == 'name':
                name = tag.attrib['v']
                i_name -= 1

        way_id = way.get('id')
        nodes_id = api.WayGet(way_id)
        nodes = api.NodesGet(nodes_id['nd'])
        lat2 = []
        lon2 = []
        for node_id in nodes:
            lat2.append(nodes[node_id]['lat'])
            lon2.append(nodes[node_id]['lon'])
        (match, near_lon, near_lat,
         index) = find_nearest_way(lon, lat, lon2, lat2, lim_dist)

        if match == 1:
            i_name = i_name + 1
            [lon_new, lat_new,
             new_gpx_index] = add_new_point(lon, lat, near_lon, near_lat,
                                            index)
            name = query_name + str(
                i_name)  # set by default in case proper tag not found
            ele = ''  # set default in case proper tag not found

            for tag in way.findall('tag'):
                if tag.attrib['k'] == 'name':
                    name = tag.attrib['v']
                    i_name -= 1
            # Because only 1 POI is possible per GPS point
            if index not in index_used:
                print query_name + " - " + name
                Pt = point(name, lon_new, lat_new, ele, node_id, index,
                           new_gpx_index, query_name)
                Pts.append(Pt)
                index_used.append(index)
            else:
                print '/!\ Node index already used: ' + query_name + " - " + name + " - " + ele
    return Pts
Esempio n. 22
0
    def readMap(self, src):

        api = osmapi.OsmApi()
        file = open(src, "r")

        self.area = api.ParseOsm(file.read())

        self.dict = {}

        self.green = ogr.Geometry(ogr.wkbMultiPolygon)
        self.roads = ogr.Geometry(ogr.wkbMultiLineString)

        for item in self.area:
            self.dict[item.get("data").get("id")] = item.get("data")

        file.close()
Esempio n. 23
0
def main():
    api = osmapi.OsmApi(api=OSM_URL, passwordfile="credentials.txt")
    api.ChangesetCreate({u"comment": u"Test of automated edit"})
    tags = {"name": "Test node", "natural": "peak"}
    print(api.NodeCreate({u"lon": LONG_MIN, u"lat": LAT_MIN, u"tag": tags}))
    nodes = []
    first = None
    for lat, lon in OUTER_COORDS:
        nodes.append(api.NodeCreate({"lon": lon, "lat": lat})["id"])
        if first is None:
            first = nodes[-1]
    nodes.append(first)
    tags = {"name": "Test way", "building": "yes"}
    api.WayCreate({"nd": nodes, "tag": tags})

    api.ChangesetClose()
Esempio n. 24
0
def main():
    overpass_api = overpass.API()
    overpass_api.Debug = True

    username = input("Username: "******"Password: "******" " + VERSION,
                            debug=True)

    with open('locs.json', 'r') as fp:
        scraped = json.load(fp)

    checker = Checker(overpass_api, osm_api, load_banks(overpass_api), scraped)
    checker.run()
Esempio n. 25
0
def get_bounding_box_data(*lat_lon):
    """
    Only works for latin america <3

    TODO: improve logic
    """
    lats = [l[0] for l in lat_lon]
    lons = [l[1] for l in lat_lon]

    min_lon = min(lons)
    min_lat = min(lats)
    max_lon = max(lons)
    max_lat = max(lats)

    api = osmapi.OsmApi()
    return api.Map(min_lon, min_lat, max_lon, max_lat)
Esempio n. 26
0
def main():
    with open('nab.json', 'r') as fp:
        nab_locations = json.load(fp)

    atms = []
    banks = []
    for location in nab_locations:
        if location['tags']['amenity'] == 'atm':
            atms.append(location)
        else:
            banks.append(location)

    allowed_names = ['Neue Aargauer Bank', 'Neue Aargauer Bank AG', 'NAB']

    atm_checker = ATMChecker(atms,
                             allowed_names=allowed_names,
                             overpass_api=overpass.API())

    username = input("username: "******"password: "******" " + VERSION)

    changer = Changer(osm_api, dry_run=True, source=NAB_ATM_SOURCE)
    changer.begin("Add information to the ATM of Neue Aargauer Bank")

    for obj, match in atm_checker.find_all_objects():
        if match:
            changer.set_some_tags(match,
                                  obj['tags'],
                                  allowed_tags=['operator'])
            print("=" * 80)
            print(obj)
            print("=" * 80)
            print(match)
            print("=" * 80)
        else:
            open_browser(**obj['coordinates'])
    for action in changer.get_planned_actions():
        tags = action.previous_tags
        next_tags = action.obj['tag']
        helper.print_different_tags(tags, next_tags)
        input("Enter... :)")
    changer.commit()
Esempio n. 27
0
    def downloadMap(self, minX, minY, maxX, maxY):
        api = osmapi.OsmApi()
        #file = open(name, "r")

        minUTM = utm.to_latlon(minX, minY, 30, 'U')

        maxUTM = utm.to_latlon(maxX, maxY, 30, 'U')

        self.area = api.Map(minUTM[1], minUTM[0], maxUTM[1], maxUTM[0])

        self.dict = {}

        self.green = ogr.Geometry(ogr.wkbMultiPolygon)
        self.buildings = ogr.Geometry(ogr.wkbMultiPolygon)
        self.roads = ogr.Geometry(ogr.wkbMultiLineString)

        for item in self.area:
            self.dict[item.get("data").get("id")] = item.get("data")
def get_coords_for_relation(rid, start_node, end_node):
    osm = osmapi.OsmApi()
    relation_details = osm.RelationGet(rid)
    wl = get_way_list(relation_details)
    print("Relation %d mapped to %d ways" % (rid, len(wl)))
    coords_list = []
    on_list = []
    prev_last_node = -1
    for wid in wl:
        w_on_list, w_coords_list = get_coords_for_way(wid, prev_last_node)
        on_list.extend(w_on_list)
        coords_list.extend(w_coords_list)
        prev_last_node = w_on_list[-1]
        print("After adding %d entries from wid %d, curr count = %d" % (len(w_on_list), wid, len(coords_list)))
    start_index = on_list.index(start_node)
    end_index = on_list.index(end_node)
    assert start_index <= end_index, "Start index %d is before end %d" % (start_index, end_index)
    return coords_list[start_index:end_index+1]
Esempio n. 29
0
def application(environ, start_response):
    status = '200 OK'
    try:
        request_body_size = int(environ.get('CONTENT_LENGTH', 0))
    except (ValueError):
        request_body_size = 0
    request_body = environ['wsgi.input'].read(request_body_size)

    d = json.loads(request_body)
    ways_string = parse_qs(d["ways"])
    ways = ways_string.get('way', [])
    if len(ways) == 0:
        status = '400 Bad request'
        response_body = 'no ways indicated'

    elif d["username"] == None or d["password"] == None or d["comment"] == None:
        status = '400 Bad request'
        response_body = 'no username, password, or comment indicated'

    else:
        try:
            api = osmapi.OsmApi(username=d["username"],
                                password=d["password"],
                                created_by="peundemerg.ro-0.1")
            api.ChangesetCreate({u"comment": d["comment"]})

            for way in ways:
                x = api.WayGet(way)
                x['tag'][u'smoothness'] = d["smoothness"]
                x['tag'][u'surface_survey'] = d["surface_survey"]
                x['tag'][u'surface'] = d["surface"]
                api.WayUpdate(x)

            response_body = str(api.ChangesetClose())

        except Exception as inst:
            traceback.print_exc()
            status = '400 Bad request'
            response_body = str(inst)

    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(response_body)))]
    start_response(status, response_headers)
    return [response_body]
Esempio n. 30
0
    def test_NodeCreate_changesetauto(self):
        # setup mock
        self.api = osmapi.OsmApi(api="api06.dev.openstreetmap.org",
                                 changesetauto=True)
        for filename in [
                'test_NodeCreate_changesetauto.xml',
                'test_ChangesetUpload_create_node.xml',
                'test_ChangesetClose.xml'
        ]:
            self._session_mock(auth=True, filenames=[filename])

            test_node = {
                'lat': 47.123,
                'lon': 8.555,
                'tag': {
                    'amenity': 'place_of_worship',
                    'religion': 'pastafarian'
                }
            }

            self.assertIsNone(self.api.NodeCreate(test_node))