Ejemplo n.º 1
0
    def sync(self):
        LIMIT = 0  # 每一種同步動作的次數限制,除錯用

        # 注意!! 實驗階段指向測試伺服器
        #host = 'api06.dev.openstreetmap.org'
        host = 'api.openstreetmap.org'
        user = '******'
        pwf = '%s/.osmpass' % os.environ['HOME']

        # 注意!! 有中文的地方需要使用 unicode 字串型態
        chset = {
            u'comment': u'自動同步 (%s)' % self.source_name,
            u'created_by': u'小璋流同步機器人 (osmapi/0.6.0)',
            u'bot': u'yes'
        }

        api = OsmApi(api=host, username=user, passwordfile=pwf)
        api.ChangesetCreate(chset)

        # 新增/修改/刪除
        actions = ['create', 'update', 'delete']
        points_map = {
            'create': self.points_new,
            'update': self.points_changed,
            'delete': self.points_disappeared
        }
        for act in actions:
            points = points_map[act]
            count = 0
            failed = 0
            total = len(points)
            for p in points:
                node = self.toNode(p, api)
                if node is not None:
                    try:
                        if act == 'create': api.NodeCreate(node)
                        if act == 'update': api.NodeUpdate(node)
                        if act == 'delete': api.NodeDelete(node)
                    except:
                        # TODO: 加入 logger 機制
                        failed = failed + 1
                else:
                    # TODO: 加入 logger 機制
                    failed = failed + 1

                # 計數/次數限制/摘要顯示
                count = count + 1
                print('\r%s: %d/%d (失敗: %d)' % (act, count, total, failed)),
                sys.stdout.flush()
                if count == LIMIT: break
            print('')

        return api.ChangesetClose()
Ejemplo n.º 2
0
    def osm_tenant(self, **kw):

        bus_ids = http.request.params['bus_ids']
        name = http.request.params['name']
        citizen = http.request.params['citizen']
        rent = http.request.params['rent']
        vrn = http.request.params['vrn']
        assess = http.request.params['assess']
        branch = http.request.params['branch']
        tax = http.request.params['tax']
        tin = http.request.params['tin']
        efd = http.request.params['efd']
        valued = http.request.params['valued']

        r = requests.get('http://www.openstreetmap.org/api/0.6/way/%s/full' %
                         (bus_ids))
        response = BeautifulSoup(r.text)
        nodes = response.osm.findAll("node")

        lat = 0
        lon = 0
        for x in nodes:
            lat = lat + float(x['lat'])
            lon = lon + float(x['lon'])
        lat = lat / len(nodes)
        lon = lon / len(nodes)

        MyApi = OsmApi(username=u"Wahab Ali Malik", password=u"Loveodoo")
        MyApi.ChangesetCreate(
            {u"comment": u"Adding One of the owner of building"})
        print MyApi.NodeCreate({
            u"lon": lon,
            u"lat": lat,
            u"tag": {
                u"tenant": u"%s" % (name),
                u"vrn": u"%s" % (vrn),
                u"assess": u"%s" % (assess),
                u"branch": u"%s" % (branch),
                u"tin": u"%s" % (tin),
                u"efd": u"%s" % (efd),
                u"citizen": u"%s" % (citizen),
                u"valued": u"%s" % (valued),
                u"rent": u"%s" % (rent),
                u"tax": u"%s" % (tax),
            }
        })
Ejemplo n.º 3
0
        print('Vols inserir (y/n)')
        tecla = press_key()
        print(tecla)
        if (tecla == 'y'):

            #primer les dades que segur que hi són:
            data = '{"lat":%f, "lon":%f, "tag": { "historic":"archaeological_site","site_type":"megalith", "name":"%s", "megalith_type":"%s"' % (
                lat, lon, name, megalith_type)
            if (wikipedia != ""):
                data += ',"wikipedia":"%s"' % (wikipedia)
            if (wikidata != ""):
                data += ',"wikidata":"%s"' % (wikidata)
            if (source != ""):
                data += ',"source":"%s"' % (source)
            if (alt_name != ""):
                data += ',"alt_name":"%s"' % (alt_name)
            data += '}}'
            print(data)
            #data = '{"lat":%f, "lon":%f, "tag": { "natural": "tree", "name": "%s", "species": "%s", "species:ca": "%s", "note": "%s", "website": "%s" }}' % (lat, lon, name, species, species_ca, note, website)
            data_json = json.loads(data)
            print(data_json)
            print(MyApi.NodeCreate(data_json))
            #MyApi.flush()
            print("dolmen inserit\n")
            num_item = num_item + 1
        else:
            print('No volem inserir\n')

