1

Para empezar llevo poco tiempo con esto y para seguir me gustaría saber cómo podría cambiar (pulsando btnMarker) el color a mi marcador cuando cambio de localización, en concreto quiero que cambie el marcador de color rojo a verde cuando esté en estas coordenadas (41.656337, -0.878863).

Pego código:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private GoogleMap mMap;
    private final static int MY_PERMISSION_LOCATION = 101;
    private GoogleApiClient googleApiClient;
    private LocationRequest locationRequest;
    protected static final String TAG = "MapsActivity";
    Double myLat = null;
    Double myLong = null;
    Button bGeo;
    Button bMarker;
    ZoomControls zContronls;

    Double myLat2 = null;
    Double myLong2 = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();


        locationRequest = new LocationRequest();
        locationRequest.setInterval(15 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);


        zContronls = (ZoomControls) findViewById(R.id.cntrlZoom);
        zContronls.setOnZoomOutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMap.animateCamera(CameraUpdateFactory.zoomOut());
            }
        });

        zContronls.setOnZoomInClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMap.animateCamera(CameraUpdateFactory.zoomIn());
            }
        });


        bGeo = (Button) findViewById(R.id.btn1);
        bGeo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText eSearch = (EditText) findViewById(R.id.etxt1);
                String coordenadas = eSearch.getText().toString();
                if (coordenadas != null && !coordenadas.equals("")) {
                    List<Address> addressList = null;
                    Geocoder geocoder = new Geocoder(MapsActivity.this);
                    try {
                        addressList = geocoder.getFromLocationName(coordenadas, 1);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    Address address = addressList.get(0);
                    LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
                    mMap.addMarker(new MarkerOptions().position(latLng).title("Mi Posicion"));
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                }
            }
        });


        bMarker = (Button) findViewById(R.id.btnMarcador);
        bMarker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                LatLng myLocation = new LatLng(myLat, myLong);
                mMap.addMarker(new MarkerOptions().position(myLocation).title("Mi Marcador"));

                LatLng myLocation2 = new LatLng(myLat2, myLong2);
                mMap.addMarker(new MarkerOptions().position(myLocation2).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
            }
        });
    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mMap = googleMap;

        // Add a marker in MyLocation and move the camera
        LatLng sydney = new LatLng(-34, 151);
        //mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_LOCATION);
        }
    }


    //PERMISOS: ALLOW or DENY
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case MY_PERMISSION_LOCATION:

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        mMap.setMyLocationEnabled(true);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "Esta app requiere permisos", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
        }


    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {
        requestLocationUpdates();
    }

    private void requestLocationUpdates()
    {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED )
        {
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
        }

    }

    @Override
    public void onConnectionSuspended(int i)
    {
        Log.i(TAG, "Conexión Suspendida");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
    {
        Log.i(TAG, "Conexión Fallida: ConnectionResult.getErrorCode = " + connectionResult.getErrorCode());
    }

    @Override
    public void onLocationChanged(final Location location)
    {

        myLat = location.getLatitude();
        myLong = location.getLongitude();

        myLat2 = 41.656337;
        myLong2 = -0.878863;

    }

    @Override
    protected void onStart()
    {
        super.onStart();
        googleApiClient.connect();

    }

    @Override
    protected void onPause()
    {
        super.onPause();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED )
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);

    }

    @Override
    protected void onResume()
    {
        super.onResume();
        if(googleApiClient.isConnected())
        {
            requestLocationUpdates();
        }
    }

    @Override
    protected void onStop()
    {
        super.onStop();
        googleApiClient.disconnect();
    }
}

2 respuestas 2

0

Para cambiar de rojo a verde el indicador de posición dependiendo de unas coordenadas especificas, puedes usar una imagen de un indicador verde:

LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());

MarkerOptions options;

if((address.getLatitude() == 41.656337) && (address.getLongitude() == -0.878863)){
   //Cambia propiedades de Marker
   options = new MarkerOptions().position(latLng).title("Mi Posicion")
   //Agrega icono marcador verde.
   options.icon(BitmapDescriptorFactory.fromResource(R.drawable.marcador_verde));
}else{
   //Marcador default
   options = new MarkerOptions().position(latLng).title("Mi Posicion")
}

//Agrega marker
mMap.addMarker(options);

Tu marcador se creará con la imagen definida:

introducir la descripción de la imagen aquí


La otra opción es usa los colores del sistema y en lugar de definir una imagen, se define un color:

//options.icon(BitmapDescriptorFactory.fromResource(R.drawable.marcador_verde));     
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

El marcador se creará con la imagen de color deseado del SDK:

introducir la descripción de la imagen aquí

Puedes usar otros colores como son:

float   HUE_AZURE   
float   HUE_BLUE    
float   HUE_CYAN    
float   HUE_GREEN   
float   HUE_MAGENTA 
float   HUE_ORANGE  
float   HUE_RED 
float   HUE_ROSE    
float   HUE_VIOLET  
float   HUE_YELLOW
0
0

Vale, me ha ayudado en cierto modo con el tema de la condición (gracias Jorgesys!), copio y pego para los que necesiten de este "problema" XD por si sirviera de ayuda:

  bMarker = (Button) findViewById(R.id.btnMarcador);
    bMarker.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

            LatLng myPos = new LatLng(myLat, myLong);
            LatLng myPos2 = new LatLng(myLat2, myLong2);


            if((myLat2 == 41.6563) || (myLong2 == -0.878863)){
            mMap.addMarker(new MarkerOptions().position(myPos2).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));}

            else{
            mMap.addMarker(new MarkerOptions().position(myPos).title("Mi Marcador"));}

        }
    });



@Override
public void onLocationChanged(Location location)
{

    myLat = location.getLatitude();
    myLong = location.getLongitude();

    myLat2 = location.getLatitude();
    myLong2 = location.getLongitude();

}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.