Esempio n. 1
0
 def test_encoding(self):
   for td in self.testdata:
     codelength = len(td['code']) - 1
     if '0' in td['code']:
       codelength = td['code'].index('0')
     self.assertEqual(td['code'],
                      olc.encode(td['lat'], td['lng'], codelength), td)
def get_objects_nearby(req):
    table = boto3.resource('dynamodb').Table('OpenCity')
    lat, lon = float(req['lat']), float(req['lon'])
    res = []
    for length in [12, 11, 10, 8]:
        pc = encode(lat, lon, length)
        grid = "OSM:" + pc
        items = table.query(
            KeyConditionExpression=Key('grid').eq(grid),
            ProjectionExpression='lat, lon, tags,ubid'
        )
        nearby = []
        for item in items['Items']:
            if 'tags' in item and 'lat' in item and 'lon' in item:
                tags = item['tags']
                if 'name' in tags or 'amenity' in tags:
                    dist = distance(lat, lon, item['lat'], item['lon'])
                    tags['distance'] = dist
                    tags['lat'] = float(item['lat'])
                    tags['lon'] = float(item['lon'])
                    tags['ubid'] = item['ubid']
                    nearby.append(tags)
        if len(res) > 0:
            break
    nearby = sorted(nearby, key=lambda x: x['distance'])

    return response(200, json.dumps(nearby))
Esempio n. 3
0
    def test_benchmark(self):
        start_micros = round(time.time() * 1e6)
        for td in self.testdata:
            olc.encode(td[0], td[1], td[2])
        duration_micros = round(time.time() * 1e6) - start_micros
        print('Encoding benchmark: %d passes, %d usec total, %.03f usec each' %
              (len(self.testdata), duration_micros,
               duration_micros / len(self.testdata)))

        start_micros = round(time.time() * 1e6)
        for td in self.testdata:
            olc.decode(td[3])
        duration_micros = round(time.time() * 1e6) - start_micros
        print('Decoding benchmark: %d passes, %d usec total, %.03f usec each' %
              (len(self.testdata), duration_micros,
               duration_micros / len(self.testdata)))
 def test_encoding(self):
   for td in self.testdata:
     codelength = len(td['code']) - 1
     if '0' in td['code']:
       codelength = td['code'].index('0')
     self.assertEqual(td['code'],
                      olc.encode(td['lat'], td['lng'], codelength), td)
Esempio n. 5
0
 def setUp(self):
     self.testdata = []
     for i in range(0, 100000):
         dec = random.randint(0, 15)
         lat = round(random.uniform(1, 180) - 90, dec)
         lng = round(random.uniform(1, 360) - 180, dec)
         length = random.randint(2, 15)
         if length % 2 == 1:
             length = length + 1
         self.testdata.append(
             [lat, lng, length,
              olc.encode(lat, lng, length)])
Esempio n. 6
0
def address_details():
    try:
        ret = {}

        res_address = request.args.get("address")
        found_address = MongoAddress.objects(st_city="EL CAMPO", ad_name_full=res_address).first()
        if found_address:
            for location in found_address.locations:
                if "E911" == location.source:
                    list_coords = location.coords["coordinates"]
                    ret = dict()
                    ret["E911"] = [{"EPSG": "2278"}, {"X": list_coords[0][0]},
                                   {"Y": list_coords[0][1]},
                                   {"PLUS CODE": openlocationcode.encode(
                                       list_coords[1][1], list_coords[1][0])}], \
                                  [{"EPSG": "4326"},
                                   {"X": list_coords[1][0]},
                                   {"Y": list_coords[1][1]},
                                   {"PLUS CODE": openlocationcode.encode(
                                       list_coords[1][1], list_coords[1][0])}]

        return jsonify(ret)
    except Exception as e:
        return (str(e))