# tanquem la sessió
MyApi.ChangesetClose()
Ejemplo n.º 4
0
from osmapi import OsmApi
import time

MyApi = OsmApi()

api = OsmApi(username="******", password="******")

import csv

with open('temple2.csv', newline='') as File:
    reader = csv.reader(File)
    for row in reader:
        print(row)
        api.ChangesetCreate({u"comment": u"Siva Temple " + row[1].title()})
        data = {
            u"lat": row[3],
            u"lon": row[4],
            u"tag": {
                u"amenity": u"temple",
                u"name": row[1].title(),
                u"location": row[2].title(),
                u"religion": u"hindu"
            }
        }
        api.NodeCreate(data)
        api.ChangesetClose()

        print(data)
        time.sleep(1)
Ejemplo n.º 5
0
                    if node.tagName == "node":
                        if not dryrun:
                            api.NodeUpdate(editnode)
                    else:
                        if not dryrun:
                            api.WayUpdate(editnode)
                elif action == "delete":
                    print("Deleting")
                    if node.tagName == "node":
                        if not dryrun:
                            api.NodeDelete(editnode)
                else:
                    if node.tagName == "node":
                        print("Creating")
                        if not dryrun:
                            api.NodeCreate(editnode)
                print(editnode)
        atleastone = True
    if atleastone and not dryrun:
        cursor.execute(
            "insert into update_requests (kommunenummer, ferdig, ip, upload, tid) values (\"%s\", 1, \"full_upload\", 1, now())"
            % (munipnumber, ))
        cursor.execute(
            "insert into update_requests (kommunenummer,ip,tid) values ('" +
            str(munipnumber) +
            "','full_upload_update_after',addtime(now(),\"0:20:00\"));")
        db.commit()

if not dryrun:
    api.ChangesetClose()
Ejemplo n.º 6
0
from config_importer import import_config

user = import_config("./config.txt", "osm_credentials", "user")
password = import_config("./config.txt", "osm_credentials", "password")
print(user, password)

#api = OsmApi(api="http://api06.dev.openstreetmap.org", username = "******", password = "******", changesetauto=True)
api = OsmApi(api="http://api06.dev.openstreetmap.org",
             username="******",
             password="******",
             changesetauto=True)
'''
#api = OsmApi(api="api06.dev.openstreetmap.org", username=user, passwordfile=password, changesetauto=True, changesetautotags={"comment":u"changeset auto"})

lat = 52.534395
lon = 13.358543

changeset ={u"comment": u"My first test"}
node = {u"lat":lat, u"lon":lon, u"tag":{}}

api.ChangesetCreate(changeset)

api.NodeCreate(node)
api.flush() # to send last updates
api.ChangesetClose()
'''

