2010-09-08 3 views
6

В настоящее время я разрабатываю приложение с SDK Andoid Maps.Android Maps get Scroll Event

Теперь я хотел бы получить уведомление, если пользователь прокручивает карту для загрузки дополнительных маркеров с сервера на основе нового центра карты.

Я уже искал функцию регистрации слушателя, но я ничего не нашел.

Есть ли способ узнать о изменениях в центре карты? Я не хочу, чтобы реализовать механизм опроса для этого ... :(

ответ

1

Я сделал это двумя способами:..

сенсорный слушателем Переведите на ощупь слушателя для просмотра карты Каждый раз, пользователь поднимает палец (или движется, или приземляется), вы можете перезагрузить.

mapView.setOnTouchListener(new OnTouchListener() { 

    public boolean onTouch(View v, MotionEvent event) { 
     switch (event.getAction()) { 
     case MotionEvent.ACTION_UP: 
      // The user took their finger off the map, 
      // they probably just moved it to a new place. 
      break; 
      case MotionEvent.ACTION_MOVE: 
      // The user is probably moving the map. 
      break; 
     } 

     // Return false so that the map still moves. 
     return false; 
    } 
}); 

Override OnLayout. Каждый раз, когда карта перемещается, OnLayout называется. Если расширить класс MAPview, вы можете переопределить onLayout, чтобы поймать это событие. Я установил здесь таймер, чтобы посмотреть, будет ли movem он остановился.

public class ExtendedMapView extends MapView { 
    private static final long STOP_TIMER_DELAY = 1500; // 1.5 seconds 
    private ScheduledThreadPoolExecutor mExecutor; 
    private OnMoveListener mOnMoveListener; 
    private Future mStoppedMovingFuture; 

    /** 
    * Creates a new extended map view. 
    * Make sure to override the other constructors if you plan to use them. 
    */ 
    public ExtendedMapView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     mExecutor = new ScheduledThreadPoolExecutor(1); 
    } 

    public interface OnMoveListener { 
     /** 
     * Notifies that the map has moved. 
     * If the map is moving, this will be called frequently, so don't spend 
     * too much time in this function. If the stopped variable is true, 
     * then the map has stopped moving. This may be useful if you want to 
     * refresh the map when the map moves, but not with every little movement. 
     * 
     * @param mapView the map that moved 
     * @param center the new center of the map 
     * @param stopped true if the map is no longer moving 
     */ 
     public void onMove(MapView mapView, GeoPoint center, boolean stopped); 
    } 

    @Override 
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 
     super.onLayout(changed, left, top, right, bottom); 

     if (mOnMoveListener != null) { 
      // Inform the listener that the map has moved. 
      mOnMoveListener.onMove(this, getMapCenter(), false); 

      // We also want to notify the listener when the map stops moving. 
      // Every time the map moves, reset the timer. If the timer ever completes, 
      // then we know that the map has stopped moving. 
      if (mStoppedMovingFuture != null) { 
       mStoppedMovingFuture.cancel(false); 
      } 
      mStoppedMovingFuture = mExecutor.schedule(onMoveStop, STOP_TIMER_DELAY, 
        TimeUnit.MILLISECONDS); 
     } 
    } 

    /** 
    * This is run when we have stopped moving the map. 
    */ 
    private Runnable onMoveStop = new Runnable() { 
     public void run() { 
      if (mOnMoveListener != null) { 
       mOnMoveListener.onMove(ExtendedMapView.this, getMapCenter(), true); 
      } 
     } 
    }; 
} 

Вы также можете использовать таймер в методе приемника касания. Это был просто пример. Надеюсь, это поможет!

+0

впустую так много времени на this.None метода работ. downvote является обязательным. – Nezam

1

Взгляните на следующем блоге (поставляется с Github кодом): http://bricolsoftconsulting.com/extending-mapview-to-add-a-change-event/

+0

не работает –

+0

Он действительно работает - для многих людей - как вы можете видеть из комментариев на этой странице. Он может не работать для вас, в зависимости от вашей ОС Android и/или устройства. Но оставляя смутный комментарий и давая мне нисходящее движение, никому не поможет. Как насчет участия в конструктивном разговоре здесь и сообщить нам, какое устройство и какая версия Android вы используете? – Theo

+0

Я использую Galaxy Nexus 4.1 и Galaxy Note 10.1 на 4.0, компонент редко меняет событие изменения вообще. Требуется много времени и прокрутки до тех пор, пока оно не выдает первое событие изменения, а затем перестает работать. Гораздо надежнее обращаться с прослушивателем событий прикосновения из стандартного MapView. Так что это не сработает, мои пользователи не привязаны к одному устройству, на котором тестировался автор. –