change marker icon with contextual menu

0

I am developing an application in android studio. I have a map with several markers that I generate as shown in the image, when I click on the inforwindows I get a contextual menu with several options what I need is to choose an option the markador where I am pocicionado change of bone icon if I choose delivered I want the markador to change to green and so it depends on the option I choose to change color.

This is the code I'm using

    public boolean onContextItemSelected(MenuItem item) {
    String id = "";
    id = TituloGlobal.substring(0, TituloGlobal.indexOf(" -"));
    switch (item.getItemId()){
        case R.id.meEntregado:
            guardarDatosCliente(id, "0", "3");


            break;
        case R.id.meParcial:
            guardarDatosCliente(id, "2", "4");
            mMap.

            break;
        case R.id.meCTotal:
            guardarDatosCliente(id, "1", "4");
            break;
        case R.id.meNPlata:
            guardarDatosCliente(id, "1", "5");
            break;
        case R.id.meRParcial:
            guardarDatosCliente(id, "2", "5");
            break;
        case R.id.meNSalio:
            guardarDatosCliente(id, "3", "5");
            break;
        case R.id.meNalcanzar:
            guardarDatosCliente(id, "4", "5");
            break;
    }


    return super.onContextItemSelected(item);
}

I am new in this programming language, I hope you can help me and thanks in advance.

package com.example.framac.app_framac;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
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.CameraPosition;
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.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.List;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.client.RedirectException;
import static android.R.attr.breadCrumbTitle;
import static android.R.attr.mode;
public class MostrarMapa extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    public String TituloGlobal, pList ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mostrar_mapa);
        to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }
    @Override
    public void onMapReady(final GoogleMap googleMap) {
        mMap = googleMap;
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        pList = extras.getString("PLIST");
        ObtDatos(pList);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {

        }

        googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                return false;
            }
        });

googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                TituloGlobal = marker.getTitle();
                registerForContextMenu(findViewById(R.id.map));
                openContextMenu(findViewById(R.id.map));

            }
        });

