在 MATLAB 上使用 ginput 命令无需单击绘图即可获取位置

Getting positions without clicking on plot with ginput command on MATLAB

我正在尝试使用 ginput 命令在以下地图上获取位置。但问题是我想在点击之前查看点的位置。

这可能吗? 单击 N 个点后,我可以看到位置,但我不能再单击它们了。我应该先看到这个位置,然后我需要点击它。

提前致谢!

这是代码:

clc
clear
close all
geoaxes('Units','normalized');
N=5;
set (gcf, 'WindowButtonMotionFcn', @mouseMove);

for i=1:N

[lat,lon]=ginput(1)
hold on
geolimits('manual')
geoscatter(lat,lon,'filled','b')
end

set (gcf, 'WindowButtonMotionFcn', @mouseMove);

function mouseMove (object, eventdata)
C = get (gcf, 'CurrentPoint');
title(gca, ['(X,Y) = (', num2str(C(1,1)), ', ',num2str(C(1,2)), ')']);
end

如果你有映射工具箱,我认为你可以使用gcpmap来简化这个。

主要问题只需要在回调函数中添加一个drawnow。然后我使用 waitforbuttonpressCurrentPoint 来获取点击的位置,而不是 ginput

h = geoaxes('Units','normalized');
geolimits('manual')
set (gcf, 'WindowButtonMotionFcn', @(x,y) mouseMove(x,y,h));
hold on

N=5;
for i=1:N
    waitforbuttonpress;
    pt = h.CurrentPoint;
    lat = pt(1,1);
    lon = pt(1,2);
    geoscatter(lat,lon,'filled','b')
end
hold off


function mouseMove (~, ~, handle)
C = handle.CurrentPoint;
title(gca, ['(X,Y) = (', num2str(C(1,1)), ', ',num2str(C(1,2)), ')']);
drawnow
end

你遇到的问题是 ginput 函数暂时覆盖了一些回调,解决这个问题的一种方法是使用 listener 来监听轴上的鼠标按下,

function myFunction
    % create a figure and an axes
    f = figure;
    ax = axes( 'parent', f );

    % give the axes a title
    t = title ( ax, '');
    % add a callback to update the title when the mouse is moving
    f.WindowButtonMotionFcn = @(a,b)updateTitle ( ax, t );
    % add a listener to the user clicking on the mouse
    addlistener ( ax, 'Hit', @(a,b)mousePress ( ax, t ) )
end
function updateTitle ( ax, t, str )
  % this function updates the title
  % 2 input args is from the mouse moving, the 3rd is only passed in
  %   when the mouoe button is pressed
  if nargin == 2; str = ''; end
  % get the current point of the axes
  cp  = ax.CurrentPoint(1,1:2);
  % check to see if its in the axes limits
  if cp(1) > ax.XLim(1) && cp(1) < ax.XLim(2) && ...
      cp(2) > ax.YLim(1) && cp(2) < ax.YLim(2)
    % update the string
    t.String = sprintf ( '%f,%f %s', cp, str );
  else
    % if ourside the limits tell the user
    t.String = 'Outside Axes';
  end
end
% this function is run when the mouse is pressed
function mousePress ( ax, t )
  updateTitle ( ax, t, '- Button Pressed' );
end

这将需要对您的代码进行一些重构,但这是一种强大的方法,并且可以向您介绍听众。

鼠标移动时的图像:

按下鼠标时的图像: