Краткая информация
Конвертирует веб-карту (в формате [JSON), которую вы хотите напечатать или экспортировать, в ArcGISProject. Проект ArcGIS затем можно изменить перед печатью или экспортом.
Обсуждение
Функция ConvertWebMapToArcGISProject конвертирует веб-карту, которую вы хотите напечатать или экспортировать, в проект ArcGIS Pro. После преобразования веб-карты в проект переходят все элементы веб-карты. Затем можно изменить проект перед печатью или экспортом в стандартные форматы, такие как PDF. ConvertWebMapToArcGISProject обычно используется при печати карт из ГИС веб-приложений с помощью ArcGIS API for JavaScript или ArcGIS Web AppBuilder.
Более подробную информацию, сценарии и обсуждения см. в разделе Печать веб-карт с помощью arcpy.mp.
Синтаксис
ConvertWebMapToArcGISProject (webmap_json, {template_pagx}, {mapframe_name}, {notes_gdb})| Параметр | Описание | Тип данных |
webmap_json | Веб-карта для печати в формате JSON. См. ExportWebMap Спецификация JSON для получения более подробной информации. ArcGIS API for JavaScript и ArcGIS Web AppBuilder позволяют разработчикам получить эту строку JSON из веб-приложения. | String |
template_pagx | Строка, содержащая путь к расположению и имя файла компоновки (.pagx), использующегося в качестве шаблона компоновки страницы. Веб-карта будет конвертирована в новую карту в проекте ArcGIS. Фрейм карты 2D в компоновке будет ссылаться на вновь созданную карту. Более подробно см. параметр mapframe_name. Слои фрейма веб-карты из файла template_pagx (и всех других фреймов карт) будут сохранены в выходном ArcGISProject. Если не указан template_pagx используйте функцию Map объекта defaultView для доступа к MapView для веб-карт. В рабочем процессе печати веб-карты из MapView выходной файл не будет содержать никаких элементов компоновки (заголовок, легенду, масштабную линейку, обзорную карту и т.п.). (Значение по умолчанию — None) | String |
mapframe_name | Строка, представляющая имя фрейма карты в компоновке, будет обновлена для указания на вновь созданную карту, содержащую веб-карту JSON. Если в компоновке только один фрейм карты, он используется как основа веб-карты по умолчанию. Если в компоновке более одного фрейма карты, и если соответствующий параметр пропущен, будет использован фрейм карты с именем WEBMAP_MAP_FRAME. Или можно использовать заданный пользователем mapframe_name. Функция выполняется с ошибкой, если есть несколько фреймов карты, но среди них нет фрейма с именем WEBMAP_MAP_FRAME и параметр mapframe_name не указан. (Значение по умолчанию — None) | String |
notes_gdb | Строка, содержащая путь к новой или существующей файловой базе геоданных либо к имеющемуся подключению к многопользовательской базе геоданных, в которую будут записаны графические объекты. Этот параметр должен использоваться только в случае, если графические элементы веб-карты JSON должны постоянно сохраняться. Чаще всего этот параметр не нужен, т.к. для хранения графических объектов будет использоваться находящаяся в памяти компьютера временная рабочая область. Этот параметр позволяет сохранять графические объекты во постоянное хранилище. Путь должен заканчиваться расширениями .gdb или .sde. (Значение по умолчанию — None) | String |
| Тип данных | Описание |
| tuple | Возвращает именованный кортеж Python веб-карты и запрашивает свойства.
|
Пример кода
В этом примере скрипт считывает веб-карту JSON. Выходной MapView из ConvertWebMapToArcGISProject экспортируется в файл PNG. Выходная карта не содержит никаких элементов страницы компоновки (таких как заголовок, легенда или масштабная линейка).
import arcpy
import os
import uuid
# Input web map json
Web_Map_as_JSON = arcpy.GetParameterAsText(0)
# Convert the web map to an ArcGIS Project
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON)
aprx = result.ArcGISProject
# Get the map view
m = aprx.listMaps()[0]
mv = m.defaultView
# Use the uuid module to generate a GUID as part of the output name
# This will ensure a unique output name
output = 'WebMap_{}.png'.format(str(uuid.uuid1()))
Output_File = os.path.join(arcpy.env.scratchFolder, output)
# Export the web map
mv.exportToPNG(Output_File, result.outputSizeWidth, result.outputSizeHeight, result.DPI)
# Set the output parameter to be the output file of the server job
arcpy.SetParameterAsText(1, Output_File)
# Clean up
del mv, m, aprx, resultВ этом примере скрипт считывает веб-карту JSON. Выходной экстент MapView из ConvertWebMapToArcGISProject будет изменен перед экспортом в файл PNG. Функция exportToPNG использует заданные пользователем значения для параметров height, width, world_file и color_mode. Выходная карта не содержит никаких элементов страницы компоновки (таких как заголовок, легенда или масштабная линейка).
import arcpy
import os
import uuid
# Input web map json
Web_Map_as_JSON = arcpy.GetParameterAsText(0)
# Convert the web map to an ArcGIS Project
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON)
aprx = result.ArcGISProject
# Get the map view
m = aprx.listMaps()[0]
mv = m.defaultView
# Change the extent of the map view
ext = mv.camera.getExtent()
ext.XMin = ext.XMin + 100
ext.YMin = ext.YMin + 100
ext.XMax = ext.XMax + 100
ext.YMax = ext.YMax + 100
mv.camera.setExtent(ext)
# Use the uuid module to generate a GUID as part of the output name
# This will ensure a unique output name
output = 'WebMap_{}.png'.format(str(uuid.uuid1()))
Output_File = os.path.join(arcpy.env.scratchFolder, output)
# Export the web map
mv.exportToPNG(Output_File, width=1000, height=1000, world_file=True, color_mode="32-BIT_WITH_ALPHA")
# Set the output parameter to be the output file of the server job
arcpy.SetParameterAsText(1, Output_File)
# Clean up
del mv, m, aprx, resultВ этом примере используется промежуточный шаблон компоновки (файл .pagx), который содержит векторные эквиваленты всех возможных сервисных слоев. После выполнения функции ConvertWebMapToArcGISProject скрипт просматривает все слои выходного документа карты и удаляет все слои, кроме промежуточных векторных, которые соответствуют сервисным слоям в веб-карте JSON. Затем выходная компоновка экспортируется в файлы PDF или PNG. В это примере также показывается, как добавить экстра-параметры (Georef_info) из веб-приложения в скрипт Python, в дополнение к стандартным параметрам, поддерживаемым задачей печати.
import arcpy
import os
import uuid
# The template location in the server data store
templatePath = '//MyServer/MyDataStore/Templates'
# Input WebMap JSON
Web_Map_as_JSON = arcpy.GetParameterAsText(0)
# Format for output
Format = arcpy.GetParameterAsText(1)
# Input layout template
Layout_Template = arcpy.GetParameterAsText(2)
# Extra parameter - georef_info
Georef_info = arcpy.GetParameterAsText(3)
# Convert Georef_info string to boolean
if Georef_info.lower() == 'false':
Georef_info_bol = False
elif Georef_info.lower() == 'true':
Georef_info_bol = True
else:
Georef_info_bol = True
# Get the requested layout template pagx file
templatePagx = os.path.join(templatePath, Layout_Template + '.pagx')
# Convert the WebMap to an ArcGISProject
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON, templatePagx, "Layers Map Frame")
aprx = result.ArcGISProject
layout = aprx.listLayouts()[0]
# Reference the map that contains the webmap
m = aprx.listMaps('Web Map')[0]
# Remove the service layer
# This will just leave the vector layers from the template
for lyr in m.listLayers():
if lyr.isWebLayer:
m.removeLayer(lyr)
# Use the uuid module to generate a GUID as part of the output name
# This will ensure a unique output name
output = 'WebMap_{}.{}'.format(str(uuid.uuid1()), Format)
Output_File = os.path.join(arcpy.env.scratchFolder, output)
# Export the WebMap - use Georef_info_bol to control georeferencing
if Format.lower() == 'pdf':
layout.exportToPDF(Output_File, georef_info=Georef_info_bol)
elif Format.lower() == 'png':
layout.exportToPNG(Output_File, world_file=Georef_info_bol)
# Set the output parameter to be the output file of the server job
arcpy.SetParameterAsText(4, Output_File)
# Clean up
del layout, aprx, resultВ этом примере, функция updateLayerFromJSON из класса Layer используется для обновления свойств (например, символов) промежуточного векторного слоя в шаблоне компоновки с определением динамического слоя из веб-карты JSON. Это удобно, если веб-приложение позволяет менять символы динамических слоев, и вы хотите заменить слои сервиса на промежуточные векторные данные, но все еще видите обновленные символы из веб-приложения.
import arcpy
import os
import uuid
import json
# The template location in the server data store
templatePath = '//MyMachine/MyDataStore/WebMap'
# Input WebMap json
Web_Map_as_JSON = arcpy.GetParameterAsText(0)
# Input Layout template
Layout_Template = arcpy.GetParameterAsText(1)
if Layout_Template == '#' or not Layout_Template:
Layout_Template = "Landscape11x17"
# Get the requested layout template
templatePagx = os.path.join(templatePath, Layout_Template + '.pagx')
# Convert the web map to an ArcGIS Project
result = arcpy.mp.ConvertWebMapToArcGISProject(webmap_json, templatePagx)
aprx = result.ArcGISProject
# Reference the map that contains the web map
m = aprx.listMaps('Web Map')[0]
# Reference the staged vector data that corresponds to the dynamic layer in the JSON
# This is the layer that will get updated based on the layer definition in the JSON
lyr = m.listLayers("U.S. States (Generalized)")[0]
# Read the JSON and extract the layer definition
# In this case we have hardcoded it to second operational layer
data = json.loads(Web_Map_as_JSON)
layerDefinition = data["operationalLayers"][1]
# Update the staged vector layer with the layer definition (e.g. renderer info) from the JSON
lyr.updateLayerFromJSON(layerDefinition)
# Remove all service layers. This will leave only staged vector layers.
for slyr in m.listLayers():
if slyr.isServiceLayer:
m.removeLayer(slyr)
# Use the uuid module to generate a GUID as part of the output name
# This will ensure a unique output name
output = 'WebMap_{}.pdf'.format(str(uuid.uuid1()))
Output_File = os.path.join(arcpy.env.scratchFolder, output)
# Export the web map
layout = aprx.listLayouts()[0]
layout.exportToPDF(Output_File)
# Set the output parameter to be the output file of the server job
arcpy.SetParameterAsText(2, Output_File)
# Clean up
del layout, m, aprx, resultВ этом примере скрипт считывает веб-карту JSON, выходной формат, шаблон компоновки и существующие документы PDF, к которым будет присоединена веб-карта. Выходная компоновка из функции ConvertWebMapToArcGISProject экспортируется в PDF, затем включается в другой файл PDF с помощью класса PDFDocument.
import arcpy
import os
import uuid
# The template location in the server data store
templatePath = '//MyMachine/MyDataStore/MapBook'
# Input WebMap json
Web_Map_as_JSON = arcpy.GetParameterAsText(0)
# Input Layout template
Layout_Template = arcpy.GetParameterAsText(1)
if Layout_Template == '#' or not Layout_Template:
Layout_Template = "LandscapeLetter"
# PDF Title Page
PDF_Title = arcpy.GetParameterAsText(2)
if PDF_Title == '#' or not PDF_Title:
PDF_Title = "TitlePage.pdf"
# PDF End Page
PDF_End = arcpy.GetParameterAsText(3)
if PDF_End == '#' or not PDF_End:
PDF_End = "ContactInfo.pdf"
# Get the requested layout template
templatePagx = os.path.join(templatePath, Layout_Template + '.pagx')
# Get the requested PDF files
PDF_Title_File = os.path.join(templatePath, PDF_Title)
PDF_End_File = os.path.join(templatePath, PDF_End)
# Convert the WebMap to an ArcGIS Project
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON,
templatePagx)
aprx = result.ArcGISProject
layout = aprx.listLayouts()[0]
# Use the uuid module to generate a GUID as part of the output name
# This will ensure a unique output name
WebMapPDF = os.path.join(arcpy.env.scratchFolder,
'WebMap_{}.pdf'.format(str(uuid.uuid1())))
# Export the WebMap to PDF
layout.exportToPDF(WebMapPDF)
# Create a new "master" output PDF Document
# Append Title, WebMap and End PDFs to it
Output_Name = os.path.join(arcpy.env.scratchFolder,
'OutputWithWebMap_{}.pdf'.format(str(uuid.uuid1())))
pdfDoc = arcpy.mp.PDFDocumentCreate(Output_Name)
pdfDoc.appendPages(PDF_Title_File)
pdfDoc.appendPages(WebMapPDF)
pdfDoc.appendPages(PDF_End_File)
pdfDoc.saveAndClose()
# Set the output parameter to be the output PDF
arcpy.SetParameterAsText(4, Output_Name)
# Clean up
del aprx, result, layoutВ этом примере используется шаблон компоновки (файл .pagx), для которого включена функция Пространственные многостраничные карты. Объекты индексирования многостраничных карт, которые пересекают экстент веб-карт, экспортируются в многостраничный PDF.
import sys, os, arcpy, uuid
# The template location in the server data store
templatePath = '//MyServer/MyDatastore/Templates'
# Input web map json
Web_Map_as_JSON = arcpy.GetParameterAsText(0)
# Format for output (PDF)
Format = arcpy.GetParameterAsText(1)
# Define output PDF file name
pdfMapSeries = os.path.join(arcpy.env.scratchFolder, 'WebMapSeries_{}.pdf'.format(str(uuid.uuid1())))
# Input Layout template
Layout_Template = arcpy.GetParameterAsText(2)
templatePagx = os.path.join(templatePath, Layout_Template)
# Convert the web map to an ArcGIS Project
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON, templatePagx, 'Series Map Frame')
aprx = result.ArcGISProject
layout = aprx.listLayouts('Layout')[0]
ms = layout.mapSeries
mf = layout.listElements('MAPFRAME_ELEMENT', 'Series Map Frame')[0]
# Get the extent of the mapframe from the web map as a geometry object
extent = mf.camera.getExtent().polygon
# This the Map Series index layer
mapSeriesLyr = mf.map.listLayers("World Countries")[0]
# Select the map series index features that intersect the web map extent
arcpy.management.SelectLayerByLocation(mapSeriesLyr, "INTERSECT", extent, selection_type="NEW_SELECTION")
# Display a message indicating which page numbers will be exported
pageRange = ', '.join(str(e) for e in ms.selectedIndexFeatures)
arcpy.AddMessage('Exporting the following map series page numbers: ' + pageRange)
# Export the selected Map Series pages
ms.exportToPDF(pdfMapSeries, 'SELECTED')
# Set the output parameter to be the output file of the server job
arcpy.SetParameterAsText(3, pdfMapSeries)В этом примере показано, как получить доступ к выбранным объектам из сервиса объектов на веб-карте и отобразить их в отчете. Функция importDocument в классе ArcGISProject используется для импорта файла отчета (.rptx) в проект ArcGIS Pro, который возвращается от ConvertWebMapToArcGISProject. По умолчанию в отчете отображаются только выбранные объекты. Класс Отчет использует для установки источник данных отчета. Выходная компоновка и отчет экспортируются как файлы PDF и связываются друг с другом с помощью класса PDFDocument.
import arcpy
import os
import uuid
# The template location in the server data store
templatePath = '//MyServer/MyDataStore/Templates'
# Input WebMap json
Web_Map_as_JSON = arcpy.GetParameterAsText(0)
# Input layout template
Layout_Template = arcpy.GetParameterAsText(1)
if Layout_Template == '#' or not Layout_Template:
Layout_Template = "Landscape_Letter_Layout"
# Input report template
Report_Template = arcpy.GetParameterAsText(2)
if Report_Template == '#' or not Report_Template:
Report_Template = "Landscape_Letter_Report"
# Get the requested layout template
templatePagx = os.path.join(templatePath, Layout_Template + '.pagx')
# Get the requested report template
templateReport = os.path.join(templatePath, Report_Template + '.rptx')
# Convert the WebMap to an ArcGIS Project
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON,
templatePagx,
"Map Frame")
aprx = result.ArcGISProject
# Import the report template
aprx.importDocument(templateReport)
report = aprx.listReports()[0]
# Reference the layer from the web map that the report will be based on
lyr = aprx.listMaps('Web Map')[0].listLayers('Sample Sites')[0]
# Change the report data source to be the layer from the web map
report.setReferenceDataSource(lyr)
# Get the selected feature ObjectIDs from the web map layer
oids = lyr.getSelectionSet()
# The report template is configured to only export selected features
if oids is not None:
# Export the report to PDF
ReportPDF = os.path.join(arcpy.env.scratchFolder,
'WebMapReport_{}.pdf'.format(str(uuid.uuid1())))
report.exportToPDF(ReportPDF)
# Export the layout to PDF
LayoutPDF = os.path.join(arcpy.env.scratchFolder,
'WebMapLayout_{}.pdf'.format(str(uuid.uuid1())))
layout = aprx.listLayouts('Layout')[0]
layout.exportToPDF(LayoutPDF)
# Append the report to the layout PDF
pdfDoc = arcpy.mp.PDFDocumentOpen(LayoutPDF)
pdfDoc.appendPages(ReportPDF)
pdfDoc.saveAndClose()
# Set the output parameter to be the output PDF
arcpy.SetParameterAsText(3, LayoutPDF)
# Clean up
del aprx, result, layout, report, lyrВ этом примере функция ImportCredentials используется для доступа к защищенным сервисам ArcGIS Server secured services.
import arcpy
import os
import uuid
# The template location in the server data store
templatePath = '//MyServer/MyDataStore/Templates'
# Input WebMap JSON
Web_Map_as_JSON = arcpy.GetParameterAsText(0)
# Input layout template
Layout_Template = arcpy.GetParameterAsText(1)
# Get the requested layout template pagx file
templatePagx = os.path.join(templatePath, Layout_Template + '.pagx')
# Specify credentials for secured services in the WebMap JSON
secure_server_connections = [os.path.join(templatePath, 'secured.ags'),
os.path.join(templatePath, 'secured.wms')]
# Import credentials
importedConnections = arcpy.ImportCredentials(secure_server_connections)
# Convert the WebMap to an ArcGISProject
result = arcpy.mp.ConvertWebMapToArcGISProject(Web_Map_as_JSON, templatePagx, "Layers Map Frame")
aprx = result.ArcGISProject
layout = aprx.listLayouts()[0]
# Use the uuid module to generate a GUID as part of the output name
# This will ensure a unique output name
output = 'WebMap_{}.pdf'.format(str(uuid.uuid1()))
Output_File = os.path.join(arcpy.env.scratchFolder, output)
# Export the WebMap
layout.exportToPDF(Output_File)
# Set the output parameter to be the output file of the server job
arcpy.SetParameterAsText(3, Output_File)
# Clear credentials
arcpy.ClearCredentials(importedConnections)
# Clean up
del layout, aprx, result