Beispiel #1
0
def create_vtpk(aprx, outputPath, vtpkname, schema):
    import arcpy
    try:
        start_timeStampName = time.strftime('%Y_%m_%d %H:%M:%S',
                                            time.localtime(time.time()))
        start = time.time()
        s = start
        print("Create Vector Tile Package local,Start time:" +
              start_timeStampName)
        arcpy.env.overwriteOutput = True

        p = arcpy.mp.ArcGISProject(aprx)
        m = p.listMaps()[0]

        print("Packaging " + m.name)

        vptkPath = os.path.join(outputPath, vtpkname + '.vtpk')

        arcpy.CreateVectorTilePackage_management(m, vptkPath, "EXISTING",
                                                 schema, "INDEXED",
                                                 295828763.795777, 564.248588)

        print("VTPK path:", vptkPath)
        end_timeStampName = time.strftime('%Y_%m_%d %H:%M:%S',
                                          time.localtime(time.time()))
        end = time.time()
        elapse_time = end - start
        print(
            "Create Vector Tile Package finished, at time:" +
            end_timeStampName, "Elapsed time:", elapse_time, "s")
    except:
        print("Create Vector Tile Package failed.")
        print()
        arcpy.GetMessages()
def execute(in_map, AOI, origin_vtpk_path, out_part_vtpk):
    arcpy.env.workspace = os.path.dirname(out_part_vtpk)
    # analyzing original_vtpk to get the scheme and index polygon feature class
    aux_paras = analysis_original_vtpk(origin_vtpk_path)
    index_polygon = aux_paras[0]
    tile_scheme = aux_paras[1]
    service_type = aux_paras[2]
    temp_workspace = aux_paras[3]
    arcpy.AddMessage("Analyzing origin vtpk succesfully! " + "\n - " +
                     index_polygon + "\n - " + tile_scheme + "\n - " +
                     service_type)
    # Calculating affected bundle indexes
    bundle_index_polygons = calculate_affected_indexes_layer(
        AOI, index_polygon)
    arcpy.AddMessage("# Affected exactly index polygons created!  ")
    arcpy.AddMessage("# Starting creating partial vector tiles ...  ")
    arcpy.CreateVectorTilePackage_management(
        in_map=in_map,
        output_file=out_part_vtpk,
        service_type=service_type,
        tiling_scheme=tile_scheme,
        tile_structure="INDEXED",
        index_polygons=bundle_index_polygons)
    arcpy.AddMessage("# Partial vector tiles created!  ")
    if os.path.exists(out_part_vtpk):
        shutil.rmtree(temp_workspace)
Beispiel #3
0
def create_partial_vtpk(workspace, index_polygon, AOI, in_map, LOD, out_part_vtpk, service_type, tile_scheme):
    arcpy.AddMessage(service_type)
    arcpy.env.workspace = workspace
    arcpy.AddMessage("Current workspace: {0}".format(arcpy.env.workspace))
    AOI_lyr = arcpy.MakeFeatureLayer_management(AOI, "AOI_temp_lyr")
    IndexPolygon_lyr = arcpy.MakeFeatureLayer_management(index_polygon, "IndexPolygon_lyr")
    arcpy.SelectLayerByLocation_management(IndexPolygon_lyr, 'intersect', AOI_lyr)
    # arcpy.AddMessage("Start LOD level: {0}".format(LOD))
    arcpy.SelectLayerByAttribute_management(IndexPolygon_lyr, 'SUBSET_SELECTION', str(' "LOD" > ' + str(LOD)))
    arcpy.CopyFeatures_management(IndexPolygon_lyr, 'NewIndex.shp')
    arcpy.AddMessage('New index layer has been generated.')
    IndexPolygon_lyr.visible = False
    AOI_lyr.visible = False
    try:
        arcpy.CreateVectorTilePackage_management(in_map=in_map,
                                                 output_file=out_part_vtpk,
                                                 service_type=service_type,
                                                 tiling_scheme=tile_scheme,
                                                 tile_structure="INDEXED",
                                                 index_polygons='NewIndex.shp')
    except Exception as err:
        arcpy.AddError(err)
        print(err)
    # arcpy.Delete_management('NewIndex.shp')
    return True
