Use my location to add bookmarks, Maps SDK for android

1

I'm creating a map application for android that shows users whether or not the place where they will pass is dangerous or not, it would have interactivity between users where, when someone presses a button, a marker will be added to their current position map. My problem is, I can not use my location when I press the set button, I can only use a pre-defined location. So I want help when I push a button, it adds a bookmark at my current position.

To make it easier to understand the code, follow the playlist link that was followed for the development: " link "

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback,         GoogleApiClient.OnConnectionFailedListener, LocationListener {

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onMapReady(GoogleMap googleMap) {
    Toast.makeText (this , "Map is Ready" , Toast.LENGTH_SHORT).show ();
    Log.d (TAG , "onMapReady: maps is ready");
    mMap = googleMap;

    if (mLocationPermissionsGrated) {
        getDeviceLocation ();

        if (ActivityCompat.checkSelfPermission (this , Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission (this ,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mMap.setMyLocationEnabled (true);
        mMap.getUiSettings ().setMyLocationButtonEnabled (false);

        init ();
    }
}

private static final String TAG = "MapActivity";

private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
private static final int PLACE_PICKER_REQUEST = 1;
private static LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds (
        new LatLng (-40, -168), new LatLng (71, 136));

//widgets
private AutoCompleteTextView mSearchText;
private ImageView mGps, mInfo, mPlacePicker;

// vars
private boolean mLocationPermissionsGrated = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private PlaceAutocompleteAdapter mPlaceAutocompleteAdapter;
private GoogleApiClient mGoogleApiClient;
private PlaceInfo mPlace;
private Marker mMarker;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate (savedInstanceState);
    setContentView (R.layout.activity_map);
    mSearchText = (AutoCompleteTextView) findViewById (R.id.input_search);
    mGps = (ImageView) findViewById (R.id.ic_gps);
    mInfo = (ImageView) findViewById (R.id.place_info);
    mPlacePicker = (ImageView) findViewById (R.id.place_picker);

    final Button btnassalto = (Button) findViewById(R.id.btnassalto);
    btnassalto.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

// Marker Assault = mMap.addMarker ( // new MarkerOptions () // .position (new LatLng (-23.5289, -46.3635)) // Provisional // .title ("Assault") // .icon (BitmapDescriptorFactory.fromResource (R.drawable.marker_roubo)));             }         });

    Button btnruaestreita = (Button) findViewById(R.id.btnruaestreita);
    btnruaestreita.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

// Marker ruaestreita = mMap.addMarker ( // new MarkerOptions () // .position (new LatLng (-23.5498, -46.5546)) // Provisional // .title ("Narrow Street") // .icon (BitmapDescriptorFactory.fromResource (R.drawable.marker_walk)));             }         });

    Button btnenchente = (Button) findViewById(R.id.btnenchente);
    btnenchente.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

// Marker flood = mMap.addMarker ( // new MarkerOptions () // .position (new LatLng (-23.5664, -46.5073)) // Provisional // .title ("Flood") // .icon (BitmapDescriptorFactory.fromResource (R.drawable.marker_value)));             }         });

    Button btnligacao = (Button) findViewById(R.id.btnligacao);
    btnligacao.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Uri uri = Uri.parse("tel:"+190);
            Intent intent = new Intent(Intent.ACTION_DIAL,uri);

            startActivity(intent);
        }
    });

    getLocationPermission ();
}

private void init() {
    Log.d (TAG , "init: initializing");

    mGoogleApiClient = new GoogleApiClient
            .Builder(this)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .enableAutoManage(this, this)
            .build();
    mSearchText.setOnItemClickListener (mAutocompleteClickListener);

    mPlaceAutocompleteAdapter = new PlaceAutocompleteAdapter (this, mGoogleApiClient,
            LAT_LNG_BOUNDS, null);

    mSearchText.setAdapter (mPlaceAutocompleteAdapter);

    mSearchText.setOnEditorActionListener (new TextView.OnEditorActionListener () {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || keyEvent.getAction() == KeyEvent.ACTION_DOWN
                    || keyEvent.getAction() == KeyEvent.KEYCODE_ENTER) {

                //execute our method for searching
                geoLocate ();
            }

            return false;
        }
    });

    mGps.setOnClickListener (new View.OnClickListener () {
        @Override
        public void onClick(View view) {
            Log.d (TAG, "onClick: clicked gps icon");
            getDeviceLocation ();
        }
    });

    mInfo.setOnClickListener (new View.OnClickListener () {
        @Override
        public void onClick(View view) {
            Log.d (TAG , "onClick: clicked place info");
            try {
                if (mMarker.isInfoWindowShown ()) {
                     mMarker.hideInfoWindow ();
                } else {
                    Log.d (TAG , "onClick: place info: " + mPlace.toString ());
                    mMarker.showInfoWindow ();
                }
            }catch (NullPointerException e){
                Log.e (TAG, "onClick: NullPointerException: " + e.getMessage ());
            }
        }
    });

    mPlacePicker.setOnClickListener (new View.OnClickListener () {
        @Override
        public void onClick(View view) {

            PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();

            try {
                startActivityForResult(builder.build(MapActivity.this), PLACE_PICKER_REQUEST);
            } catch (GooglePlayServicesRepairableException e) {
                Log.e (TAG, "onClick: GooglePlayServicesRepairableException: " + e.getMessage ());
            } catch (GooglePlayServicesNotAvailableException e) {
                Log.e (TAG, "onClick: GooglePlayServicesNotAvailableException: " + e.getMessage ());
            }
        }
    });

    hideSoftKeyboard();
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == RESULT_OK) {
            Place place = PlacePicker.getPlace(this, data);

            PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
                    .getPlaceById (mGoogleApiClient, place.getId ());
            placeResult.setResultCallback (mUpdatePlaceDetailsCallback);
        }
    }
}