api.ChangesetCreate({u"comment": u"My first test"})
print(api.NodeCreate({u"lon": 1, u"lat": 1, u"tag": {"tollmap": "test1"}}))
# {u'changeset': 532907, u'lon': 1, u'version': 1, u'lat': 1, u'tag': {}, u'id': 164684}
api.ChangesetClose()
Ejemplo n.º 7
0
class TestOsmApiNode(osmapi_tests.TestOsmApi):
    def test_NodeGet(self):
        self._conn_mock()

        result = self.api.NodeGet(123)

        args, kwargs = self.api._conn.putrequest.call_args
        self.assertEquals(args[0], 'GET')
        self.assertEquals(args[1], '/api/0.6/node/123')

        self.assertEquals(
            result, {
                'id': 123,
                'changeset': 15293,
                'uid': 605,
                'timestamp': datetime.datetime(2012, 4, 18, 11, 14, 26),
                'lat': 51.8753146,
                'lon': -1.4857118,
                'visible': True,
                'version': 8,
                'user': '******',
                'tag': {
                    'amenity': 'school',
                    'foo': 'bar',
                    'name': 'Berolina & Schule'
                },
            })

    def test_NodeGet_with_version(self):
        self._conn_mock()

        result = self.api.NodeGet(123, NodeVersion=2)

        args, kwargs = self.api._conn.putrequest.call_args
        self.assertEquals(args[0], 'GET')
        self.assertEquals(args[1], '/api/0.6/node/123/2')

        self.assertEquals(
            result, {
                'id': 123,
                'changeset': 4152,
                'uid': 605,
                'timestamp': datetime.datetime(2011, 4, 18, 11, 14, 26),
                'lat': 51.8753146,
                'lon': -1.4857118,
                'visible': True,
                'version': 2,
                'user': '******',
                'tag': {
                    'amenity': 'school',
                },
            })

    def test_NodeCreate_changesetauto(self):
        # setup mock
        self.api = OsmApi(api="api06.dev.openstreetmap.org",
                          changesetauto=True)
        self._conn_mock(auth=True,
                        filenames=[
                            'test_NodeCreate_changesetauto.xml',
                            'test_ChangesetUpload_create_node.xml',
                            'test_ChangesetClose.xml',
                        ])

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

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

    def test_NodeCreate(self):
        self._conn_mock(auth=True)

        # setup mock
        self.api.ChangesetCreate = mock.Mock(return_value=1111)
        self.api._CurrentChangesetId = 1111

        test_node = {
            'lat': 47.287,
            'lon': 8.765,
            'tag': {
                'amenity': 'place_of_worship',
                'religion': 'pastafarian'
            }
        }

        cs = self.api.ChangesetCreate({'comment': 'This is a test dataset'})
        self.assertEquals(cs, 1111)
        result = self.api.NodeCreate(test_node)

        args, kwargs = self.api._conn.putrequest.call_args
        self.assertEquals(args[0], 'PUT')
        self.assertEquals(args[1], '/api/0.6/node/create')

        self.assertEquals(result['id'], 9876)
        self.assertEquals(result['lat'], test_node['lat'])
        self.assertEquals(result['lon'], test_node['lon'])
        self.assertEquals(result['tag'], test_node['tag'])

    def test_NodeCreate_wo_changeset(self):
        test_node = {
            'lat': 47.287,
            'lon': 8.765,
            'tag': {
                'amenity': 'place_of_worship',
                'religion': 'pastafarian'
            }
        }

        with self.assertRaisesRegexp(Exception, 'need to open a changeset'):
            self.api.NodeCreate(test_node)

    def test_NodeCreate_wo_auth(self):
        self._conn_mock()

        # setup mock
        self.api.ChangesetCreate = mock.Mock(return_value=1111)
        self.api._CurrentChangesetId = 1111
        test_node = {
            'lat': 47.287,
            'lon': 8.765,
            'tag': {
                'amenity': 'place_of_worship',
                'religion': 'pastafarian'
            }
        }

        with self.assertRaisesRegexp(UsernamePasswordMissingError,
                                     'Username/Password missing'):
            self.api.NodeCreate(test_node)

    def test_NodeUpdate(self):
        self._conn_mock(auth=True)

        # setup mock
        self.api.ChangesetCreate = mock.Mock(return_value=1111)
        self.api._CurrentChangesetId = 1111

        test_node = {
            'id': 7676,
            'lat': 47.287,
            'lon': 8.765,
            'tag': {
                'amenity': 'place_of_worship',
                'name': 'christian'
            }
        }

        cs = self.api.ChangesetCreate({'comment': 'This is a test dataset'})
        self.assertEquals(cs, 1111)
        result = self.api.NodeUpdate(test_node)

        args, kwargs = self.api._conn.putrequest.call_args
        self.assertEquals(args[0], 'PUT')
        self.assertEquals(args[1], '/api/0.6/node/7676')

        self.assertEquals(result['id'], 7676)
        self.assertEquals(result['version'], 3)
        self.assertEquals(result['lat'], test_node['lat'])
        self.assertEquals(result['lon'], test_node['lon'])
        self.assertEquals(result['tag'], test_node['tag'])

    def test_NodeDelete(self):
        self._conn_mock(auth=True)

        # setup mock
        self.api.ChangesetCreate = mock.Mock(return_value=1111)
        self.api._CurrentChangesetId = 1111

        test_node = {'id': 7676}

        cs = self.api.ChangesetCreate({'comment': 'This is a test dataset'})
        self.assertEquals(cs, 1111)

        result = self.api.NodeDelete(test_node)

        args, kwargs = self.api._conn.putrequest.call_args
        self.assertEquals(args[0], 'DELETE')
        self.assertEquals(args[1], '/api/0.6/node/7676')
        self.assertEquals(result['id'], 7676)
        self.assertEquals(result['version'], 4)

    def test_NodeHistory(self):
        self._conn_mock()

        result = self.api.NodeHistory(123)

        args, kwargs = self.api._conn.putrequest.call_args
        self.assertEquals(args[0], 'GET')
        self.assertEquals(args[1], '/api/0.6/node/123/history')

        self.assertEquals(len(result), 8)
        self.assertEquals(result[4]['id'], 123)
        self.assertEquals(result[4]['version'], 4)
        self.assertEquals(result[4]['lat'], 51.8753146)
        self.assertEquals(result[4]['lon'], -1.4857118)
        self.assertEquals(result[4]['tag'], {
            'empty': '',
            'foo': 'bar',
        })

    def test_NodeWays(self):
        self._conn_mock()

        result = self.api.NodeWays(234)

        args, kwargs = self.api._conn.putrequest.call_args
        self.assertEquals(args[0], 'GET')
        self.assertEquals(args[1], '/api/0.6/node/234/ways')

        self.assertEquals(len(result), 1)
        self.assertEquals(result[0]['id'], 60)
        self.assertEquals(result[0]['changeset'], 61)
        self.assertEquals(result[0]['tag'], {
            'highway': 'path',
            'name': 'Dog walking path',
        })

    def test_NodeRelations(self):
        self._conn_mock()

        result = self.api.NodeRelations(4295668179)

        args, kwargs = self.api._conn.putrequest.call_args
        self.assertEquals(args[0], 'GET')
        self.assertEquals(args[1], '/api/0.6/node/4295668179/relations')

        self.assertEquals(len(result), 1)
        self.assertEquals(result[0]['id'], 4294968148)
        self.assertEquals(result[0]['changeset'], 23123)
        self.assertEquals(result[0]['member'][1], {
            'role': 'point',
            'ref': 4295668179,
            'type': 'node',
        })
        self.assertEquals(result[0]['tag'], {
            'type': 'fancy',
        })

    def test_NodesGet(self):
        self._conn_mock()

        result = self.api.NodesGet([123, 345])

        args, kwargs = self.api._conn.putrequest.call_args
        self.assertEquals(args[0], 'GET')
        self.assertEquals(args[1], '/api/0.6/nodes?nodes=123,345')

        self.assertEquals(len(result), 2)
        self.assertEquals(
            result[123], {
                'id': 123,
                'changeset': 15293,
                'uid': 605,
                'timestamp': datetime.datetime(2012, 4, 18, 11, 14, 26),
                'lat': 51.8753146,
                'lon': -1.4857118,
                'visible': True,
                'version': 8,
                'user': '******',
                'tag': {
                    'amenity': 'school',
                    'foo': 'bar',
                    'name': 'Berolina & Schule'
                },
            })
        self.assertEquals(
            result[345], {
                'id': 345,
                'changeset': 244,
                'timestamp': datetime.datetime(2009, 9, 12, 3, 22, 59),
                'uid': 1,
                'visible': False,
                'version': 2,
                'user': '******',
                'tag': {},
            })
