Thanks a lot hippe013
This code helped me a lot. The thing that went wrong with it at first, was that an offset can return a negative number, so this meant that it was marked as smaller than minOffset.
The code I wrote -based on your code- in C# works as a charm:
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using Autodesk.Civil;
using Autodesk.Civil.ApplicationServices;
using Autodesk.Civil.DatabaseServices;
using StationTools;
using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;
[assembly: CommandClass(typeof(Commands))]
namespace StationTools
{
class Commands
{
[CommandMethod("PointToStation")]
public void PointToStation()
{
Document doc = AcadApp.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = AcadApp.DocumentManager.MdiActiveDocument.Editor;
PromptPointResult pPtRes;
PromptPointOptions pPtOpts = new PromptPointOptions("");
pPtOpts.Message = "\nSelect point: ";
pPtRes = doc.Editor.GetPoint(pPtOpts);
Point3d ptSelected = pPtRes.Value;
var result = GetClosestAlignment(ptSelected);
ed.WriteMessage("\nAlignment name: " + result.Item1);
ed.WriteMessage("\nStation: " + result.Item2);
}
public (string,double) GetClosestAlignment (Point3d point)
{
Document doc = AcadApp.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
double offset = double.NaN;
double station = double.NaN;
double minOffset = double.MaxValue;
double minStation = double.MinValue;
string AlignName = "";
using (Transaction tr = db.TransactionManager.StartTransaction())
{
CivilDocument civDoc = CivilApplication.ActiveDocument;
ObjectIdCollection alignColl = civDoc.GetAlignmentIds();
foreach (ObjectId AlignId in alignColl)
{
Alignment align = (Alignment)tr.GetObject(AlignId, OpenMode.ForRead);
try
{
if (align.AlignmentType == AlignmentType.Rail)
{
align.StationOffset(point.X, point.Y, ref station, ref offset);
if (Math.Abs(offset) < minOffset)
{
minOffset = Math.Abs(offset);
minStation = station;
AlignName = align.Name;
}
}
}
catch
{
PointNotOnEntityException exception = new PointNotOnEntityException();
}
}
tr.Commit();
}
return (AlignName, minStation);
}
}
}