Showing posts with label coding. Show all posts
Showing posts with label coding. Show all posts

Wednesday, August 17, 2022

Remove Marker from Shape Elements in Inkscape

There's a known bug in Inkscape that prevents removing special markers from the start and end points of a polygon element.

  • Select a line, circle/ellipse, or a polygon object
  • Apply a stroke in the Stroke paint tab on the Fill and Stroke dialog
  • Navigate to the Stroke style tab and select an Start/Mid/End marker


I'm making a diagram with a number of line elements that I wanted to be displayed with arrow heads.


I know there are settings that let you use the last style as the default for new elements so you don't have to copy and paste the formatting to additional objects. Somewhere along the way, I think my line markers got applied to my polygon elements. Now I have weird arrow heads at the start/end point of my shape, which is absolutely not acceptable.

Rather than duplicating existing shapes to try find a clean element to resolve this, use the XML Editor to edit the element's properties to get rid of those arrowheads entirely. Using the XML Editor will allow you to edit existing elements without having to re-create the design from scratch each time.

  • Select the object
  • Navigate to Edit > XML Editor or launch it from the shortcut: Ctrl+Shift+X
  • With the graphic object selected in the list at the top of the editor, click on the style element to begin editing it's style attributes
  • Select and remove the marker-start; & marker-end; attributes. Ensure that you didn't remove too many- or leave any extra semicolon characters (;) as each attribute will be separated by one semicolon 
  • Click the check ✅ to apply the edits

Additional shapes may still have unwanted arrow markers, so clean up and restart the project.
  • Choose File > Clean Up Document
  • Save the project
  • Close and re-open Inkscape

Thursday, August 11, 2022

Roadway Index Consolidation

The fire department needs an updated wall map of city roadways with a lookup grid and an alphabetically sorted index of roadway names for rapid review. This workflow creates a grid index, and joins its identification information to all roadways within each cell; which are then consolidated into a reference index.

While this illustration uses a gridded map index, this method can be used to summarize features that exist across any kind of aerial boundary unit: for instance zip codes, districts, neighborhoods, etc.

Here is the City of Cocoa's footprint:

Create an Area of Interest Layer

This is for firefighters at Station 2, so their area of interest is mainly focused in the southeast portion of the city and surrounding areas. I created a polygon layer to describe that footprint, using ArcGIS Pro's Direction tool in the Edit toolset to snap digitized vertexes to cardinal directions for 90º corners.
ℹ Precision isn't super important here, so I didn't switch over to a Mercator projection for digitization. I left the coordinate system in NAD83 Florida State Plane East (FIPS 0901) US Feet to avoid errors in the next step which is more important.

Create Fishnet Grid

We'll test ½ square mile grid cells (2640' x 2640') to balance fitting a sufficient amount of streets into a grid cell without being too densely populated and hard to identify a roadway within a cell.
  • Open the Create Fishnet tool
  • In ArcGIS Pro 3.0, open the dropdown at the top of the Template Extent section and choose Browse to select the Area of Interest layer that we created above as the template for the extent of this grid feature class
  • Ensure you're using the appropriate coordinate system with expected unit of measure for your own needs. I'm using FL State Plane East with US Feet as the unit of measure so I can enter a value of feet for an accurate grid cell size
    • Enter 2640 in the Cell Size Width & Cell Size Height fields (which is half a mile in US feet)
    • Set the Geometry Type to Polygon and run the tool

Cull & Customize the Grid

Many of these cells are over water, and I'd prefer to get rid of those and use that space for the Index. Even if the index doesn't fit there and I end up printing it out separately, I'd still prefer to remove those unnecessary cells in the northeast. 
  • Open the Attribute Table
  • Add a Field to named Status
  • Manually select of those unwanted cells (107-110, and down running southeast to cell 33) 
  • Calculate Values of "Blank" or "Remove" or whatever
  • Open the Layer Properties for that Fishnet layer and navigate to the Definition Query section
  • Click New definition query
    • Where Status | Is Null

Re-Calculate Grid IDs

