How do I update google map marker position in a separate thread in android

4.5k views Asked by At

I am trying to update a google map marker position in a separate thread. I can update the marker fine in the main thread, but as soon as I try it in a separate thread, the app crashes.

Logcat:

06-10 12:35:37.107: E/AndroidRuntime(25915): FATAL EXCEPTION: Thread-2909
06-10 12:35:37.107: E/AndroidRuntime(25915): java.lang.IllegalStateException: Not on the main thread
06-10 12:35:37.107: E/AndroidRuntime(25915):    at com.google.l.a.ce.b(Unknown Source)
06-10 12:35:37.107: E/AndroidRuntime(25915):    at com.google.maps.api.android.lib6.d.ct.a(Unknown Source)
06-10 12:35:37.107: E/AndroidRuntime(25915):    at com.google.maps.api.android.lib6.d.aq.a(Unknown Source)
06-10 12:35:37.107: E/AndroidRuntime(25915):    at com.google.android.gms.maps.model.internal.t.onTransact(SourceFile:73)
06-10 12:35:37.107: E/AndroidRuntime(25915):    at android.os.Binder.transact(Binder.java:380)
06-10 12:35:37.107: E/AndroidRuntime(25915):    at com.google.android.gms.maps.model.internal.zzi$zza$zza.setPosition(Unknown Source)
06-10 12:35:37.107: E/AndroidRuntime(25915):    at com.google.android.gms.maps.model.Marker.setPosition(Unknown Source)

and the thread:

new Thread(new Runnable() {
    Marker mkr = marker;
    public void run(){
        double lng = 78.486671;
        double lat = 17.385044;
        mkr.setPosition(new LatLng(lat, lng));
    }
}).start();
1

There are 1 answers

0
Daniel Nugent On

You could use runOnUiThread() in order to modify the Marker position inside your worker thread, for an example see here.

In your case it would be something like this:

    new Thread(new Runnable() {
        Marker mkr = marker;
        public void run(){

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    double lng = 78.486671;
                    double lat = 17.385044;
                    mkr.setPosition(new LatLng(lat, lng));
                }
            });

        }
    }).start();