Beispiel #4
0
def create_partial_vtpk(workspace, IndexPolygonPart, in_map, out_part_vtpk, service_type, tile_scheme):
    arcpy.AddMessage("Service Type: " + service_type)
    try:
        arcpy.CreateVectorTilePackage_management(in_map=in_map,
                                                 output_file=out_part_vtpk,
                                                 service_type=service_type,
                                                 tiling_scheme=tile_scheme,
                                                 tile_structure="INDEXED",
                                                 index_polygons=IndexPolygonPart)
    except Exception as err:
        arcpy.AddError(err)
        print(err)
    # arcpy.Delete_management(IndexPolygonPart)
    return True
def execute(in_map, AOI, origin_vtpk, is_adv_vtpk, index_polygon,
            out_part_vtpk):

    arcpy.env.workspace = os.path.dirname(out_part_vtpk)
    temp_workspace = None

    # Update 2018-9-20, add support for user defined xml file
    if is_adv_vtpk:
        # analyzing original_vtpk to get the scheme and index polygon feature class
        adv_aux_paras = analysis_original_vtpk(origin_vtpk)
        index_polygon = adv_aux_paras[0]
        tile_scheme = adv_aux_paras[1]
        service_type = adv_aux_paras[2]
        temp_workspace = adv_aux_paras[3]
        arcpy.AddMessage("- Analyzing origin vtpk succesfully! " + "\n - " +
                         index_polygon + "\n - " + tile_scheme + "\n - " +
                         service_type)
    else:
        common_aux_paras = get_tile_scheme_and_index(in_map)
        tile_scheme = common_aux_paras[0]
        service_type = common_aux_paras[1]
        arcpy.AddMessage("- Servcie Type: " + service_type)

    # Calculating affected bundle indexes
    bundle_index_polygons = calculate_affected_indexes_layer(
        AOI, index_polygon)
    arcpy.AddMessage("# Affected exactly index polygons created!  ")
    arcpy.AddMessage("# Starting creating partial vector tiles ...  ")
    arcpy.CreateVectorTilePackage_management(
        in_map=in_map,
        output_file=out_part_vtpk,
        service_type=service_type,
        tiling_scheme=tile_scheme,
        tile_structure="INDEXED",
        index_polygons=bundle_index_polygons)
    arcpy.AddMessage("# Partial vector tiles created!  ")

    # Remove temporary intermediate data
    if os.path.exists(out_part_vtpk) and arcpy.Exists(out_part_vtpk):
        arcpy.Delete_management(
            os.path.join(arcpy.env.workspace, bundle_index_polygons))
        arcpy.AddMessage("Temp Data deleted - " + bundle_index_polygons)
    if os.path.exists(out_part_vtpk) and temp_workspace is not None:
        shutil.rmtree(temp_workspace)
        arcpy.AddMessage("Temp Data deleted - " + temp_workspace)
Beispiel #6
0
#Create variable for Vector tile index
tileIndex = r"C:\Users\jaburton\Documents\ArcGIS\Projects\VectorBasemap\VectorBasemap.gdb\VectorTileIndex1"

#Create vector tile package locally
p = arcpy.mp.ArcGISProject(
    r'C:\Users\jaburton\Documents\ArcGIS\Projects\VectorBasemap\VectorBasemap.aprx'
)
outputPath = r'C:\Users\jaburton\Documents\ArcGIS\Projects\VectorBasemap'
#log start time
logging.debug("Process began" + ' ' + day + ' ' + 'at' + ' ' + beginTime +
              "\n")
#logOutput.write("Process began" + ' ' + day + ' ' + 'at' + ' ' + beginTime + "\n")
for m in p.listMaps("VectorTile"):
    print("Packaging " + m.name)
    arcpy.CreateVectorTilePackage_management(m, outputPath + m.name + '.vtpk',
                                             "ONLINE", "", "INDEXED",
                                             295828763.795777, 564.248588)
    print("Vector Tile Created")


#returns ssl value and user token
def getToken(adminUser, pw):
    data = {
        'username': adminUser,
        'password': pw,
        'referer': 'https://www.arcgis.com',
        'f': 'json'
    }
    url = 'https://www.arcgis.com/sharing/rest/generateToken'
    jres = requests.post(url, data=data, verify=False).json()
    return jres['token'], jres['ssl']