This will remove those features from the view, but the grid ID numbers will become inconsistent: e.g. After cell 32, numbering will continue on the next line above at 34.


Since the definition query is already in place, and the intended order is already sorted based on the object ID, we can run a custom field calculation to create a new contiguous unique ID to fix these gaps.
ℹ Optional: To be safe, you can create a new field (named ID_Original) to preserve the original ID. You'll first need to temporarily disable the definition query to record all values; Calculate Field on that new ID_Original and simply use the OID field to populate the ID value for every record. When finished, re-apply the definition query.
  • Create another new field named ID_Truncated or something similar
  • Ensure there is no selection, and the definition query is set to exclude any unwanted parcels (see the graphic above)
  • Open the Calculate Field dialog to calculate values on that new field
    • ID_Truncated = autoIncrement()
    • Code Block: Enter the following script and click Apply to run
rec=0
def autoIncrement():
    global rec
    pStart = 1  # adjust start value, if req'd 
    pInterval = 1  # adjust interval value, if req'd
    if (rec == 0): 
        rec = pStart 
    else: 
        rec = rec + pInterval 
    return rec


  • Finally, change the labeling field to the new ID_Truncated 

Join Grid IDs to the Roadways

Now run an Intersect process to join the grid cell IDs to each roadway, while splitting roadway segments at the borders of each grid cell
  • Input Features: the Roadway Centerlines layer, and the Fishnet grid layer
  • Attributes: All
  • Output Type: Line
The result will be a line dataset set to the extent of the fishnet grid:

Export to Spreadsheet Editor

Move over to Excel/Sheets to finish processing. Run the Table to Excel tool to export the attribute table of the resulting Intersect process. This will make it easier to consolidate the dataset into distinct roadways with multiple IDs concatenated together. Here's an example:

  • Open the dataset in Excel and hide all field besides the Address Label (from the Roadway Centerlines dataset) and the ID_Truncated field (from the fishnet grid)
  • Add three field headings after these two fields: named Count, End, and Formatted

Clean up the Data

  • Select the first row of headings, navigate to the Data tab and click the Filter button to turn on field filtering tools
  • Sort the Address Label field, ascending
  • Remove any blank or null Address Labels by selecting those records and deleting those rows
  • Select cell A1 and press Ctrl+A to select all records
  • Navigate to the Data tab and run the Remove Duplicates tool
    • Select the Address Label and the ID_Truncated fields and click OK to run. The tool will report how many duplicate records were removed

Create Analysis & Formatting Formulas

Use the following formulas for those three new fields. Count and End are for reference and filtering use later, while the Formatted field is going to help build the index mapping that we're summarizing
  • Enter the following formulas for each cell:
    • Count: =COUNTIF($A$2:$A$1177,A2)
      * Where 1177 is the last row in the dataset
    • End: =IF(A2=A3, "", "End")
    • Formatted, line 2: =B2
    • Formatted, line 3: =IF(A3=A2,E2 & ", " & B3, B3)
  • Fill the formulas down the the bottom of the dataset, leaving cell B2 as a unique outlier to help start the formatting trick 

Here's what's happening in each of these new fields:
  1. The Count field compares downward, and aims to report how many times an Address Label is present across the dataset. A Lane is in the dataset twice, while A Street is in the dataset three times.
  2. The End field aims to mark the end of a group of addresses. We'll use this flag for filtering reasons next. Notice the value of End on the 2nd of two records for A Lane, and the 3rd of three records for A Street.
  3. Most importantly, we're beginning by taking the first ID in the dataset and writing that to the Formatted field. On the next row, we're looking upward to see if this next record's address is the same as the previous. If so, that means our address is found on an additional grid cell, so we're concatenating it with the previous cell, separated with a comma and a space. If the previous Address Label is different, then it's a new address and we'll pull a new ID by itself.

Consolidate with Formatting

Now we'll finish up by applying that filter.
  • Make those formulas permanent by copying those cells and Paste Special > Values
  • Select the filter menu for the End field and remove the Blank category. Click OK to apply the filter
  • The unnecessary records are merely hidden here. Hit Ctrl+A to Select All records, and Paste it into a new worksheet to make the dataset permanent. Notice the spreadsheet's row numbers are now sequential 

