How do I determine which Locator is selected in a LocatorPane with multiple Locators?
Does this work for you?
DynamicModule[
{pts = Array[pt, 5], active},
Column@{
Dynamic@active,
Dynamic@pts,
LocatorPane[
Dynamic[
pts,
{
(active = First@FirstPosition[pts - #, _?(# != {0, 0} &)]; pts = #)&,
(active = None) &
}
],
Graphics[{Yellow, Disk[{0, 0}, 2]}, PlotRange -> 2]
]
}
]
This simply finds the currently updating point by checking which value has changed.
Update
Seeing @user6014's solution, I thought I'd point out some issues I see with both apporaches:
- My approach fails if you don't actually change the position of the locator (you can do this by clicking once to get the locator directly under your cursor and then clicking again without moving the mouse)
- @user6014's approach fails if you manage to put two locators on top of each other (or at least it might not find the correct locator)
You may use MousePosition
set to the "Graphics"
of the LocatorPane
with Nearest
.
pts = {{1, 1}/2, {-1, 1}/2, {1, -1}/2};
selectedLocator = None;
LocatorPane[
Dynamic[pts,
{
(selectedLocator =
FirstPosition[pts, First@Nearest[pts, MousePosition[{"Graphics", LocatorPane}]]]) &,
Automatic,
None
}],
Graphics[{Yellow, Disk[{0, 0}, 2]}, PlotRange -> 2],
LocatorAutoCreate -> True
]
Dynamic[selectedLocator]
When the LocatorPane
beings to update locator the MousePosition
in the pane's "Graphics"
coordinates will be used to calculate the index of the nearest locator in pts
and store this position in selectedLocator
. This calculation only occurs at the start of updating a locator which reduces the load on the system.
With LocatorAutoCreate
set to True
additional locators can be added by holding Alt and clicking on the LocatorPane
.
selectedLocator
can be set to None
in the third item of the second parameter of Dynamic
if needed; (selectedLocator = None)&
.
Hope this helps.
Does this work for you?
DynamicModule[{pts = {{-1, 1}/2, {1, 1}/2}, a = False,
pointNames = Table["Point " <> ToString@i, {i, 10}]},
EventHandler[
{LocatorPane[Dynamic[pts], Framed@Graphics[{}],
LocatorAutoCreate -> True], Dynamic[a]}
,
{"MouseUp" :> {a = "Null"},
"MouseDragged" :> {a =
pointNames[[Position[pts,
Nearest[pts, MousePosition["Graphics"]][[1]]][[1, 1]]]]}}
, PassEventsDown -> True]
]
This simply finds the point closest to your current mouse position when pressed down.
Use Alt+Click to create new locators.