;; CADLisp Tools - Station/Chainage Along Polyline
(vl-load-com)

(defun ct-ch:supported-polyline-p (data / flags)
  (and data
       (or (= (cdr (assoc 0 data)) "LWPOLYLINE")
           (and (= (cdr (assoc 0 data)) "POLYLINE")
                (setq flags (cdr (assoc 70 data)))
                (= 0 (logand flags 80))))))

(defun c:CHAINAGE (/ data distance ent nearest pick point)
  (cond
    ((null (setq pick (entsel "\nPick a polyline: ")))
      (prompt "\nNo polyline selected."))
    ((not (ct-ch:supported-polyline-p
            (setq data (entget (setq ent (car pick))))))
      (prompt "\nThe selected object is not a supported polyline."))
    ((null (setq point (getpoint "\nPick station location: ")))
      (prompt "\nNo station point supplied."))
    ((vl-catch-all-error-p
       (setq nearest
         (vl-catch-all-apply 'vlax-curve-getClosestPointTo
           (list ent (trans point 1 0)))))
      (prompt "\nThe closest point could not be calculated."))
    ((vl-catch-all-error-p
       (setq distance
         (vl-catch-all-apply 'vlax-curve-getDistAtPoint (list ent nearest))))
      (prompt "\nThe chainage could not be calculated."))
    (T
      (prompt (strcat "\nDistance along from polyline start: " (rtos distance 2 3)))))
  (princ))