Esempio n. 7
0
def lambda_handler(event, context):
    table = dynamodb.Table('OpenCity')
    with table.batch_writer() as batch:
        items = dict()
        for record in event['Records']:
            payload = base64.b64decode(record['kinesis']['data'])
            #print(payload)
            obj = json.loads(payload.decode("utf-8"))
            obj['ubid'] = str(obj['hash'])
            for field in ['nds', 'members', 'tags']:
                if field in obj:
                    obj[field] = json.loads(obj[field])
                    if len(obj[field]) == 0:
                        del obj[field]
            for length in [8, 10, 11, 12]:
                grid = encode(obj['lat'], obj['lon'], length)
                obj['grid'] = "OSM:" + grid
                ca = decode(grid)
                lat, lon = ca.latitudeCenter, ca.longitudeCenter
                obj['distance'] = distance(lat, lon, obj['lat'], obj['lon'])
                o = json.loads(json.dumps(obj))
                for field in ['distance', 'lon', 'lat']:
                    o[field] = Decimal(str(o[field]))
                items[o['grid'] + o['hash']] = o
        for item in items.values():
            for k in list(item.keys()):
                if item[k] == '':
                    del item[k]
            try:
                batch.put_item(Item=item)
            except Exception as e:
                print("Unable to process item '%s'" % item)
                raise e
    print("Processed %d, %d distinct items" %
          (len(event['Records']), len(items)))
    # print("Decoded payload: " + obj)

    return {'statusCode': 200, 'body': json.dumps('Hello from Lambda!')}
Esempio n. 8
0
 def test_maxdigits_encoding(self):
   for codelength in [15, 16, 17, 100000]:
     code = olc.encode(37.539669125, -122.375069125, codelength)
     self.assertEqual(code, "849VGJQF+VX7QR4M")
Esempio n. 9
0
    arcpy.AddField_management(to_fc, "cad_url", "TEXT", "", "", "100",
                              "CAD URL", "NULLABLE", "NON_REQUIRED")
    fields = ["prop_id", "plus_code", "cad_url", "SHAPE@XY"]

    with arcpy.UpdateCursor(to_fc, fields) as cursor:
        for row in cursor:
            if row[0] is None:
                continue

            prop_id = int(row[0])
            cad_url = f"http://search.wharton.manatron.com/details.php?DB_account=R0{str(prop_id)}&account=R0{str(prop_id)}"
            row[2] = cad_url

            # check for valid x,y tuple
            if row[3] is None or row[3][0] is None or row[3][1] is None:
                continue

            x, y = row[3]
            # convert from State Plane to lat/lng
            x, y = transform(proj_2278, proj_4326, x, y)
            plus_code = openlocationcode.encode(y, x)
            row[1] = plus_code
            cursor.updateRow(row)

    arcpy.RegisterAsVersioned_management(ds, "EDITS_TO_BASE")
    ec_arcpy_util.dbCompress(arcpy.env.workspace)
    logging.info("Successful completion")

except Exception as e:
    logging.error(f"{inspect.stack()[0][3]} {e}")
Esempio n. 10
0
            list_area.append(round(d['building_area']/d['pisos']*cantidad_pisos))
        else:
            list_pisos.append(d['pisos'])
            list_area.append(d['building_area'])
        lat = geocode_result[0]['geometry']['location']['lat']
        lng = geocode_result[0]['geometry']['location']['lng']
        lat = round(lat,7)
        lng = round(lng,7)
        # Construimos geometría
        lado = round(math.sqrt(round(d["building_area"]/d["pisos"])))
        l.append([lat,round(lng+(lado/2/111319),7)])
        l.append([lat,round(lng-(lado/2/111319),7)])
        l.append([round(lat+(lado/111319),7),l[0][1]])
        l.append([round(lat-(lado/111319),7),l[1][1]])
        # Obtenemos UBID de edificios
        ubid = openlocationcode.encode(lat,lng)
        list_address.append(x)
        list_lat.append(lat)
        list_lng.append(lng)
        list_ubid.append(ubid)
    else:
        df_first = df_first.drop([i],axis=0)
        dir_not_found.append(x)
        cont=cont+1
        df_first = df_first.reset_index(drop=True)

if cont>0:
    print("No se encontro latitud y longitud de "+str(cont)+" edificios, estos fueron eliminados")

print("Se agrega altura a cada edificio")
print("Se agrega UBID y latitud y longitud")