Create Button that gives you your location in Android Studio

0

I want to create a Button that tells me exactly where my device is located, and that it is indicated to me in a MapView, I tried to do it in some ways but I did not get it.

For now this is code that I have:

public class CameraFragment extends Fragment implements OnMapReadyCallback{
 double latitude, longitude;
 Button myplacebtn;
MapView mapView;
 GoogleMap map;

 public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.camera_fragment, container, false);
         myplacebtn = (Button) view.findViewById(R.id.myplacebtn);//Button --get my location

         mapView = (MapView) view.findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        //get a MapView
        mapView.getMapAsync(new OnMapReadyCallback() {

            public static final int MY_REQUEST_INT = 177;

            @Override
            public void onMapReady(GoogleMap googleMap) {
                map = googleMap;
                // Setting a click event handler for the map
                map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

                    @Override
                    public void onMapClick(LatLng latLng) {

                        // Creating a marker
                        MarkerOptions markerOptions = new MarkerOptions();

                        // Setting the position for the marker
                        markerOptions.position(latLng);
                        setCoordinates.setText(latLng.latitude + " , " + latLng.longitude);
                        latitude = latLng.latitude;
                        longitude = latLng.longitude;

                        // Setting the title for the marker.
                        // This will be displayed on taping the marker
                        markerOptions.title(latLng.latitude + " : " + latLng.longitude);

                        // Clears the previously touched position
                        map.clear();

                        // Animating to the touched position
                        map.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                        // Placing a marker on the touched position
                        map.addMarker(markerOptions);
                    }
                });
                map.getUiSettings().setMyLocationButtonEnabled(false);


                LatLng jerusalem = new LatLng(32.1105435, 34.8683683);
                CameraUpdate miLocation = CameraUpdateFactory.newLatLngZoom(jerusalem, 11);
                map.moveCamera(CameraUpdateFactory.newLatLng(jerusalem));
                googleMap.animateCamera(miLocation);
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(jerusalem);

                if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
                        android.Manifest.permission.ACCESS_FINE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(),
                        android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
                                android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}, MY_REQUEST_INT);
                    }
                    return;
                } else {
                    googleMap.setMyLocationEnabled(true);
                }

                googleMap.getUiSettings().setZoomControlsEnabled(true);

            }
        });



        }



    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }


    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

}

I tried to use LocationListener but it gives me error

    
asked by Julio Mizrahi 11.09.2018 в 02:58
source

1 answer

1

You can try something like that, my friend, here is the example class of how coordinates are obtained by GPS.

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

    mensaje1 = (TextView) findViewById(R.id.mensaje_id);
    mensaje2 = (TextView) findViewById(R.id.mensaje_id2);


    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,}, 1000);
    } else {
        locationStart();
    }
}

private void locationStart() {
    LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Localizacion Local = new Localizacion();
    Local.setMainActivity(this);
    final boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (!gpsEnabled) {
        Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(settingsIntent);
    }
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,}, 1000);
        return;
    }
    mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) Local);
    mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) Local);

    mensaje1.setText("Localizacion agregada");
    mensaje2.setText("");
}

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == 1000) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            locationStart();
            return;
        }
    }
}

public void setLocation(Location loc) {
    //Obtener la direccion de la calle a partir de la latitud y la longitud
    if (loc.getLatitude() != 0.0 && loc.getLongitude() != 0.0) {
        try {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> list = geocoder.getFromLocation(
                    loc.getLatitude(), loc.getLongitude(), 1);
            if (!list.isEmpty()) {
                Address DirCalle = list.get(0);
                mensaje2.setText("Mi direccion es: \n"
                        + DirCalle.getAddressLine(0));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/* Aqui empieza la Clase Localizacion */
public class Localizacion implements LocationListener {
    MainActivity mainActivity;

    public MainActivity getMainActivity() {
        return mainActivity;
    }

    public void setMainActivity(MainActivity mainActivity) {
        this.mainActivity = mainActivity;
    }

    @Override
    public void onLocationChanged(Location loc) {
        // Este metodo se ejecuta cada vez que el GPS recibe nuevas coordenadas
        // debido a la deteccion de un cambio de ubicacion

        loc.getLatitude();
        loc.getLongitude();

        String Text = "Mi ubicacion actual es: " + "\n Lat = "
                + loc.getLatitude() + "\n Long = " + loc.getLongitude();
        mensaje1.setText(Text);
        this.mainActivity.setLocation(loc);
    }

    @Override
    public void onProviderDisabled(String provider) {
        // Este metodo se ejecuta cuando el GPS es desactivado
        mensaje1.setText("GPS Desactivado");
    }

    @Override
    public void onProviderEnabled(String provider) {
        // Este metodo se ejecuta cuando el GPS es activado
        mensaje1.setText("GPS Activado");
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        switch (status) {
            case LocationProvider.AVAILABLE:
                Log.d("debug", "LocationProvider.AVAILABLE");
                break;
            case LocationProvider.OUT_OF_SERVICE:
                Log.d("debug", "LocationProvider.OUT_OF_SERVICE");
                break;
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                Log.d("debug", "LocationProvider.TEMPORARILY_UNAVAILABLE");
                break;
        }
    }
}

} '

The only thing that would remain, would be once having the coordinates, pass them to the map to show it with a marker.

    
answered by 12.09.2018 / 00:06
source