Example #1
0
 def test_parsing_from_overpass(self):
     """
     Test city border convertation to MultiPolygon
     """
     xml = overpass_call('rel(448930); out geom;')
     data = xml2geojson(xml)
     self.assertEqual(len(data['features']), 1)
Example #2
0
def get_osm_way(way_id: str) -> Dict:
    """ Returns the xml payload from the osm api"""
    way_url = get_osm_way_url(way_id)

    way_resp = http.get(way_url)

    if not way_resp.ok:
        logger.error("No way")
        raise Exception("Could not get way: {}".format(way_resp.status_code))

    way_resp_content = way_resp.text

    geojson_response = osm2geojson.xml2geojson(way_resp_content,
                                               filter_used_refs=False,
                                               log_level="INFO")

    if not isinstance(geojson_response, dict):
        raise Exception("Did not get a valid server response from OSM API")

    if "type" not in geojson_response:
        raise Exception("Did not get a valid server response from OSM API")

    if geojson_response["type"] != "FeatureCollection":
        raise Exception("Did not get a valid FeatureCollection from OSM API")

    if "features" not in geojson_response:
        raise Exception("GeoJSON has no features")

    return geojson_response
Example #3
0
def convert(osmFile):
    with open(osmFile) as data:
        xml = data.read()

    geojson = osm2geojson.xml2geojson(xml)

    writeFile = os.path.splitext(osmFile)[0] + '.geojson'
    with open(writeFile, 'w') as write:
        json.dump(geojson, write, indent=4, sort_keys=True)
Example #4
0
 def test_files_convertation(self):
     """
     Test how xml2geojson converts saved files
     """
     for name in ['empty', 'node', 'way', 'relation', 'map']:
         xml_data = read_data_file(name + '.osm')
         geojson_data = read_data_file(name + '.geojson')
         data = xml2geojson(xml_data)
         saved_geojson = json.loads(geojson_data)
         self.assertDictEqual(saved_geojson, data)
Example #5
0
def process_request(payload):
    coords = payload['coords']
    main_object = payload['mainObject']
    relative_object = payload['relativeObject']

    poly_coords = None

    query = ""

    request_begin = time.time()

    # search considering time reach distance
    if main_object['timeReachOn']:
        time_distance = main_object['maxDistance'] * 60
        poly_coords = get_opr_isochrone_poly_coords(coords, time_distance, main_object['transportMean'])

    # search considering also relative object
    if relative_object['applicable']:
        query = get_ovp_main_relative_object_search_query(main_object, relative_object, coords, poly_coords)

    # search only by main object
    else:
        query = get_ovp_main_object_search_query(main_object, coords, poly_coords)

    query += "(._;>;);out body;"
    # logger.info(query)

    try:
        data = o2g.xml2geojson(o2g.overpass_call(query), filter_used_refs=True, log_level='INFO')

        objects_number = len(data['features'])

        data = process_overpass_data(data)

        response_time = round(time.time() - request_begin, 2)
        logger.info('request time: ' + str(response_time) + 's; elements number: ' + str(objects_number))

        return {
            'geojson': data,
            'polygon': poly_coords,
            'time': response_time,
            'objectsNumber': objects_number
        }
    except Exception as e:
        msg = 'Error processing request. Try again. Error: ' + str(e)
        logger.error(msg)

    return { 'error': msg }
Example #6
0
def regions_data_view(request, osm_id):
    cache_key = Region.CACHE_KEY_PATTERN.format(osm_id)

    content = cache.get(cache_key, None)

    if content is None:
        region = None
        try:
            region = Region.objects.get(osm_id=osm_id)
        except Region.MultipleObjectsReturned:
            regions = Region.objects.filter(osm_id=osm_id)
            regions.delete()
        except Region.DoesNotExist:
            pass
        else:
            content = region.content
            cache.set(cache_key, region.content)

        if region is None:
            url = '{}{}/{}'.format(REGIONS_DATA_URL, osm_id, "full")
            r = requests.get(url, headers={'User-Agent': "curl/7.38.0"})
            if r.status_code != requests.codes.ok:
                return HttpResponse('Server responded with error',
                                    status=r.status_code)
            else:
                _content = osm2geojson.xml2geojson(r.content,
                                                   filter_used_refs=False,
                                                   log_level='INFO')
                content = {"type": _content['type'], "features": []}
                for el in _content['features']:
                    if 'geometry' in el:
                        try:
                            if (el['geometry']['type'] == 'Polygon' or el['geometry']['type'] == 'MultiPolygon') \
                                    and el['properties']['id'] == int(osm_id):
                                el['geometry']['coordinates'] = el['geometry'][
                                    'coordinates'][0]
                                content['features'].append(el)
                        except KeyError:
                            pass
                content = json.dumps(content)

                region = Region(osm_id=osm_id, content=content)
                region.save()
                cache.set(cache_key, region.content)
    return HttpResponse(content, content_type='application/json')
Example #7
0
def get_osm_and_geojson_data(name):
    xml_data = read_data_file(name + '.osm')
    geojson_data = read_data_file(name + '.geojson')
    data = xml2geojson(xml_data)
    saved_geojson = json.loads(geojson_data)
    return (data, saved_geojson)