Determine the closest marker. Google maps

7

My Android project works with Google maps, therefore it has 190 markers. The problem I face is that I would like to determine which of these is closest to my position, the problem is that I have no idea how to do it. This is the way I added the bookmarks:

    map.addMarker(new MarkerOptions().position(marcador1).title("Ciclovia Callao").snippet("Calle / Bidireccional / Alcántara a Sánchez Fontecilla").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador2).title("Ciclovia Antonio Varas").snippet("Calle y Vereda / Bidireccional / Nueva Providencia a Irarrázaval").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador3).title("Ciclovia Cardenal Raúl Silva Henríquez / Américo Vespucio").snippet("Vereda, Calle y Bandejón / Bidireccional / Canal Torrente a Porvenir").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador4).title("Ciclovia Arzobispo Valdivieso").snippet("Vereda / Bidireccional / Comandante Véliz a Ocho Norte").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador5).title("Ciclovia Almirante Blanco Encalada").snippet("Almirante Blanco Encalada").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador6).title("Ciclovia Central Cardenal Silva Henríquez").snippet("Vereda / Bidireccional / Buenaventura a Américo Vespucio").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador7).title("Ciclovia Alberto Llona").snippet("Vereda / Bidireccional / Vicente Reyes a 5 de Abril").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador8).title("Ciclovia Clotario Blest").snippet("Vereda / Bidireccional / Carlos Valdovinos a Lo Ovalle").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador9).title("Ciclovia 5 de Abril / Parque por Simón Bolívar").snippet("Bandejón / Bidireccional / Vostok a Las Torres").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador10).title("Ciclovia 5 de Abril / Esquina Blanca").snippet("Vereda y bandejón / Bidireccional / Primera Transversal a Concepción del Oro").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador11).title("Ciclovia Carlos Valdovinos").snippet("Vereda / Bidireccional / Santa Rosa a Vicuña Mackenna").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador12).title("Ciclovia Carmen / Las Industrias").snippet("Vereda / Bidireccional / General Jofré a Comercio").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador13).title("Ciclovia Cardenal Raúl Silva Henríquez").snippet("Vereda / Bidireccional / Jorge Quevedo a San Gregorio").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador14).title("Ciclovia Chile España").snippet("Calle / Bidireccional / Simón Bolívar a Miguel de Cervantes").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador15).title("Ciclovia Calle G").snippet("Bandejón / Bidireccional / Juan Cristóbal a Juan Muñoz").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador16).title("Ciclovia IV Centenario ").snippet("Vereda / Bidireccional / Los Milagros a Los Pozos").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador17).title("Ciclovia Centenario (a)").snippet("Bandejón / Bidireccional / Club Hípico a Bascuñán Guerrero").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador18).title("Ciclovia Alameda / Pajaritos").snippet("Bandejón y Calle / Bidireccional / Teatinos a Escr. Jorge Inostroza").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador19).title("Ciclovia Camino a Melipilla / Pedro Aguirre Cerda").snippet("Calle y vereda / Bidireccional / Avenida Cuatro a Esquina Blanca").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    map.addMarker(new MarkerOptions().position(marcador20).title("Ciclovia Brasil").snippet("Calle / Bidireccional / Huérfanos a Mapocho").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));

I hope you can help me out.