Ejemplo n.º 8
0
    def create_owner(self, **kw):

        #####################################################
        # Assign values to local variables
        #####################################################

        bus_ids = http.request.params['bus_ids']

        owner = http.request.params['name']
        citizen = http.request.params['citizen']
        vrn = http.request.params['vrn']
        assess = http.request.params['assess']
        branch = http.request.params['branch']
        tax = http.request.params['tax']
        tin = http.request.params['tin']
        efd = http.request.params['efd']
        valued = http.request.params['valued']
        tenants_id = http.request.params['tenants_id']

        #####################################################
        # Getting building boarder nodes
        #####################################################

        r = requests.get('http://www.openstreetmap.org/api/0.6/way/%s/full' %
                         (bus_ids))

        response = BeautifulSoup(r.text)

        nodes = response.osm.findAll("node")

        lat = 0
        lon = 0

        for x in nodes:
            lat = lat + float(x['lat'])
            lon = lon + float(x['lon'])
        lat = lat / len(nodes)
        lon = lon / len(nodes)

        #####################################################
        # Conneting to OSM through api
        #####################################################

        MyApi = OsmApi(username=USERNAME, password=PASSWORD)

        #####################################################
        # Info about changeset
        #####################################################

        MyApi.ChangesetCreate(
            {u"comment": u"Adding One of the Owner of building"})

        #####################################################
        # Create Node
        #####################################################

        MyApi.NodeCreate({
            u"lon": lon,
            u"lat": lat,
            u"tag": {
                u"owner": u"%s" % (owner),
                u"citizen": u"%s" % (citizen),
                u"vrn": u"%s" % (vrn),
                u"assess": u"%s" % (assess),
                u"branch": u"%s" % (branch),
                u"tax": u"%s" % (tax),
                u"tin": u"%s" % (tin),
                u"efd": u"%s" % (efd),
                u"valued": u"%s" % (valued),
                u"tenants_id": u"%s" % (tenants_id),
            }
        })