googleMap.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener()  {

            @Override
            public void onInfoWindowClose(Marker marker) {


            }
        });


    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getMenuInflater().inflate(R.menu.menu_mapa, menu);

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        String id = "";
        id = TituloGlobal.substring(0, TituloGlobal.indexOf(" -"));
        switch (item.getItemId()){
            case R.id.meEntregado:
                guardarDatosCliente(id, "0", "3");

                //setMarkerDrawableEjecucion("funcion", R.drawable.entregado);
                break;
            case R.id.meParcial:
                guardarDatosCliente(id, "2", "4");


                break;
            case R.id.meCTotal:
                guardarDatosCliente(id, "1", "4");
                break;
            case R.id.meNPlata:
                guardarDatosCliente(id, "1", "5");
                break;
            case R.id.meRParcial:
                guardarDatosCliente(id, "2", "5");
                break;
            case R.id.meNSalio:
                guardarDatosCliente(id, "3", "5");
                break;
            case R.id.meNalcanzar:
                guardarDatosCliente(id, "4", "5");
                break;
        }


        return super.onContextItemSelected(item);
    }

    public Bitmap setMarkerDrawable(String dato) {
        int background = R.drawable.textonegocio;
String datoC = "";
        if (dato.length() > 25){
            datoC = dato.substring(0, 25);
        }else{
            datoC = dato;
        }

        Bitmap icon = drawTextToBitmap(background, String.valueOf(datoC));

        return icon;
    }

    public Bitmap setMarkerDrawable2(String dato) {
        int background = R.drawable.textocasa;

      String datoC = "";



        if (dato.length() > 25){
            datoC = dato.substring(0, 25);

        }else{
            datoC = dato;
        }

        Bitmap icon = drawTextToBitmap(background, String.valueOf(datoC));

        return icon;
    }

    public Bitmap drawTextToBitmap(int gResId, String gText) {

        Resources resources = getResources();
        float scale = resources.getDisplayMetrics().density;
        Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);
        android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();

        if (bitmapConfig == null) {
            bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
        }
        bitmap = bitmap.copy(bitmapConfig, true);
        Canvas canvas = new Canvas(bitmap);

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.rgb(255, 255, 255));
        paint.setTextSize((int) (8 * scale));
        paint.setShadowLayer(1f, 0f, 1f, Color.BLACK);
        Rect bounds = new Rect();
        paint.getTextBounds(gText, 0, gText.length(), bounds);
        int x = (bitmap.getWidth() - bounds.width()) / 2;
        int y = (bitmap.getHeight() + bounds.height()) / 2;
        canvas.drawText(gText, x, y-15, paint);

        return bitmap;
    }


    public void CargarLista(ArrayList<String> datos) {
        double lat = 0, lon = 0, latD = 0, lonD = 0;
        String CodigoCliente = "", NombreCliente = "", RefCliente = "", telefonos = "", Op = "";

        for (int i = 0; i < datos.size(); i++) {
            String dato = datos.get(i).toString();

            try {
                CodigoCliente = String.valueOf(dato.substring(0, dato.indexOf("@")));
                NombreCliente = String.valueOf(dato.substring(dato.indexOf("@") + 1, dato.indexOf("$")));
                lat = Float.valueOf(dato.substring(dato.indexOf("$") + 1, dato.indexOf("%")));
                lon = Float.valueOf(dato.substring(dato.indexOf("%") + 1, dato.indexOf("&")));
                //RefCliente = String.valueOf(dato.substring(dato.indexOf("&") + 1, dato.indexOf("*")));
                telefonos = String.valueOf(dato.substring(dato.indexOf("&") + 1, dato.indexOf("#")));
                Op = String.valueOf(dato.substring(dato.indexOf("#") + 1, dato.length()));

                //datos.get(0).equals("false")
                if (Op.equals("1")) {
                    Marker marcador = mMap.addMarker(new MarkerOptions()
                            .position(new LatLng(lat, lon))
                            .title(String.valueOf(NombreCliente))
                            .icon(BitmapDescriptorFactory.fromBitmap(setMarkerDrawable(NombreCliente)))
                            .snippet(RefCliente + " Cel: " + telefonos)

                    );

                }

                if (Op.equals("2")) {
                    Marker marcador = mMap.addMarker(new MarkerOptions()
                            .position(new LatLng(lat, lon))
                            .title(String.valueOf(NombreCliente))
                            .icon(BitmapDescriptorFactory.fromBitmap(setMarkerDrawable2(NombreCliente)))
                            .snippet(RefCliente + " Cel: " + telefonos)
                    );


                }


            } catch (ArrayIndexOutOfBoundsException excepcion) {
                lat = 0;
                lon = 0;

            }
            if ((lat != 0) && (lon != 0)) {
                latD = lat;
                lonD = lon;

            }
            //marcador.showInfoWindow();
        }
        CameraPosition camPos = new CameraPosition.Builder()
                .target(new LatLng(latD, lonD))   //Centramos el mapa en Madrid
                .zoom(15)         //Establecemos el zoom en 19
                .bearing(45)      //Establecemos la orientación con el noreste arriba
                .build();

        CameraUpdate camUpd3 =
                CameraUpdateFactory.newCameraPosition(camPos);
        mMap.animateCamera(camUpd3);

    }


    public void ObtDatos(String codigo){
        AsyncHttpClient client = new AsyncHttpClient();
        String url = "http://www.framac.com.bo/webservice/pListBuscarE.php";

        RequestParams parametros = new RequestParams();
        //parametros.put("codigo", 131);

        parametros.put ("codigo", codigo);
        //parametros.put ("dia", 2);

        client.post(url, parametros, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200){
                    CargarLista(ObtDatosJason(new String (responseBody)));
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });

    }

    public void onInfoWindowClick(Marker marcador) {
        Toast.makeText(this, "Info window clicked",
                Toast.LENGTH_SHORT).show();
    }

    public ArrayList<String> ObtDatosJason(String response){
        ArrayList<String> listado = new ArrayList<String>();
        try{
            JSONArray jsonArray = new JSONArray(response);
            String texto;
            for (int i=0;i<jsonArray.length();i++){
                texto = jsonArray.getJSONObject(i).getString("codigo")+ '@'+
                        jsonArray.getJSONObject(i).getString("cliente")+ '$'+
                        jsonArray.getJSONObject(i).getString("latitud")+ '%'+
                        jsonArray.getJSONObject(i).getString("longitud") + '&' +
                        //jsonArray.getJSONObject(i).getString("referencia") + '*' +
                        jsonArray.getJSONObject(i).getString("telefonos") + '#' +
                        jsonArray.getJSONObject(i).getString("entrega");


                listado.add(texto);
            }


        }catch (Exception e){
            e.printStackTrace();
        }

        return  listado;
    }

    public void guardarDatosCliente(String cod, String op, String Entrega ) {

        AsyncHttpClient client = new AsyncHttpClient();
        String url = "http://www.framac.com.bo/webservice/guardarDatosPlist.php";

        RequestParams parametros = new RequestParams();


        parametros.put("id", cod);
        parametros.put("opcion", op);
        parametros.put("entrega", Entrega);
        parametros.put("Lat", "0");
        parametros.put("Lon", "0");


        client.post(url, parametros, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    Toast toast1 = Toast.makeText(getApplicationContext(), "Los datos se guardaron correctamente", Toast.LENGTH_SHORT);
                    toast1.setGravity(Gravity.CENTER, 0, 0);
                    toast1.show();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast toast1 = Toast.makeText(getApplicationContext(), "Existe error en la coneccion con el servidor intente mas tarde", Toast.LENGTH_SHORT);
                toast1.setGravity(Gravity.CENTER, 0, 0);
                toast1.show();
            }
        });
    }

    public void cambiarIcono(Marker marker){
        //marker.
        marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
    }
}

This is the whole code of my application

    
asked by Marcelo 18.06.2018 в 17:47
source

1 answer

0

What you need to change the color marker is the following line

marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));

where HUE_BLUE is one of the colors you can use. You can see the list here and market is the instance on marker that you used for that specific marker.

To save the marker reference, you can create an array with all the markers once you add them to the map, something like this:

private ArrayList<Marker> mMarcadores;

mMarcadores.add(mGoogleMap.addMarker(new MarkerOptions()....);

You can use the setOnMarkerClickListener , and that's where you can receive the marker you're using. For what you put in the comments, you are using the setOnInfoWindowClickListener that is different.

Then to your openContextMenu function, I do not know how it is implemented, so I can not help much but you can receive the bookmark, choose the option and then change the color

mGoogleMap.setOnMarkerClickListener(marker -> {
    openContextMenu(findViewById(R.id.map), marker);
    return false;
});

openContextMenu(MapView mapa,Marker marker){
    //etc lanzar dialogo
    //cachar opcion del dialogo
    marker.setIcon(BitmapDescriptorFactory
        .defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
                    return false;
}
    
answered by 18.06.2018 в 19:32