MainActivity:

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback {

    GoogleMap map;
    String email;
    LocationManager locationManager;
    private static final int PERMS_REQUEST_CODE = 123;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        //obtener datos para la barra
        if (user != null) {
            String nombre = user.getDisplayName();
            email = user.getEmail();
            Uri foto = user.getPhotoUrl();

            NavigationView navigationsView = (NavigationView) findViewById(R.id.nav_view);
            View hView = navigationsView.getHeaderView(0);
            TextView nav_user = (TextView) hView.findViewById(R.id.txtMail);
            TextView name = (TextView) hView.findViewById(R.id.txtNombre);
            ImageView img_user = (ImageView) hView.findViewById(R.id.profile_image);

            name.setText(nombre);
            nav_user.setText(email);
            Picasso.with(this).load(foto).into(img_user);
        } else {
            SharedPreferences loginbdd = getSharedPreferences("login", Context.MODE_PRIVATE);
            email = loginbdd.getString("nombre", "");
            String nombre = loginbdd.getString("mail", "");

            NavigationView navigationsView = (NavigationView) findViewById(R.id.nav_view);
            View hView = navigationsView.getHeaderView(0);
            TextView nav_user = (TextView) hView.findViewById(R.id.txtMail);
            TextView name = (TextView) hView.findViewById(R.id.txtNombre);
            ImageView img_user = (ImageView) hView.findViewById(R.id.profile_image);

            nav_user.setText(email);
            name.setText(nombre);


            isLocationEnabled();
            if(!isLocationEnabled()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Encienda su GPS")
                        .setMessage("Su GPS se encuentra desactivado, le gustaria activarlo?")
                        .setCancelable(false)
                        .setPositiveButton("Encencer GPS",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                                    }
                                });
                AlertDialog alert = builder.create();
                alert.show();
            }
        }
    }

    private boolean hasPermissions() {
        int res = 0;
        //string array of permissions,
        String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};

        for (String perms : permissions) {
            res = checkCallingOrSelfPermission(perms);
            if (!(res == PackageManager.PERMISSION_GRANTED)) {
                return false;
            }
        }
        return true;
    }

    private void requestPerms() {
        String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(permissions, PERMS_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        boolean allowed = true;

        switch (requestCode) {
            case PERMS_REQUEST_CODE:

                for (int res : grantResults) {
                    // if user granted all permissions.
                    allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
                    onMapReady(map);
                }

                break;
            default:
                // if user not granted permissions.
                allowed = false;
                break;
        }

        if (allowed) {
            onMapReady(map);
        } else {
            // we will give warning to user that they haven't granted permissions.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
                    Toast.makeText(this, "Permisos de Ubicación Denegados.", Toast.LENGTH_SHORT).show();
                }
            }
        }

    }

    private void goLogin() {
        Intent intent = new Intent(this, Login.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            new AlertDialog.Builder(MainActivity.this)
                    .setIcon(R.drawable.cerrar).setTitle("Cerrar Aplicación").setMessage("Deseas cerrar CicloMapp?")
                    .setCancelable(true).setPositiveButton("Si", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    System.exit(0);
                }

            })
                    .setNegativeButton("No", null).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        } else if (id == R.id.endSession) {
            new AlertDialog.Builder(MainActivity.this)
                    .setIcon(R.drawable.cerrar)
                    .setTitle("Cerrar sessión")
                    .setMessage("Deseas cerrar sesión?")
                    .setCancelable(true)
                    .setPositiveButton("Si", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                            if (user != null) {
                                LoginManager.getInstance().logOut();
                                FirebaseAuth.getInstance().signOut();
                                goLogin();
                            } else {
                                SharedPreferences loginbdd = getSharedPreferences("login", Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = loginbdd.edit();
                                editor.remove("inicio");
                                editor.commit();
                                goLogin();
                            }
                        }
                    })
                    .setNegativeButton("No", null).show();
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.AgregarRuta) {
            //  Intent i = new Intent(MainActivity.this, agregarRuta.class);
            // i.putExtra("correo", email);
            // startActivity(i);
        } else if (id == R.id.ValorarRuta) {
            Intent i = new Intent(MainActivity.this, Valoraraciones.class);
            i.putExtra("correo", email);
            startActivity(i);
        } else if (id == R.id.ReportarRuta) {
            Intent i = new Intent(MainActivity.this, Reportar.class);
            i.putExtra("correos", email);
            startActivity(i);
        } else if (id == R.id.Eventos) {

        } else if (id == R.id.tiendas) {
            Intent i = new Intent(MainActivity.this, Tiendas.class);
            startActivity(i);
        } else if (id == R.id.Leyes) {

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onMapReady(final GoogleMap googleMap) {

        if (hasPermissions()) {
            map = googleMap;
            map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            map.getUiSettings().setMapToolbarEnabled(false);
            map.getUiSettings().setMyLocationButtonEnabled(true);
            map.setMyLocationEnabled(true);
            map.getUiSettings().setZoomControlsEnabled(true);
            CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(-33.447487,-70.673676));
            CameraUpdate zoom = CameraUpdateFactory.zoomTo(11);
            map.moveCamera(center);
            map.animateCamera(zoom);

            //carga clase polylines y el metodo de agregar las polyline
            Polyline po = new Polyline();
            po.AddPolyline(map);

            //ejecutar snackbar al hacer click en un marcador
            map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(final Marker marker) {
                    View v1 = (RelativeLayout)findViewById(R.id.content_main);


                  Snackbar snackbar=  Snackbar.make(v1,"Aqui puedes \n Valorar o Reportar \n la ruta \n seleccionada",12000)
                          .setActionTextColor(Color.YELLOW)
                          .setAction("Opciones", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    new AlertDialog.Builder(MainActivity.this)
                                            .setIcon(R.drawable.cerrar)
                                            .setTitle("Opciones")
                                            .setMessage("Te gustaria valorar o reportar la ruta?")
                                            .setCancelable(true)
                                            .setPositiveButton("Valorar", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    Intent i= new Intent(getApplicationContext(),Valoracion2.class);
                                                    i.putExtra("Nruta", marker.getTitle().toString());
                                                    startActivity(i);
                                                }
                                            })
                                            .setNeutralButton("Cancelar", null)
                                            .setNegativeButton("Reportar",new DialogInterface.OnClickListener(){
                                                @Override
                                                public void onClick(DialogInterface dialog,int which){

                                                }
                                            }).show();
                                }
                            });
                    View snackbarView = snackbar.getView();
                    TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
                    textView.setMaxLines(5);
                    snackbar.show();

                    return false;
                }
            });
            //establecer tamaño del icono y mostrar marcadores
            int height = 50;
            int width = 50;
            BitmapDrawable bitmapdraw = (BitmapDrawable) getResources().getDrawable(R.drawable.mruta);
            Bitmap b = bitmapdraw.getBitmap();
            Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
            Marcadores ma=new Marcadores();
            ma.MarcadoreBdd(map,smallMarker);
        }
        else {
            requestPerms();
        }
    }

    protected boolean isLocationEnabled(){
        String le = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getSystemService(le);
        if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
            return false;
        } else {
            return true;
        }
    }

}