private void geoLocate(){
    Log.d (TAG, "geoLocate: geolocating");

    String searchString = mSearchText.getText ().toString ();

    Geocoder geocoder = new Geocoder (MapActivity.this);
    List<Address> list = new ArrayList<> ();
    try{
        list = geocoder.getFromLocationName (searchString, 1);
    }catch (IOException e){
        Log.e (TAG, "geoLocate: IOException" + e.getMessage () );
    }

    if (list.size ()>0){
        Address address= list.get (0);

        Log.d (TAG, "geoLocate: found a location" + address.toString ());
        //Toast.makeText (this, address.toString (), Toast.LENGTH_SHORT).show ();

        moveCamera (new LatLng (address.getLatitude (), address.getLongitude ()), DEFAULT_ZOOM,
                address.getAddressLine (0));
    }
}

private void getDeviceLocation(){
    Log.d(TAG, "getDeviceLocation: getting the devices current locations");

    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

    try{
        if (mLocationPermissionsGrated){

            com.google.android.gms.tasks.Task<Location> location = mFusedLocationProviderClient.getLastLocation();
            location.addOnCompleteListener(new OnCompleteListener<Location>() {
                @Override
                public void onComplete(@NonNull com.google.android.gms.tasks.Task<Location> task) {
                     if (task.isSuccessful()){
                         Log.d(TAG, "onComplete: found location!");
                         Location currentlocation = (Location) task.getResult();

                         moveCamera(new LatLng(currentlocation.getLatitude(), currentlocation.getLongitude()),
                                 DEFAULT_ZOOM,
                                 "My Location!");

                     }else{
                         Log.d(TAG, "onComplete: current location is null");
                         Toast.makeText(MapActivity.this, "unable to get current location"
                                 , Toast.LENGTH_SHORT).show();
                     }
                }
            });
        }
    } catch (SecurityException e){
        Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
    }
}

private void moveCamera(LatLng latLng, float zoom, PlaceInfo placeInfo){
    Log.d(TAG, "moveCamera: moving the camera to: last: " + latLng.latitude + ", lng:" +latLng.longitude);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));

    mMap.clear ();

    mMap.setInfoWindowAdapter (new CustomInfoWindowAdapter (MapActivity.this));

    if (placeInfo != null){
        try{
            String snippet = "Endereço: " + placeInfo.getAddress () + "\n" +
                             "Telefone: " + placeInfo.getPhoneNumber () + "\n" +
                             "Site: " + placeInfo.getWebsiteUri () + "\n" +
                             "Avaliação: " + placeInfo.getRating () + "\n";

            MarkerOptions options = new MarkerOptions ()
                    .position (latLng)
                    .title (placeInfo.getName ())
                    .snippet (snippet);
            mMarker = mMap.addMarker (options);

        }catch (NullPointerException e){
            Log.e (TAG, "moveCamera: NullPointerException: " + e.getMessage ());
        }
    }else{
        mMap.addMarker (new MarkerOptions ().position (latLng));
    }

    hideSoftKeyboard();
}

private void moveCamera(LatLng latLng, float zoom, String title){
    Log.d(TAG, "moveCamera: moving the camera to: last: " + latLng.latitude + ", lng:" +latLng.longitude);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));

    if (!title.equals ("My Location!")){
        MarkerOptions options = new MarkerOptions ()
                .position (latLng)
                .title (title);
        mMap.addMarker (options);
    }

    hideSoftKeyboard();
}
private void initMap(){
    Log.d(TAG, "initMap: initializing map");
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager(). findFragmentById(R.id.map);

    mapFragment.getMapAsync(MapActivity.this);
}

private void getLocationPermission(){
    Log.d(TAG, "getLocationPermission: getting location permissions");
    String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
    Manifest.permission.ACCESS_COARSE_LOCATION};

    if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
            FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
        if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
                COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            mLocationPermissionsGrated = true;
            initMap();
        }else{
            ActivityCompat.requestPermissions(this,
                    permissions,
                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    }else{
        ActivityCompat.requestPermissions(this,
                permissions,
                LOCATION_PERMISSION_REQUEST_CODE);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    Log.d(TAG, "onRequestPermissionsResult: called");
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    mLocationPermissionsGrated = false;

    switch (requestCode) {
        case LOCATION_PERMISSION_REQUEST_CODE: {
            if (grantResults.length > 0) {
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        mLocationPermissionsGrated = false;
                        Log.d(TAG, "onRequestPermissionsResult: permission failed");
                        return;
                    }
                }
                Log.d(TAG, "onRequestPermissionsResult: permission granted");
                mLocationPermissionsGrated = true;
                //Inicia o Mapa
                initMap();
            }
        }
    }
}

private void hideSoftKeyboard(){
    this.getWindow ().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
    
asked by anonymous 11.11.2018 / 22:04

0 answers