Stylize & Finishing

  • Remove the ID_Truncated, Count, and End fields
  • Rename the remaining fields to Roadway, and Grid
  • Optionally, you may want to use the formula =PROPER(A2) or =UPPER(A2) to change the case of the Address Label field as needed
  • Adjust the formatting of the font size and typeface to suit your map's style
At last, copy and paste the range (or segments of the dataset at a time) back into your mapping project for final cartography and layout.



Tuesday, April 25, 2017

Setup Arduino Print Line / Debug Print / Console Log Messaging

It took me a few extra minutes to figure out why any Serial.println() statements weren't appearing in my Arduino IDE's Serial Monitor. I'm brand new to Arduino coding, but it seemed like if you click the Serial Monitor icon your debug/print line messages should show up there.

For this basic example, I set the Arduino Uno's onboard LED on Pin 13 to blink twice per second, with a println() statement running just after each change of the LED's state. Esssentially:

  • Turn on the LED
  • Write me a message that says On
  • Turn it off
  • Write Off
  • Etc.


It turns out that I needed to set the channel to communicate with the IDE in code.

Inside void setup(){} add the line Serial.begin(9600); where the value 9600 matches the baud rate in the Serial Monitor.






That's it. It begins writing to the monitor as soon as you upload the sketch and the device resets itself.

There's some more information about the begin() method on the Arduino Language Reference

Thursday, December 3, 2015

Automating Password Management

I have a password that I don't particularly need to be super secret, but I don't really want to memorize another password either.

I  put together a script that will automatically copy the password to the clipboard (essentially a Control + C command of text). I threw this into a project folder and I can run the script quickly by double clicking it.

For the sake of slight security, I named the file something boring and unrelated.

Code

from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('password')
r.destroy()


Setup

  • Install Python if it's not already installed
  • Copy the code above
  • Paste into Notepad or another text editor
  • Replace the highlighted password with your own password
  • Save as type: All Files (*.*)
  • File Name: "SomeFileName.py"
    • Wrapping the filename in quotes ensures the file type will be set to .py - a python script file
  • Double click on the file to run it. A Python window will briefly open and close automatically
  • Navigate to a text area and hit Ctrl+V or use some other paste command

Sunday, November 29, 2015

Color Development: Tools and Methods

I accidentally went nuts writing about the basics of digital color, so I decided to make it a separate article.  Check that out:
Color Development: Digital Color Basics
In this article, I'll list a few tools I use for color development, and discuss how I like to brew and develop colors in graphic design and cartography environments.

Color Brewing

These are some of my favorite tools to build and tune color sets.

Browser Utilities

ColorPick Eyedropper



ColorPick Eyedropper is a Chrome extension that enables you to quickly grab a color from a Web page. There's even a rad little magnifying visualization that helps zero in on the exact pixel you need.



Desktop Utilities

ColorPic


ColorPic is a great desktop tool to help snag Hex, HSV, RGB, CMYK, values, and save your own custom groups of color. There are even sliders, and grids to use to help build or tune your colors if necessary.

ColorOracle

ColorOracle is a fantastic color deficiency simulator. It's a quick way to preview your entire monitor view for any potential issues with color patterns which may be difficult to read for those with color-vision impairments. No exporting


Sunday, June 7, 2015

Make New Project Directory

I like to organize photos, videos, GIS projects, and developments projects in separate "project directories." Each project folder has the following format:
YYYY-MM-DD - Description

File Structure Example:
  • [Drive]:\
    • Development
      • 2014-10-04 - Scuba Calculators
      • 2015-06-01 - Make New Project Directory
    • GIS
      • 2012-05-14 - Whatever Project...
        • Shapefiles
        • Exports
        • From Client
        • MXDs
    • Photos
      • 2013-04-05 - Birthday in Midtown
        • Hilights
          • Edited
        • Original
      • ...
    • Videos