class where I have the markers, I will place 20, so that it is not an infinite post

public class Marcadores {
    Connection con;

    public void MarcadoreBdd(GoogleMap map,Bitmap smallMarker) {

        //Marks
        LatLng marcador1 = new LatLng(-33.377763, -70.655048);
        LatLng marcador2 = new LatLng(-33.411492, -70.630575);
        LatLng marcador3 = new LatLng(-33.418552, -70.595004);
        LatLng marcador4 = new LatLng(-33.436021, -70.664835);
        LatLng marcador5 = new LatLng(-33.440952, -70.613127);
        LatLng marcador6 = new LatLng(-33.451081, -70.598126);
        LatLng marcador7 = new LatLng(-33.457891, -70.669612);
        LatLng marcador8 = new LatLng(-33.462861, -70.664945);
        LatLng marcador9 = new LatLng(-33.464718, -70.725187);
        LatLng marcador10 = new LatLng(-33.471569, -70.719421);
        LatLng marcador11 = new LatLng(-33.474207, -70.6351);
        LatLng marcador12 = new LatLng(-33.47576, -70.664878);
        LatLng marcador13 = new LatLng(-33.484084, -70.63058);
        LatLng marcador14 = new LatLng(-33.493925, -70.676427);
        LatLng marcador15 = new LatLng(-33.50299, -70.711023);
        LatLng marcador16 = new LatLng(-33.51035, -70.741265);
        LatLng marcador17 = new LatLng(-33.515225, -70.693527);
        LatLng marcador18 = new LatLng(-33.516518, -70.755622);
        LatLng marcador19 = new LatLng(-33.540047, -70.620863);
        LatLng marcador20 = new LatLng(-33.558337, -70.615721);



        map.addMarker(new MarkerOptions().position(marcador1).title("Ciclovia Callao").snippet("Calle / Bidireccional / Alcántara a Sánchez Fontecilla").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador2).title("Ciclovia Antonio Varas").snippet("Calle y Vereda / Bidireccional / Nueva Providencia a Irarrázaval").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador3).title("Ciclovia Cardenal Raúl Silva Henríquez / Américo Vespucio").snippet("Vereda, Calle y Bandejón / Bidireccional / Canal Torrente a Porvenir").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador4).title("Ciclovia Arzobispo Valdivieso").snippet("Vereda / Bidireccional / Comandante Véliz a Ocho Norte").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador5).title("Ciclovia Almirante Blanco Encalada").snippet("Almirante Blanco Encalada").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador6).title("Ciclovia Central Cardenal Silva Henríquez").snippet("Vereda / Bidireccional / Buenaventura a Américo Vespucio").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador7).title("Ciclovia Alberto Llona").snippet("Vereda / Bidireccional / Vicente Reyes a 5 de Abril").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador8).title("Ciclovia Clotario Blest").snippet("Vereda / Bidireccional / Carlos Valdovinos a Lo Ovalle").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador9).title("Ciclovia 5 de Abril / Parque por Simón Bolívar").snippet("Bandejón / Bidireccional / Vostok a Las Torres").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador10).title("Ciclovia 5 de Abril / Esquina Blanca").snippet("Vereda y bandejón / Bidireccional / Primera Transversal a Concepción del Oro").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador11).title("Ciclovia Carlos Valdovinos").snippet("Vereda / Bidireccional / Santa Rosa a Vicuña Mackenna").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador12).title("Ciclovia Carmen / Las Industrias").snippet("Vereda / Bidireccional / General Jofré a Comercio").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador13).title("Ciclovia Cardenal Raúl Silva Henríquez").snippet("Vereda / Bidireccional / Jorge Quevedo a San Gregorio").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador14).title("Ciclovia Chile España").snippet("Calle / Bidireccional / Simón Bolívar a Miguel de Cervantes").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador15).title("Ciclovia Calle G").snippet("Bandejón / Bidireccional / Juan Cristóbal a Juan Muñoz").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador16).title("Ciclovia IV Centenario ").snippet("Vereda / Bidireccional / Los Milagros a Los Pozos").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador17).title("Ciclovia Centenario (a)").snippet("Bandejón / Bidireccional / Club Hípico a Bascuñán Guerrero").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador18).title("Ciclovia Alameda / Pajaritos").snippet("Bandejón y Calle / Bidireccional / Teatinos a Escr. Jorge Inostroza").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador19).title("Ciclovia Camino a Melipilla / Pedro Aguirre Cerda").snippet("Calle y vereda / Bidireccional / Avenida Cuatro a Esquina Blanca").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
        map.addMarker(new MarkerOptions().position(marcador20).title("Ciclovia Brasil").snippet("Calle / Bidireccional / Huérfanos a Mapocho").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
    }
    