Beispiel #7
0
def add_vector_tile_layers(vector_layers):
    """ Accepts the dictionary of vector layers, adds them to a map,
    creates the vector tile package locally, deletes the exisiting layer
    in AGOL if it exists, uploads the tile package to AGOL and then
    publishes the tile package to a hosted tile layer
    """

    aprx = arcpy.mp.ArcGISProject(APRX_PATH)
    m = aprx.listMaps(MAP)[0]
    gis = arcgis.GIS(AGOL, USERNAME, PASSWORD)

    remove_all_layers(m)
    # Get the group object for the mobile suma AGOL group
    mobile_suma_group = gis.groups.get(GROUP_ID)
    LOGGER.debug(f'Group name: {mobile_suma_group.title} found')
    for k, v in vector_layers.items():
        # First add a dummy layer to the map so that it sets the spatial
        # reference of the map to Web Mercator. This is nessecary to
        # publish to the AGOL/Google maps tiling scheme.
        LOGGER.info(f'creating spatial reference layer for {k} group')
        arcpy.MakeFeatureLayer_management(SPATIAL_REFERENCE_LAYER,
                                          'spatial_reference_layer')
        m.addDataFromPath(SPATIAL_REFERENCE_LAYER)
        LOGGER.info(f'added spatial reference layer for {k}')
        for i in v:
            layer = arcpy.mp.LayerFile(os.path.join(QDL_PATH, i + ".lyr"))
            LOGGER.info(f'adding layer: {layer} to map')
            m.addLayer(layer)
        # Make sure all the layers are on
        turn_on_layers_in_map(m)
        # Create the vector tile package locally
        LOGGER.info('Creating Vector tile package locally')
        arcpy.CreateVectorTilePackage_management(
            m,
            f'mobile_suma_gis/vector_tile_packages/{k}.vtpk',
            'ONLINE',
        )
        LOGGER.info(f'finished creating vtpk')
        # Delete the old package and tile layer. The name of the old layer and
        # new layer must match or they will break links from web maps.
        # AGOL does not currently support overwriting tile
        # packages, only feature services
        LOGGER.info('Checkinig if content already exists on AGOL and'
                    'deleting if it does.')

        agol_items = gis.content.search(
            f'owner:{OWNER} AND title:{k} AND group:{GROUP_ID}')
        if len(agol_items) > 0:
            for agol_item in agol_items:
                LOGGER.info(f'Deleting {agol_item}')
                agol_item.delete()
        else:
            LOGGER.info('No items to delete from agol.')
        # Publish to AGOL.
        LOGGER.info('Adding vtpk to AGOL')
        vtpk = gis.content.add(
            {
                'description': (f'VTPK for the {k} group'
                                'layer this layer is updated weekly.')
            },
            f'mobile_suma_gis/vector_tile_packages/{k}.vtpk',
            folder='vector_tiles')
        # When using the share method you must use the gis group object.
        # Using the group id or name does not work, despite what the
        # documentation says.
        vtpk.share(org=True, groups=[mobile_suma_group])
        LOGGER.info('Publishing hosted tile layer')
        publish = vtpk.publish()
        publish.share(org=True, groups=[mobile_suma_group])

        # Remove the layers. All active layers in the map
        # will be included in the vtpk
        LOGGER.info('Removing layers from map.')
        remove_all_layers(m)
for subdir, dirs, files in os.walk(vtpath):
    for file in files:
        if file.endswith('.zip'):
            os.remove(subdir + file)

for subdir, dirs, files in os.walk(path):
    for file in files:
        if file.endswith('.aprx'):
            proj = os.path.join(subdir, file)
            p = arcpy.mp.ArcGISProject(proj)
            for m in p.listMaps():
                print("Packaging " + m.name)
                tpk = vtpath + m.name + '.vtpk'
                arcpy.CreateVectorTilePackage_management(
                    m, tpk, "ONLINE", "", "INDEXED", 147914381.897889,
                    141.062147)
                base = os.path.splitext(tpk)[0]
                zip = os.rename(tpk, base + ".zip")

for subdir, dirs, files in os.walk(vtpath):
    for file in files:
        vtname = os.path.splitext(file)[0]
        out = pathlib.Path(serverpath + vtname + '\\VectorTileServer\\tile\\')
        vtzip = os.path.join(subdir, file)
        with zipfile.ZipFile(vtzip, 'r') as zip:
            for file in zip.namelist():
                if file.startswith(prefix):
                    destpath = out.joinpath(file[len(prefix):])
                    # make sure destination directory exists otherwise `open` will fail
                    os.makedirs(destpath.parent, exist_ok=True)