Direct my button to google maps on Android

2

Hello, I have been doing an APP, which is basically filled by a WebService, where I get all the information in it its latitud and longitud in this example of a school x, in my detail and put a map button is say that if you click on it, it directs you to the application that it has by default in android or to the maps of chrome, basically in my application I already have the latitude and longitude:

public String getLatitud() {
        return latitud;
    }

    public String getLongitud() {
        return longitud;
    }

Well this is the listening part of the button

// Setear escucha para el fab
mapsButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Iniciar actividad de de Localizacion
                    }
                }
        );

Full code:

    public class DetailFragment extends Fragment {

        /**
         * Etiqueta de depuración
         */
        private static final String TAG = DetailFragment.class.getSimpleName();

        /*
        Instancias de Views
         */
        private ImageView cabecera;
        private TextView titulo;
        private TextView institucion;
        private TextView codigo_plaza;
        private TextView modalidad;
        private TextView especialidad;
        private TextView nivel;
        private TextView tipo_vacante;
        private TextView jornada;
        private TextView motivo;
        private TextView estado;
        private ImageButton editButton;
        private String extra;
        private Gson gson = new Gson();

    public DetailFragment() {
    }

    public static DetailFragment createInstance(String idMeta) {
        DetailFragment detailFragment = new DetailFragment();
        Bundle bundle = new Bundle();
        bundle.putString(Constantes.EXTRA_ID, idMeta);
        detailFragment.setArguments(bundle);
        return detailFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_detail, container, false);


        // Obtención de views
        cabecera = (ImageView) v.findViewById(R.id.cabecera);
        titulo = (TextView) v.findViewById(R.id.titulo);
        institucion = (TextView) v.findViewById(R.id.institucion);
        codigo_plaza = (TextView) v.findViewById(R.id.codigo_plaza);
        modalidad = (TextView) v.findViewById(R.id.modalidad);
        especialidad = (TextView) v.findViewById(R.id.especialidad);
        nivel = (TextView) v.findViewById(R.id.nivel);
        tipo_vacante = (TextView) v.findViewById(R.id.tipo_vacante);
        jornada = (TextView) v.findViewById(R.id.jornada);
        motivo = (TextView) v.findViewById(R.id.motivo);
        estado = (TextView) v.findViewById(R.id.estado);
        editButton = (ImageButton) v.findViewById(R.id.fab);

        // Obtener extra del intent de envío
        extra = getArguments().getString(Constantes.EXTRA_ID);

        // Setear escucha para el fab
mapsButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Iniciar actividad de de Localizacion
                    }
                }
        );

        // Cargar datos desde el web service
        cargarDatos();

        return v;
    }

    /**
     * Obtiene los datos desde el servidor
     */
    public void cargarDatos() {

        // Añadir parámetro a la URL del web service
        String newURL = Constantes.GET_BY_ID + "?plazaID=" + extra;

        // Realizar petición GET_BY_ID
        VolleySingleton.getInstance(getActivity()).addToRequestQueue(
                new JsonObjectRequest(
                        Request.Method.GET,
                        newURL,
                        null,
                        new Response.Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject response) {
                                // Procesar respuesta Json
                                procesarRespuesta(response);
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Log.d(TAG, "Error Volley: " + error.getMessage());
                            }
                        }
                )
        );
    }

    /**
     * Procesa cada uno de los estados posibles de la
     * respuesta enviada desde el servidor
     *
     * @param response Objeto Json
     */
    private void procesarRespuesta(JSONObject response) {

        try {
            // Obtener atributo "mensaje"
            String mensaje = response.getString("estado");

            switch (mensaje) {
                case "1":
                    // Obtener objeto "meta"
                    JSONObject object = response.getJSONObject("meta");

                    //Parsear objeto 
                    Plaza plaza = gson.fromJson(object.toString(), Plaza.class);

                    // Asignar color del fondo
                    switch (plaza.getEstado()) {
                        case "0":
                            cabecera.setBackgroundColor(getResources().getColor(R.color.ocupadoColor));
                            estado.setText("OCUPADO");
                            titulo.setText("OCUPADO");
                            break;
                        case "1":
                            cabecera.setBackgroundColor(getResources().getColor(R.color.vacanteColor));
                            estado.setText("VACANTE");
                            titulo.setText("VACANTE");
                            break;
                        case "2":
                            cabecera.setBackgroundColor(getResources().getColor(R.color.reservadolColor));
                            estado.setText("RESERVADO");
                            titulo.setText("RESERVADO");
                            break;
                    }
                    // Seteando valores en los views

                    institucion.setText(plaza.getIe());
                    codigo_plaza.setText(plaza.getCodigoPlaza());
                    modalidad.setText(plaza.getModalidad());
                    especialidad.setText(plaza.getEspecialidad());
                    nivel.setText(plaza.getNivel());
                    tipo_vacante.setText(plaza.getTipoVacante());
                    jornada.setText(plaza.getJornada()+" HORAS");
                    motivo.setText(plaza.getMotivoVacante());
                    //estado.setText(plaza.getEstado());

                    break;

                case "2":
                    String mensaje2 = response.getString("mensaje");
                    Toast.makeText(
                            getActivity(),
                            mensaje2,
                            Toast.LENGTH_LONG).show();
                    break;

                case "3":
                    String mensaje3 = response.getString("mensaje");
                    Toast.makeText(
                            getActivity(),
                            mensaje3,
                            Toast.LENGTH_LONG).show();
                    break;
            }


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

    }
}
    
asked by Ivan More Flores 19.07.2017 в 17:12
source

1 answer

4

To open the google maps that comes by default in the mobiles you should use Intent .

In the attached Intent as parameter

  

ACTION_VIEW (Activity Action: Display the data to the user.)

In the uri what we added was the action that we want to be executed in this case

  

geo:

Followed by the parametros that you request, to show the location and the text that we will send to google maps

if(instancia.getLatitud()==null && instancia.getLongitud())
{   //suponiendo que tienes un metodo que lanza un mensaje
    mostrarAlerta("No se puede realizar la busqueda en mapa");
}else{
    String labelLocation = "Titulo: Si se quiere anexar algo de texto aquí";
    String uri = "geo:<" + getLatitud()+ ">,<" + getLongitud()+ ">?q=<" + getLatitud()+ ">,<" + getLongitud()+ ">(" + labelLocation + ")";
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
    startActivity(intent);
}

As a result you should show something like this.

  

Intent (String action, Uri uri)

     

Create an intent with a given action and for a given data url.

I leave the link to the documentation of how to use Intent link

    
answered by 19.07.2017 / 18:01
source