asked by zhet 08.12.2016 в 23:15
source

3 answers

3

It would be best to calculate the distances between your position and those of your markers

public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
    double earthRadius = 6371000; //meters
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
           Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
           Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double dist = (double) (earthRadius * c);

    return dist;
}

This function, extracted from stackoverflow question in English calculates the distance between two directions in meters

As you have the latitudes and longitudes of all your markers, when you arm them, send this function your latitude and longitude to obtain the distance in meters. Something like this:

public void masCercano(double lat1, double lng1, double lat2, double lng2){
  double distance = distFrom(lat1, lng1, lat2, lng2);
   if(this.contador == 0){
      this.distancia = distance;
      this.latitud_cercana = lat1;
      this.longitud_cercana = lng1;
      this.contador++;
   }else{
       if(distance <= this.distancia){
           this.distancia = distance;
           this.latitud_cercana = lat1;
           this.longitud_cercana = lng1;
       }
   }
}

And so you get the smallest of the distances being 0 if you're right there.

marcador1 = new LatLng(-33.377763, -70.655048);
this.masCercano(-33.377763, -70.655048, ti_latitud, tu_longitud);

Where latitud_cercana and longitud_cercana would be your data for the nearest marker.

This would be like this:

public class Test {
    public double distancia = 0.0;
    public double latitud_cercana = 0;
    public double longitud_cercana = 0;
    public static double mi_latitud = -33.3916818;
    public static double mi_longitud = -70.6157192;
    public int contador = 0;
    public static void main(String[] args) {
        // TODO Auto-generated method stub


        ArrayList < Marcador > marcadores = new ArrayList < Marcador > ();
        marcadores.add(new Marcador(-33.3908577, -70.6170388));
        marcadores.add(new Marcador(-33.3956634, -70.6159224));
        //marcadores.add(new Marcador(-33.3916818, -70.6157192));
        marcadores.add(new Marcador(-33.3838813, -70.6247515));
        Test a = new Test();
        for (Marcador object: marcadores) {
            a.masCercano(object.latitud, object.longitud, mi_latitud, mi_longitud);
        }
        System.out.println("Distancia = " + a.distancia);
        System.out.println("Latitud cercana  = " + a.latitud_cercana);
        System.out.println("Longitud cercana = " + a.longitud_cercana);
    }