This is an easy way to chronologically catalog projects within their respective folders, but I'm lazy, and I hate having to look down at my task bar clock to find out what the date is, and I can't stand typing in that endless date!

Solutions Posted on GitHub

I posted all the scripts I came up with for this on my GitHub page under the Make New Project Directory repo.

Batch File

I originally tried coming up with a Batch file (.bat) to add the folder using the format I wanted. It's easy to make a predefined folder structure using CMD commands, but pulling that date style turned out to be a little tricky, so I looked elsewhere.

Python Script

I came up with a great Python script that will automatically add a folder that's named with the current date followed by XXXXDescriptionXXXX (so I could easily find and rename it further). Just double click the python file and the new project folder is added. Additionally, I repeated the code to add subdirectories for common sub-folders: Exports and Shapefiles for GIS projects; Originals, Highlights, and Edited for photos & video; etc.


Pros:

  • This is great! It works automatically
  • Simple code. It executes in 6 lines.  View the code here

Cons:

  • I quickly realized how awfully tedious it is to have to slow double click to rename, something every time I create a new project. I need some kind of interface to enter a project name, and I haven't had great luck using TkInter yet.
Note: I've heard good things about PyQt for an interface
  • I don't necessarily want those sub-directories for every project

VBScript

My best solution so far was to write a VBScript (.vbs format) to prompt me for a project name AND ask if I want to add those common project sub-folders.






Pros:

  • Most efficient method so far
  • Quick, easy, no renaming