Ejemplo n.º 9
0
    def create_building_information(self, **kw):

        #####################################################
        # Assign values to local variables
        #####################################################

        bus_ids = http.request.params['bus_ids']

        property_name = http.request.params['property_name']
        ward = http.request.params['ward']
        sub_ward = http.request.params['sub_ward']
        street = http.request.params['street']
        plot_no = http.request.params['plot_no']
        post_code_no = http.request.params['post_code_no']
        user = http.request.params['user']
        tenure = http.request.params['tenure']
        owner = http.request.params['owner']
        address = http.request.params['address']
        walls = http.request.params['walls']
        roof = http.request.params['roof']
        ceiling = http.request.params['ceiling']
        floor = http.request.params['floor']
        windows = http.request.params['windows']
        doors = http.request.params['doors']
        state = http.request.params['state']
        services = http.request.params['services']
        discription = http.request.params['discription']
        room_counts = http.request.params['room_counts']
        fixture_and_fittng = http.request.params['fixture_and_fittng']
        brif_dis = http.request.params['brif_dis']
        main_building = http.request.params['main_building']
        out_building = http.request.params['out_building']
        site_work = http.request.params['site_work']
        condition = http.request.params['condition']
        depreciation = http.request.params['depreciation']

        #####################################################
        # Getting building boarder nodes
        #####################################################

        r = requests.get('http://www.openstreetmap.org/api/0.6/way/%s/full' %
                         (bus_ids))

        response = BeautifulSoup(r.text)

        nodes = response.osm.findAll("node")

        lat = 0
        lon = 0

        for x in nodes:
            lat = lat + float(x['lat'])
            lon = lon + float(x['lon'])
        lat = lat / len(nodes)
        lon = lon / len(nodes)

        #####################################################
        # Conneting to OSM through api
        #####################################################

        MyApi = OsmApi(username=USERNAME, password=PASSWORD)

        #####################################################
        # Info about changeset
        #####################################################

        MyApi.ChangesetCreate(
            {u"comment": u"Adding Building related Information"})

        #####################################################
        # Create Node
        #####################################################

        MyApi.NodeCreate({
            u"lon": lon,
            u"lat": lat,
            u"tag": {
                u"property_name": u"%s" % (property_name),
                u"ward": u"%s" % (ward),
                u"sub_ward": u"%s" % (sub_ward),
                u"street": u"%s" % (street),
                u"plot_no": u"%s" % (plot_no),
                u"post_code_no": u"%s" % (post_code_no),
                u"user": u"%s" % (user),
                u"tenure": u"%s" % (tenure),
                u"owner": u"%s" % (owner),
                u"address": u"%s" % (address),
                u"state": u"%s" % (state),
                u"discription": u"%s" % (discription),
                u"roof": u"%s" % (roof),
                u"ceiling": u"%s" % (ceiling),
                u"walls": u"%s" % (walls),
                u"windows": u"%s" % (windows),
                u"doors": u"%s" % (doors),
                u"floor": u"%s" % (floor),
                u"room_counts": u"%s" % (room_counts),
                u"fixture_and_fittng": u"%s" % (fixture_and_fittng),
                u"brif_dis": u"%s" % (brif_dis),
                u"main_building": u"%s" % (main_building),
                u"out_building": u"%s" % (out_building),
                u"site_work": u"%s" % (site_work),
                u"services": u"%s" % (services),
                u"condition": u"%s" % (condition),
                u"depreciation": u"%s" % (depreciation),
            }
        })
Ejemplo n.º 10
0
import csv

from osmapi import OsmApi

MyApi = OsmApi(username="******", password="******")
MyApi.ChangesetCreate({u"comment": u"TPER import"})

with open("CM.csv") as cm_file:
    for row in csv.reader(cm_file, delimiter=";"):
        to_push = {
            "lon": row[7].replace(",", "."),
            "lat": row[6].replace(",", "."),
            "tag": {
                "addr:city": row[3].title(),
                "highway": "bus_stop",
                "ref": row[0],
                "name": row[1].title(),
                "operator": "TPER",
                "source": "http://www.tper.it/azienda/tper-open-data"
            }
        }
        print to_push
        MyApi.NodeCreate(to_push)

MyApi.ChangesetClose()