    public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
        double earthRadius = 6371000; //meters
        double dLat = Math.toRadians(lat2 - lat1);
        double dLng = Math.toRadians(lng2 - lng1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
            Math.sin(dLng / 2) * Math.sin(dLng / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double dist = (double)(earthRadius * c);

        return dist;
    }

    public void masCercano(double lat1, double lng1, double lat2, double lng2) {
        double distance = distFrom(lat1, lng1, lat2, lng2);
        if (this.contador == 0) {
            this.distancia = distance;
            this.latitud_cercana = lat1;
            this.longitud_cercana = lng1;
            this.contador++;
        } else {
            if (distance <= this.distancia) {
                this.distancia = distance;
                this.latitud_cercana = lat1;
                this.longitud_cercana = lng1;
            }
        }
    }
}
    
answered by 11.12.2016 / 00:27
source
5

You can determine the distance using the class Location .

For example, go through all the distances of your markers and save them on a map.

private static float distance(LatLng marcador, Location miUbicacion){
    Location cL = new Location("");
    cL.setLatitude(marcador.latitude);
    cL.setLongitude(marcador.longitude);

    return miUbicacion.distanceTo(cL);
}

Then use the Collections.min() method to know which is the closest distance to your current position. With the following sentence you would extract that information to the Log of the device:

Log.i("TAG", "Valor mínimo: " + Collections.min(mapDistance.keySet())); 

EDITED

Taking into account the above information, generate a method that returns a list of LatLong.

You must go through the list and create a map to save the distance (Key) obtained from the distance () method and associate the LatLong (Value) from which it is obtained, then you must pass the mapDistance to the Collections.min () method to know what is the minimum distance of the map. With the help of the minimum distance that returns you get the LatLong on the map.

  private void encuentraMasCercano(){
    //Variable para verificar el tiempo que se tarda en ejecutar todo el método
    long time = System.currentTimeMillis();

    //LatLng de mi ubicación
    LatLng miLatLng = new LatLng(-33.461496, -70.659317);
    //Location de mi ubicación
    Location miLocation = new Location("");
    miLocation.setLatitude(miLatLng.latitude);
    miLocation.setLongitude(miLatLng.longitude);
    //Listado de LatLong de ejemplo
    List<LatLng> latLngList = getList();
    //Mapa con un tamaño definido para el ejemplo
    Map<Float, LatLng> mapDistance = new HashMap<>(20);

    for (LatLng latLng : latLngList){
        float distance = distance(latLng, miLocation);
        Log.d("TAG" , "Distance : "+ distance);
        mapDistance.put(distance, latLng);
    }

    float min = Collections.min(mapDistance.keySet());
    //Obtienes la LatLng mas cercano a tu ubicación
    LatLng latLngMasCercano = mapDistance.get(min);

    Log.d("TAG" , "Distancia : "+ min  + " Latitude " + latLngMasCercano.latitude  + " Longitude : " +latLngMasCercano.longitude);

    time = System.currentTimeMillis() - time;
    Log.d("TAG", " time : " + time );
 }  

Greetings.

    
answered by 09.12.2016 в 00:00
2

In addition to the answers given, you should bear in mind that Google already provides the library Google Maps Android API utility library that not only implements a method to calculate the distance between two GPS points ( computeDistanceBetween for two objects LatLng ), but also includes other convenient methods such as calculating the Heading (or the address to be taken from one point to the other) and other useful methods for areas and calculation of length of a Path, in addition to other utilities.

Then, like the other solutions, like in Maps you do not have a method to list the bookmarks loaded in the map , you have to solve it on your own, loading in an array or List<LatLng> all the markers that interest you and then iterate over that list comparing those positions with your current position to find out which is the closest.

Example:

When you add the markers .. you should also add them in a list or arrangement

   List<LatLng> marcadores = new ArrayList<>();

   marcadores.add(marcador1);
   map.addMarker(new MarkerOptions().position(marcador1).title("Ciclovia Callao").snippet("Calle / Bidireccional / Alcántara a Sánchez Fontecilla").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));

   marcadores.add(marcador2);
   map.addMarker(new MarkerOptions().position(marcador2).title("Ciclovia Antonio Varas").snippet("Calle y Vereda / Bidireccional / Nueva Providencia a Irarrázaval").icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));

   // etc

Then, Assuming that miPos has the position you are in:

LatLon miPos = new LatLon(<aquí va tu posición>);
LatLng posicionMasCercana = null;
double distanciaActual = Double.MAX_VALUE;

for(int i=0; i < marcadores.size(); i++) {
    double distancia = SphericalUtil.computeDistanceBetween(miPos, marcadores.get(i));
    if (distanciaActual > distancia) {
        posicionMasCercana = marcadores.get(i);
        distanciaActual = distancia;
    }
}

// en este punto, posicionMasCercana, tiene la latitud y longitud del punto
// mas cercano a miPos
    
answered by 13.12.2016 в 19:11