Cons:


  • Slightly longer code (24 lines without comments & line continuation), but it does include some more logic handling. View the code here.
  • This is still generalized, and the "common subdirectories" option is hard coded (i.e. I don't need a Shapefiles directory in a video editing project).
Overall, This VBScript method opens the door to writing a slightly larger executable in Visual Studio with a more dynamic interface to add any kind of project folder - but that moves away from the original requirement of a highly rapid way to add a project folder automatically. I think this nails it.




    Tuesday, March 10, 2015

    Make New Directory Script

    I like to keep my projects organized by date. I  name new project folders with this format inside a "Project" folder on the root of my data drive:

    YYYY-MM-DD - Project Description

    It'll end up like this:

    D:\Projects\2015-03-10 - Make New Directory Script\

    It's an easy way to keep things consistently organized. I'll usually have some ambiguous reference directories in there that I don't want to be mixed in with regular projects (e.g. development, temp data, snippets, links, tools, logos, notes, etc.).

    Shortcut Method

    Another method is to add a Date Created sorting option to your file explorer window, but this may not help keep projects separated from those reference directories:
    • Open Windows Explorer
    • Press Alt + v to open the View menu, and choose the Details view. Sorting options will appear over the main file area of the window
    • Right click on that details bar and choose More...
    • Scroll down and check Date created to add it as a sorting option. Look around the Details menu and select/deselect parameters that are useful or unhelpful

    Make a Formated Folder with Python

    Let's get real. I like my method.

    I'll also be honest: I'm not saving any real time here.  I can easily click the New Folder button and immediately start typing a folder name, but I have to look ALL the way down at the clock to verify the date, then I gotta type all 13 characters of the date prefix. I'm over it.


    I threw these two tricks together in five lines using Python's os and datetime modules - And 40% of that just calls those modules!

     import os  
     import datetime  
     today = datetime.date.today()  
     newpath = today.strftime('D:\Projects\%Y-%m-%d - Description')  
     if not os.path.exists(newpath): os.makedirs(newpath)  
    

    Line 3 prepares the today() date object
    Line 4 formats the path and embeds the 4-digit year (capital %Y), etc.
    Line 5 even checks to  make sure the path doesn't already exist.

    Killer.

    As long as you have Python installed, you can save this code as makeNewDirectory.py and run it. It should take just a fraction of a second to run.

    Batch File

    I was trying to run this as a .bat file, but it was kind of tricky and I got bored. Here's what I came up with.

    mkdir easily makes a new directory, and this comment on StackOverflow pulls apart a %date% stamp with concatenation. I got them to work separately, but not together. Play around with underscores and let me know what you can find.

    Tuesday, September 16, 2014

    Cannot Register Assembly for ESRI.ArcGIS.Desktop.AddIns

    I'm doing a lot of coding in Visual Studio 2010 for ArcGIS Desktop Add-ins at 10.2. Every few saves (build/rebuild solutions/etc.) I get an annoying message:
    Cannot register assembly "[path to my project]\[Projectname].dll". Could not load file or assemly ' ESRI.ArcGIS.Desktop.AddIns, Version=10.2.0.0, Culture=neutral, PublicKeyToken=[Unique Token]' or ont of its dependencies. They system cannot find the file specified.
    Screenshot of the error in the Error List window
    Try one or both of the following procedures to solve this problem.

    Disable COM Interop Registraion

    Some Esri forum posts mentioned to sure the "Register for COM interop" setting was disabled. Here's how to find it in Visual Studio 2010:

    • Go to the Properties window for the project from the Solution Explorer
    • Navigate to the Compile tab
    • Uncheck Register for Com interop toward the bottom of the page

    • Close and re-open Visual Studio and it should solve the issue.  If not, try the next step that we've been using a bit

    Remove & Re-Add AddIns Reference

    This usually only works for a few hours, or up to a few days, but it'll definitely solve the problem so you can continue work.
    • Open the Properties window for the project again, but navigate to the References tab.
    • Scroll down through the references and look for ESRI.ArcGIS.Desktop.AddIns under the Reference Name field. Highlight it and click the Remove button

    • Click the Add button just to the left of the Remove button and choose Reference...
    • Navigate to the .NET tab
    • Scroll down a ways (further than you might think; it's not necessarily in alphanumerical order) to find the ESRI.ArcGIS.Desktop.AddIns component.  Select it and click OK to add it. As long as you removed it in the previous step, it will be included in this list.
    • Close Visual Studio.  When you open it again, the problem will be fixed


    Friday, July 27, 2012

    HTML List with No Heading/Bullet/Number

    I make a lot of bulleted lists for this blog, as well as other Web-based tutorials and design documents.  Often I will want to insert a centered graphic for a given bullet point, however the indentation of the list will offset the center justification of the image - which looks like garbage on the narrow area provided in this blog's style.

    I can usually close the tags of the list, insert a centered graphic and move on with my life, however there are a few instances where I will want to return to the indentation of the list without starting a new bullet point.

    Basic illustration:
    Example:
    • A single item in an unordered list
    A centered image outside of an unordered list

    Code:
    <ul>

    <li>An example list</li>
    </ul>

    <img src="lolinternet.gif" />

    Omit <li> tags or use <p>:
    Instead of using a list item tag (<li>), use a paragraph tag (<p>) to jump back into the indentation without including a new bullet point.

    Example:
    • Another unordered list item
    Another centered image,
    outside of <ul> tags
      Returning to indentation without a bullet point
    • An additional bullet point

    Code:
    <ul>

    <li>Another unordered list item</li>
    </ul>

    <img src="lolinternet_8bit.gif" />

    <ul>
    <p>Returning to indentation without a bullet point </p>
    <li>An additional bullet point </li>
    </ul>



    Jump back into ordered lists in any defined order:
    However rarely, it is sometimes necessary to have more control over the order of a list.  One can begin a list at any position using any style.  These attributes have been deprecated and one should instead utilize a style, but the idea is still the same.

    Example - The Buzz Ordering System:


    1. I'm not that lucky
    1. We have smoke detectors
    1. We live on the most boring street in the United States of America; where nothing even remotely dangerous will ever happen. Period!

    Code:

    <img src="buzz.PNG" />
     
    <ol type="a">
    <li value="1">I'm not that lucky</li>
    </ol>

    <ol>
    <li value="2">We have smoke detectors</li>
    </ol>

    <ol type="A">
    <li value="4">We live on the most boring street in the United States of America; where nothing even remotely dangerous will ever happen. Period!</li>
    </ol>

    Where the type="" attribute sets the ordered marker style, with numbers as the default/inherent value:
    • 1 = Numbers: 1, 2, 3, 4, 5...
    • A = Capital letters: A, B, C, D, E...
    • a = Lowercase letters: a, b, c, d, e...
    • I = Roman numerals: I, II, III, IV, V...
    • i = Small Roman numerals: i, ii, iii, iv, v...
    The value="" attribute sets the starting position, with 1 as a default value. 

    Read more about these methods:

    Saturday, April 21, 2012

    HTML <button> vs <input type="button">

    <form name="frmTestingButtonTypes">
     <button>This is a button</button><br />
     <!-- Vs. -->
     <input type="button" value="This is a button">
    </form>

    HTML allows a developer to use JavaScripts to run custom functions and calculations in a simple, universal web interface.  This can be accomplished with only a little bit of experience with JavaScripting (and with some excellent guidance from w3schools.com).

    A problem I ran into recently (having plenty of HTML experience, and stolen only enough JavaScript code over the years to hack through and get by) was with some scuba calculators I recently began developing as HTML forms like this one:

    JavaScript scuba calculator utilizing onUpdate events

    I decided to omit a submit/command button and instead use onUpdate events to call the calculations so a user can convert from depth to pressure, or change the pressure and convert back to depth.  Also, this way is just cooler.

    The problem is that by adding name attributes in a <button> element inside of a <form>, the web page will want to reference any text boxes/drop down menus/check boxes/command buttons/etc. explicitly; so it will pass their values to the URL when any of those elements are applied:

    <form name="frmTestingButtonTypes">
     <button name="testButton">This is a button</button><br />
     <!-- Vs. -->
     <input name="testInput" type="button" value="This is a button">
    </form>

    Original URL remains the same when using onChange events

    Including a <button> tag passes control values as arguments to the URL
    when the first button is clicked

    Clicking the second button passes its value to the URL


    The URL examples above return two buttons would continue further if additional controls (text boxes/check boxes, etc.) on the page were populated with data.  Further, this has "navigated away" from the original blank version of the page which may require a user to click the browser's Back button to reset properly.

    Instead, use only the latter input tag method
    <input type="button" onClick="someFunction()" />
    and avoid using the button tags
    <button onclick="someFunction()">Name</button>so the arguments will not be passed to the URL.

    Additionally, avoid using the type="sumbit" in an <input> tag, which will give the same results as using <button> tags:
    <input type="submit" onClick="someFunction()" />

    Friday, August 12, 2011

    Connect to ArcMap layers and tables with VBA

    Example description:
    I am editing a coverage of stream segments (lines) and would like to log any updates to a non-spatial, standalone table in the geodatabase so I can keep track of the evolution of the dataset over time.  The application will first need to know which datasets to edit, so I start by adding  two combo boxes to the form that will be automatically populated with the two necessary types of data, named cboFlowingWatersLayer, and cboFlowingWatersUpdateTable, respectively.


    The first combo box will allow me to select any of the the spatial datasets (geodatabase coverages/feature classes/shapefiles/projected datasets/etc.) that are available in the Table of Contents pane:

    Map layers in an active ArcMap project

    The second combo box will select the non-spatial, standalone table (highlighted below) that is otherwise available under the Source tab in the Table of Contents pane.  There are two additional dummy tables that I added to this project that are not visible in the screenshot below, but you'll see them later.

    Non-spatial tables in an ArcMap project

    Coding:
    I add some code to populate the combo boxes with any available layers or standalone tables when the form activates.  There's a brief Setup section, then an If/Then statement will check to see if there is a layer already set in there.  If not, it'll clear it and populate the control with any spatial layers that are available.  If there is anything in there, it will run a separate function to check if it's the right layer.  I won't address that procedure here, so it's commented out below (though I recommend adding such a function). Let's get started with filling in the names of just the spatial datasets first:

    Private Sub UserForm_Activeate()
    'Setup
      Dim pMxDoc As IMxDocument
      Dim pMap As IMap

      Set pMxDoc = ThisDocument
     
    Set pMap = pMxDoc.FocusMap

    'Populate the first combo box with any available spatial
    ' layers that will show up in the Display tab in the
    ' ArcMap Table of Contents pane
      Dim i As Integer
      If cboFlowingWatersLayer.ListCount = 0 Then
          cboFlowingWatersLayer.Clear
          For i = 0 To pMap.LayerCount - 1
              Me.cboFlowingWatersLayer.Additem (pMap.Layer(i).Name)
          Next i
      Else
          'Call Me.FlowingWatersLayerCheck
      End If

    End Sub

    What should appear when the first combo box is selected are any layers that are available the Display tab of an ArcMap project.


    (Note that apps can only work with shapefiles, geodatabase coverages, etc. and not groups of data.  Data groups appear in this example as individual layers, but since they are not really spatial datasets, selecting them will cause an error at run time if they are selected and processed.)

    Next we'll add some more code to add any standalone tables that are in the project using the IStandaloneTableCollection interface:

    Private Sub UserForm_Activeate()
    'Setup
      Dim pMxDoc As IMxDocument
      Dim pMap As IMap
      Dim pSATCollection As IStandaloneTableCollection 

      Set pMxDoc = ThisDocument
     
    Set pMap = pMxDoc.FocusMap
     
    Set pSATCollection = pMxDoc.FocusMap

    'Populate the first combo box with any available spatial
    ' layers that will show up in the Display tab in the
    ' ArcMap Table of Contents pane
      Dim i As Integer
      If cboFlowingWatersLayer.ListCount = 0 Then
          cboFlowingWatersLayer.Clear
          For i = 0 To pMap.LayerCount - 1
              Me.cboFlowingWatersLayer.Additem (pMap.Layer(i).Name)
          Next i
      Else
          'Call Me.FlowingWatersLayerCheck
      End If

    'Populate the second combo box with any available non-spatial
    ' tables that will show up in the Source tab in the
    ' ArcMap Table of Contents pane
      Dim j As Integer
      If cboFlowingWatersUpdateTable.ListCount = 0 Then
          cboFlowingWatersUpdateTable.Clear
          For j = 0 To pSATCollection.StandaloneTableCount - 1
              Me.cboFlowingWatersUpdateTable.Additem _
                  (pSATCollection.StandaloneTable(j).Name)
          Next j
      Else
          'Call Me.FlowingWatersTableCheck
      End If

    End Sub

    Finally, this is what the second combo box will look like (with the additional two dummy datasets that were hidden from view in the screenshot above - they're named "Delete - Test 1" and "Delete - Test 2"):


    Referencing the selected layer/table:
    There are a virtually unlimited number of uses for mapping layers like this.  The idea is that the method above provides a heads-up interface to access the position of a given layer or table in the Table of Contents.  Think of the position as the dataset's number in line, starting at 0 instead of 1.  Take the five spatial "layers" that are available for example:

    Place in lineVB Position #Layer Name
    1st / Top
    2nd
    3rd
    4th
    5th / Bottom
    0
    1
    2
    3
    4
    "FlowingWaters layer"
    "New Group Layer"
    "Florida NHD"
    "SWFWMD_draft_primary_canals"
    "Reporting Units"

    Whenever you need to use a specific layer, the interface we built above will allow a quick way for Visual Basic to reference the position number of a selected layer.  Of course you will need some error checking and handling code to ensure that the layer position isn't changed (adding, removing, or moving the order of layers in the Table of Contents will affect each layer's position number).

    The following are a few examples on how to reference a layer's position number using the interface that we built above.

    Example 1 - Connect to a dataset:
    A working example follows, so don't worry about the function of the code yet.  This simply illustrates the structure of references needed to connect to a dataset.

    The previous sections explain that an ArcMap project is made of up layers and sometimes non-spatial tables.  Further, those layers and tables have position numbers associated with them that are usually just unimportant background information.  Well, now we will use those position numbers to tell a program where to target its procedures.

    After we choose a layer from the program interface, that combo box/pull down menu will store our selection as a number, which it refers to as its ListIndex.  Now if we want to know which layer or table we chose, we'll call it by referencing cboFlowingWatersLayer.ListIndex.

    In the example below, we are instantiating a new variable based off of the IFeatureLayer interface (again, don't worry about what's happening yet).  We will set that new variable, named pFeatureLayer, equal to a specific layer number (position number) in an ArcMap project so we can do some more work on it later.  Just pay attention to the way that the combo box position is referenced:

    Dim pMxDoc As IMxDocument 'Whatever
    Dim pFeatureLayer As IFeatureClass 'Slightly Important
    '...more code

    Set pMxDoc = ThisDocument 'Still not the point
    'Oh, here we go!
    Set pFeatureLayer = _
      pMxDoc.FocusMap.Layer(cboFlowingWatersLayer.ListIndex)
    '...more code


    Ok! This essentially told the function/sub routine that:
    1. We're working with this project (aka ThisDocument)
    2. We're looking for a specific feature layer (spatial dataset/shapefile/geodatabase coverage/etc.)
    3. That dataset of interest will be in a certain position when you focus the map; and that position number can be found by A) looking at the combo box (pull down menu named cboFlowingWatersLayer) and B) pulling its current ListIndex value.
    Got it.  Let's move on to a working example.

    Example 2 - Count the selected spatial features:
    Add two command buttons to the form, named cboLayerCount & cboTableCount, and change their captions to match the screenshot below

    Added two command buttons

    When a user clicks on one of these buttons, a message box will report how many records are selected in a layer or a table.  I'll add a quick error check at the beginning to make sure that a layer has been selected.  If a layer has not been selected yet, the ListIndex value will be -1. Here's the code:


    Private Sub cmdLayerCount_Click()
    'Error Checking
      If cboFlowingWatersLayer.ListIndex = -1 Then
          MsgBox "Please choose a layer to count."
          Exit Sub
      End If

    'Setup
      Dim pMxDoc As IMxDocument
      Dim pMap As IMap
      Dim pFS As IFeatureSelection
      Dim pSelectedFeatures As ISelectionSet

      Set pMxDoc = ThisDocument
      Set pMap = pMxDoc.FocusMap
      Set pFS = pMap.Layer(cboFlowingWatersLayer.ListIndex)
      Set pSelectedFeatures = pFS.SelectionSet 

    'Display a message box to report info
      If pSelectedFeatures.Count = 1 Then
        MsgBox "There is 1 feature selected."
      Else
        MsgBox "There are " & pSelectedFeatures.Count & _
            " features selected."
      End If

    End Sub

    Save this, run the code, select a few features and you should get something like this:


    Example 3 - Count the selected standalone table features
    Using the same GUI (graphic user interface) that was built in the previous example, apply the following code to the "Table Count" command button to count the number of selected records in a standalone table.  A very similar method will be used for this procedure, however we will need to use the ITableSelection inteface in place of the IFeatureSelection interface since we're working with a standalone table instead of a spatial dataset.  Further, I won't need to sort through any of the selected features in the standalone table in my larger project, so I'll leave out the Selection Set and count directly from my Table Selection:

    Private Sub cmdTableCount_Click()
    'Error Checking
      If cboFlowingWatersUpdateTable.ListIndex = -1 Then
          MsgBox "Please choose a layer to count."
          Exit Sub
      End If

    'Setup
      Dim pMxDoc As IMxDocument
      Dim pSATCollection As IStandAloneTableCollection
      Dim pTS As ITableSelection

      Set pMxDoc = ThisDocument
      Set pSATCollection = pMxDoc.FocusMap
    'This next bit must be on the a single line;
    '  the format of this blog makes coding difficult.
      Set pTS = pSATCollection.StandaloneTable(
           cboFlowingWatersUpdateTable.ListIndex)

    'Display a message box to report info
      If pTS.SelectionSet.Count = 1 Then  
          MsgBox "There is 1 feature selected."
      Else 
          MsgBox "There are " & pTS.SelectionSet.Count & _
              " features selected."
      End If

    End Sub

    Now, after you map a standalone table in the Flowing Waters Update Table combo box and click the Table Count command button, you will be able to count any selected records in the table, just like you would count the records in a spatial layer.