Java – The camera stops moving for a while after updating Google Maps

The camera stops moving for a while after updating Google Maps… here is a solution to the problem.

The camera stops moving for a while after updating Google Maps

I

still don’t believe I can’t find any issues on SO, so feel free to point out one.

I’m using Google map to implement an application that displays multiple tags. I want to make it dynamic so that only visible markers are drawn. To do this, I want to be able to know when the map stops completely, and then wait a few seconds so I don’t mess with the map when the user might still be moving it, and then clear the marker and draw a new one. If the user moves before the timer is triggered, the timer must be canceled and then start counting again.

So far I’ve managed to trigger a camera change when I stop the animation using onCameraChangeListener, though it’s definition specifies that this may still be called mid-animation. Is this the right thing to do?

The second question is about timers. My current implementation is as follows:

map.setOnCameraChangeListener(new OnCameraChangeListener() {
    public void onCameraChange(CameraPosition position) {
        refresher.schedule(new refreshMapData(), 2000);
    }
});

The timer that really updates the necessary flags is this:

class refreshMapData extends TimerTask{

public void run() {
        map.clear();
        for ( ... ) {
            map.addMarker( ... );
        }
    }
}

This obviously throws a “not on the main thread” exception and brings me to the next question: what is the workaround for this problem? If I am not allowed to do this from outside the main thread, how can I modify the value of Google map using the timer?

EDIT: Regarding the first question, I guess I just need to compare if the position has changed since the last time, so that’s it. Only the timer needs to update the answer to the question.

Solution

You’re better off using Handler. This does not create unnecessary extra threads.

Just call it in onCameraChange:

handler.removeMessages(MSG_ID);
handler.sendEmptyMessageDelayed(MSG_ID, 2000);

In handleMessage Do your job.

If only a few markers are displayed, why do you need it to be dynamic? Markers outside the visible area don’t slow things down much. The code that you clear and add tags can slow things down.

If you want to display thousands of tags, try Android Maps Extensions, which only adds built-in visible tags.

Related Problems and Solutions