更改标记在地图上的位置

时间:2017-10-02 14:50:08

标签: android google-maps google-maps-api-3 google-maps-markers marker

我有一个MapsActivity类,它从地图上设置的固定点开始。我正在调用一个Thread,当返回为true时,Map只被完全加载。 (我将通过Web服务在数据库中搜索,它将返回我在地图上播放的Lat和Long值,并且该值将每15秒更改一次。)

我需要知道,如何在MapReady上改变Marker的位置。

遵循MapsActivity类

package com.example.patrickcamargo.myapplication.Maps;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;

public class MapsActivity extends SupportMapFragment implements     GoogleMap.OnMyLocationButtonClickListener, OnMapReadyCallback,
    ActivityCompat.OnRequestPermissionsResultCallback, GoogleMap.OnMapClickListener {

private GoogleMap mMap;
Marker marker;
LatLng latLng = new LatLng(-23.497444, -47.440722);
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private FusedLocationProviderClient mFusedLocationClient;
public Double latitude, longitude;

public ProgressDialog getProgress() {
    return progress;
}

public void setProgress(ProgressDialog progress) {
    this.progress = progress;
}

private ProgressDialog progress;

boolean teste = true;
boolean teste2 = true;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getMapAsync(this);

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());

    mFusedLocationClient.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if(location != null){
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                Toast toast = Toast.makeText(getContext(),"LAT:  " + location.getLatitude() + "LONG:  " + location.getLongitude(),Toast.LENGTH_LONG);
                toast.show();
            }
        }
    });

    //TESTE DE EVENTO

    progress = new ProgressDialog(getContext());
    progress.setMessage("AGUARDE ENQUANTO IDENTIFICAMOS O SERVIÇO...");
    progress.show();
    progress.setCanceledOnTouchOutside(false);
    ThreadCarregarChamado threadCarregarChamado = new ThreadCarregarChamado();
    threadCarregarChamado.setMapsActivity(this);
    threadCarregarChamado.start();

    //CRIADO UM LOOP INFINITO, PARA QUE SÓ SEJA CARREGADO O MAPA TOTALMENTE, QUANDO O RETORNO DO CHAMADO JÁ TIVER UM FUNCIONARIO DISPONIVEL
    //E TAMBEM VINCULADO COM ESSE CHAMADO QUE FOI ABERTO
    //ENQUANTO NÃO FOR VINCULADO UM FUNCIONARIO, NÃO IRA SER EXECUTADO DAQUI PRA FRENTE
    while (teste);
    //onMapReady(mMap);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    enableMyLocation();
    mMap = googleMap;
    mMap.setOnMapClickListener(this);
    // Add a marker in Sydney and move the camera
    marker = mMap.addMarker(new MarkerOptions()
            .position(latLng)
            .title("Testando")
            .snippet("Population: 776733"));
}


private void enableMyLocation() {
    if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        PermitirLocalizacao.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                android.Manifest.permission.ACCESS_FINE_LOCATION, true);
    } else if (mMap != null) {
        mMap.setMyLocationEnabled(true);//BOTÃO PARA MUDAR CAMERA PARA POSIÇÃO ATUAL}
        LatLng latLng = new LatLng(latitude, longitude);
        //mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); JOGA O ZOOM DIRETO NA POSIÇÃO ATUAL DO CLIENTE
        //mMap.animateCamera(CameraUpdateFactory.zoomTo(80));
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
        return;
    }

    if (PermitirLocalizacao.isPermissionGranted(permissions, grantResults,
            android.Manifest.permission.ACCESS_FINE_LOCATION)) {
        enableMyLocation();
    } else {
        //resume.mPermissionDenied = true;
    }
}

@Override
public boolean onMyLocationButtonClick() {
    return false;
}

@Override
public void onMapClick(LatLng latLng) {
    Toast toast = Toast.makeText(getContext(),"Coordenadas: " + latLng.toString(),Toast.LENGTH_LONG);
    toast.show();
}

