开发者

What's the correct way to determine when a MapView's Lat/Lon window has changed?

I'm developing an Android application that uses开发者_高级运维 a MapView. I'd like to run a procedure whenever the visible portion of the map changes (due to zooming/panning/rotating the phone/etc), and I'd like to pass the new latitude and longitude values to the procedure.

I thought I could override onInterceptTouchEvent to do this, but then the procedure only seems to run when you first touch the screen (so, for example, panning by dragging your finger only calls the procedure at the beginning of the dragging motion). Which means the procedure is never called with the new coordinates.

So -- what's the correct way to do it?


You probably have to combine several techniques to achieve what you want.

To catch the panning, I'd try overriding your MapViews onTouchEvent(), or maybe dispatchTouchEvent(), and listen for the MotionEvent.ACTION_UP event. This is triggered when the user lifts his finger from the screen:

public boolean onTouchEvent(MotionEvent event) {
  if (event.getAction()==MotionEvent.ACTION_UP) {
    // Call your procedure here
  }

  return super.onTouchEvent(ev);
}

If you wanted to call your procedure during the panning, I think you'd have to look for the panning motion overriding one of the two same methods. Something like this:

public boolean onTouchEvent(MotionEvent event) {
  if (event.getAction() == MotionEvent.ACTION_MOVE) {
    if (event.getHistorySize() < 1)
      return; // First call, no history

    // Get difference in position since previous move event
    float diffX = event.getX() - event.getHistoricalX(event.getHistorySize() - 1);
    float diffY = event.getY() - event.getHistoricalY(event.getHistorySize() - 1);

    if (Math.abs(diffX) > 0.5f || Math.abs(diffY) > 0.5f) {
      /* Position has changed substantially, so this is probably a drag action. 
         Call your procedure here. */
    }
  }
}

To detect a change in zoom level you can override dispatchDraw:

int oldZoomLevel=-1;

public void dispatchDraw(Canvas canvas) {
  super.dispatchDraw(canvas);

  if (getZoomLevel() != oldZoomLevel) {
    // Call your procedure here

    oldZoomLevel = getZoomLevel();
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