Changing position of a Marker

0

I have a MapsActivity Class, where it starts at a fixed point set on the map. I'm calling a Thread, where Map is only fully loaded, when the return is true. (I will do a search on a DB through the Web Service where it will return me Lat and Long values to play on the map, and that value will be changed every 15 seconds.)

I needed to know how do I change the position of a Marker outside the onMapReady class.

Follow the MapsActivity class

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);

}
}

Now my Thread

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);
    }
}
}

In the Mark Guincho class, this is where I need to change the position of the marker set above, but it is giving null to me, so this is giving error .. .

Error on this line

marker.setPosition(new LatLng(-25.63356, -47.440722));
    
asked by anonymous 01.10.2017 / 18:34

1 answer

0

I do not know if I understood your question correctly, but if you're looking at how to update the position of a marker on the map from time to time, I am sending below as an example, part of a code that moves the marker to its current location, rate defined in the onLocationChanged settings (I did not show the code that enables LocationServices.API)

private Marker MarcadorVoceEstaAqui;

public void onLocationChanged(Location location) {
    CarregaMarcPosAtual(location);
}

private void CarregaMarcPosAtual(Location location) {
    if (location != null) {
        if (MarcadorVoceEstaAqui != null) {MarcadorVoceEstaAqui.remove();}

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Você está aqui!");
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_directions_car_black_24dp));
        MarcadorVoceEstaAqui = mMap.addMarker(markerOptions);

        // Se preferir também podes mover a camera para o novo local do marcador
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
    }
}
    
13.12.2017 / 01:08