如何让最近的标记到我的位置,谷歌地图

时间:2016-12-09 16:01:16

标签: android google-maps

我有一个包含190个标记的Android项目,我需要一种可以获得最接近标记的方法,但我不知道该怎么做,而且我正在寻找任何帮助,例如示例或关于那个的文档

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
        map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                View v1 = (RelativeLayout)findViewById(R.id.content_main);
                Snackbar.make(v1,"Nombre de la ciclovía: "+marker.getTitle()+ System.getProperty ("line.separator")+"Caracteristicas de la vía: "+marker.getSnippet(),12000).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;
    }
}

}

0 个答案:

没有答案