public void MarcarGuincho()
{
    teste=false;
    marker.setPosition(new LatLng(-25.63356, -47.440722));
    //latLng = (-23.497444, -47.440722);

}
}

现在我的主题

package com.example.patrickcamargo.myapplication.Maps;

import android.app.ProgressDialog;
import android.content.Context;

import com.example.patrickcamargo.myapplication.Conexao;
import com.example.patrickcamargo.myapplication.ConexaoInterface;

import org.json.JSONException;

public class ThreadCarregarChamado extends Thread implements ConexaoInterface{
private ProgressDialog progress;
private Context context;

Conexao conexao;

public MapsActivity getMapsActivity() {
    return mapsActivity;
}

public void setMapsActivity(MapsActivity mapsActivity) {
    this.mapsActivity = mapsActivity;
}

private MapsActivity mapsActivity;

@Override
public void run() {
    //conexao = new Conexao(context, this, "ThreadCarregarChamado.java");
    //conexao.execute("teste.php?","");
    try {
        depoisDownload("OK");
        Thread.sleep(5000);
    } catch (JSONException e) {

    } catch (InterruptedException e) {

    }

}

public Context getContext() {
    return context;
}

public void setContext(Context context) {
    this.context = context;
}

@Override
public void depoisDownload(String result) throws JSONException {
    if(result.equals("FALSE\r"))
    {
        run();
    }
    else {
        mapsActivity.MarcarGuincho();
        ProgressDialog progress;
        progress = mapsActivity.getProgress();
        progress.dismiss();
        mapsActivity.setProgress(progress);
    }
}
}

在MarcarGuincho课程中,这是我需要更改上面标记集位置的地方,但是它给我的空白,所以这给出了错误......

此行中的错误

marker.setPosition(new LatLng(-25.63356, -47.440722));

logcat的

10-02 13:29:43.628 29584-30901/com.example.patrickcamargo.myapplication E/AndroidRuntime: FATAL EXCEPTION: Thread-240709
Process: com.example.patrickcamargo.myapplication, PID: 29584
com.google.maps.api.android.lib6.common.apiexception.c: Not on the main thread
at com.google.maps.api.android.lib6.common.k.b(:com.google.android.gms.DynamiteModulesB@11517436:11)
at com.google.maps.api.android.lib6.common.p.a(:com.google.android.gms.DynamiteModulesB@11517436:5)
at com.google.maps.api.android.lib6.impl.cz.c(:com.google.android.gms.DynamiteModulesB@11517436:176)
at com.google.android.gms.maps.model.internal.q.onTransact(:com.google.android.gms.DynamiteModulesB@11517436:18)
at android.os.Binder.transact(Binder.java:387)
at com.google.android.gms.internal.zzed.zza(Unknown Source)
at com.google.android.gms.maps.model.internal.zzr.getPosition(Unknown Source)
at com.google.android.gms.maps.model.Marker.getPosition(Unknown Source)
at com.example.patrickcamargo.myapplication.Maps.MapsActivity.MarcarGuincho(MapsActivity.java:148)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.depoisDownload(ThreadCarregarChamado.java:55)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.run(ThreadCarregarChamado.java:30)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.depoisDownload(ThreadCarregarChamado.java:60)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.run(ThreadCarregarChamado.java:30)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.depoisDownload(ThreadCarregarChamado.java:60)
at com.example.patrickcamargo.myapplication.Maps.ThreadCarregarChamado.run(ThreadCarregarChamado.java:30)
Line 148 = marker.remove();

1 个答案:

答案 0 :(得分:0)

尝试使用

    teste = false;
    LatLng latLng1 = new LatLng(-25.63356, -47.440722);
    if(marker != null)
    {
    marker.remove();
    marker = mMap.addMarker(new MarkerOptions()
                .position(latLng1)
                .title("Testando")
                .snippet("Population: 776733"));
    }