简体   繁体   中英

Update Google Maps after a while when camera stopped moving

I still don't believe I couldn't find any question on SO, so please feel free to point me to one.

I'm implementing an application using Google Maps that shows several markers. I want to make it dynamic so that only seen markers are drawn. For this, I want to be able to know when the map is completely stopped, then wait a couple of seconds so I dont mess around with the map while the user might still be moving it, and then clear markers and draw the new ones. If the user moves before the timer fires it has to cancel and then start counting once again.

So far, I managed to get the camera change to fire when the animation is stopped using onCameraChangeListener , though it's definition specifies that this might still get called in mid animation. Is this the right way to do it?

Second question is regarding timers. My current implementation is as follows:

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

And the Timer that actually updates the necessary markers is this one:

class refreshMapData extends TimerTask{

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

Which obviously throws a "Not on the main thread" exception and leads me to the next question: What is the workaround for this issue? How can I modify Google Map's values using a timer if I'm not allowed to do it from outside the main thread?

Edit: About the first question, I'm guessing I just need to compare if the position has changed since the last time so that will do. Just need the answer to the timer updating issue.

You would be better off using Handler . This doesn't create additional threads, which are not necessary.

Just call this in onCameraChange:

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

and in handleMessage do your work.

Why would you need it dynamic if you show only several markers? Markers outside visible region are not making is much slower. Your code that clears and adds markers may make it slower.

If you were to show thousands of markers, try Android Maps Extensions , which has adding only visible markers built in.

I don't know if you keep needing a good solution, but I found this question and think could help. It help me, the guy wrote a blog post explaining how to use cluster manager and how to set up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM