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