More

Programmatically adding .shp file to .mxd file

Programmatically adding .shp file to .mxd file


I have spent hours attempting to find the solution to the following problem online, but all answers I have found are quite old, and none work. Here is the situation: I have a variety of .shp files. I have a blank mxd file. I want to add the .shp files into the .mxd file.

Various stackoverflow and stackexchange answers would have me believe that the answer to my problem lies in either: arcpy.MakeFeatureLayer_management(,) or arcpy.mapping.Layer()

Unfortunately, I get a similar error no matter what approach I take.

The exact code from my most recent attempt (I'm really not sure how this could possibly be simpler):

import arcpy arcpy.env.workspace = "C:/test" arcpy.Exists("shapefile.shp") #returns True arcpy.mapping.Layer("shapefile.shp")

It is at this point that I receive the following error: Traceback (most recent call last):… File "C:Program FilesArcGISServerarcpyarcpyarcobjectsmixins.py", line 289 in init super(LayerMixin, self).init(lyrfile) File "C:Program FilesArcGISServerarcpyarcpyarcobjects_base.py", line 47, in init for arg in args ValueError: Object: CreateObject Layer invalid data source

Edit: exact code from my attempt using the other function

import arcpy arcpy.env.workspace = "C:/test" arcpy.Exists("shapefile.shp") #returns True arcpy.MakeFeatureLayer_management("shapefile.shp","myshapelayer")

In this case, I receive the following error: Traceback (most recent call last):… arcgisscripting.ExecuteError: ERROR 000229: Cannot open shapefile.shp Failed to execute .

Can anyone advise me as to how to proceed? I have found almost five different solutions suggesting that this is the procedure which I should follow, but it definitely isn't working for me. I am using Python 2.7.

Additional Notes: -I have manually loaded the shapefile in ArcMap, it loads and displays correctly.


You're improperly using the arcpy.mapping.Layer function.

arcpy.mapping.Layer takes a Layer File (*.lyr) saved on disk and returns a Layer Object from that.

Layer Objects have methods which you can use to change various properties of the layer, such as its visibility, transparency, definition query, etc.

You're giving it a shapefile. Hence the error, invalid data source.

Just use the MakeFeatureLayer_management function which will create an in_memory Feature Layer and automatically add it to the current MXD, where the first argument is the absolute path to your shapefile, and the second argument is a string representing the name of the layer as it will appear in the Table of Contents.

arcpy.MakeFeatureLayer_management(r"C:SomeDataPathshapefile.shp", "MyShapefile")

I have finally solved the problem - it was actually a simple fix - a misunderstanding on my part. I failed to realize that a "shapefile" is far more than just the ".shp" file. Apparently you need to have all (five?) files (with all (five?) extensions) in the appropriate directory in order for the function to work properly. After adding my .dbfs, my .xmls, etc., it works just fine.


The following code contains more than you need, but it will show that you need to specify or create a blank mxd, then specify a data frame, then activate that data frame then add your layers/shapefiles with optional symbology specified

"mxd_create.py Author: [email protected] Purpose: create a base mxd and populate it with default values Requires: specify the files to load and the default dataframes etc template paths ie C:Program Files (x86)ArcGISDesktop10.2MapTemplatesTraditional LayoutsLetterLandscape.mxd C:Program Files (x86)ArcGISDesktop10.2MapTemplatesTraditional LayoutsLetterPortrait.mxd"import arcpy import sys import os import shutil script = sys.argv[0] # script name and location mxd_src = "C:/!test/mapping/mxd_test02.mxd" # a shell empty project path, doc = os.path.split(mxd_src) template = path + "/LetterPortrait.mxd" shutil.copyfile(template,doc) arcpy.env.workspace = path + "/shapefiles" arcpy.overwriteOutputs = True shp_files = ["AOI_mtm9.shp", "RandomPnts.shp"] lyr_files = ["AOI_mtm9.lyr","RandomPnts.lyr"] arcpy.ListFiles("*.lyr") #use this to check above author = "This could be you!!!!" description = "Demo project working with the arcpy.mapping module and Python" title = "Arcpy Mapping Demo: Introduction to arcpy.mapping and Python interaction" mxd = arcpy.mapping.MapDocument(doc) mxd.author = author mxd.description = description mxd.title = title mxd.relativePaths = True df = arcpy.mapping.ListDataFrames(mxd)[0] # list of data frames, 1 exists by default df.name = "Sample files" # set its title mxd.activeView = df.name # activate it for shp in shp_files: # cycle through the list of shapefiles #fn, ext = os.path.splitext(f) # for testing lyr = arcpy.mapping.Layer(shp) # add the files and auto arrange arcpy.mapping.AddLayer(df,lyr,"AUTO_ARRANGE") arcpy.ApplySymbologyFromLayer_management(lyr,lyr_files[1]) # apply symbology from lyr files #arcpy.mapping.UpdateLayer(df, updateLayer, sourceLayer, True) arcpy.RefreshActiveView() mxd.save() del template, shp_files, lyr_files, lyr, df, mxd os.startfile(doc) del doc ##

Cara Export Banyak MXD ArcGIS Sekaligus (Multiple Export)

Dalam mengerjakan suatu project atau tugas GIS menggunakan ArcGIS (Arcmap) dengan banyak file MXD tentunya akan memakan waktu lama jika harus mengexportnya satu per satu ke format JPG, PNG atau PDF. Dengan menggunakan script phyton yang sudah dibungkus dalam sebuah toolbox akan sangat memudahkan teman-teman untuk melakukan Export MXD secara praktis sehingga bisa mengemat waktu dan tenaga kita dalam pekerjaan.

Dengan menggunakan script phyton (toolbox) di bawah ini, maka tanpa perlu sibuk membuka masing-masing mxd, file akan terexport secara otomatis sekaligus. Berikut contoh preview tampilan toolboxnya.

Script phyton (toolbox) Ini adalah alat sederhana untuk mengekspor beberapa dokumen peta (mxd) ke PDF, PNG dan JPG dalam jumlah banyak sekaligus. Dokumen masukan peta (mxd) dapat ditambahkan dari lebih dari satu lokasi ke satu lokasi. Teman-teman dapat menentukan resolusi (DPI) untuk setiap format. Namun, harap diingat bahwa DPI bekerja secara berbeda untuk setiap format. Jadi, kita perlu menyesuaikannya. ArcPy adalah satu-satunya perpustakaan yang digunakan untuk skrip ini. Script dapat dilihat atau dimodifikasi sesuai dengan kebutuhan teman-teman. Ini dapat dilakukan dari ArcCatalog. Pada update terakhir sudah ada fitur menambahkan opsi untuk menggabungkan beberapa dokumen PDF menjadi satu.

Untuk menjalankannya sangat simpel sekali. Pastikan mxd nya sudah final dan siap untuk diexport ke PDF, PNG dan JPG.

  1. Buka aplikasi ArcMap atau juga bisa melalui ArcCatalog
  2. Buka jendela Arctoolbox untuk melakukan Add Toolbox > cari lokasi tools exporter yang sudah di unduh.
  3. Setelah toolbox ditambahkan silahkan dibuka maka akan muncul jendela script baru.
  4. Silahkan masukkan MXD yang akan di export (bisa lebih dari satu)
  5. Tentukan folder outputnya
  6. Resolusi (dpi)
  7. Format export seperti PDF, PNG dan JPG - bisa juga PDF yang langsung dicombine (gabungan)
  8. Terakhir OK, maka tools akan melakukan proses export dan lihat hasilnya.

Baiklah sekian dulu untuk sharing kali ini tentang Export Banyak MXD ArcGIS Sekaligus - Multiple Export. Jika ada saran, tanggapan, pertanyaan, link mati serta request silakan gunakan kotak komentar, halaman kontak atau sosial media yang ada di website Lapak GIS. Terima Kasih.

Lapak GIS 

Lapak GIS adalah Tempat Berbagi Pengetahuan tentang Geographic Information System (GIS) dan Remote Sensing (Pengindraan Jauh).


Watch the video: Convert ArcGIS file types .lyr.mxd to QGIS with SLYR. burdGIS