Shahil Islam
Shahil Islam

Reputation: 77

Change position of MyLocation Button in MapsActivity

I am trying to change the position of my location button in my Maps Android App from top to bottom. Seems like it is default in top. Please help me changing the position of it. I have taken the code from the google samples github. This is the new version of code which uses getMapAsync instead of getMap.

enter image description here

MapsActivity.java:

public class MapsActivity extends AppCompatActivity implements GoogleMap.OnMyLocationButtonClickListener,
      GoogleMap.OnMyLocationClickListener,
      OnMapReadyCallback,
      ActivityCompat.OnRequestPermissionsResultCallback {

  /**
  * Request code for location permission request.
  *
  * @see #onRequestPermissionsResult(int, String[], int[])
  */
  private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

  /**
  * Flag indicating whether a requested permission has been denied after returning in
  * {@link #onRequestPermissionsResult(int, String[], int[])}.
  */
  private boolean mPermissionDenied = false;

  private GoogleMap mMap;

  private PlaceAutocompleteFragment placeAutocompleteFragment;

  Marker marker;

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

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


      placeAutocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
      // placeAutocompleteFragment.setFilter(new AutocompleteFilter.Builder().setCountry("ID").build());
      placeAutocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
          @Override
          public void onPlaceSelected(Place place) {
              final LatLng latLngLoc = place.getLatLng();

              if (marker != null) {
                  marker.remove();
              }
              marker = mMap.addMarker(new MarkerOptions().position(latLngLoc).title(place.getName().toString()));
              mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngLoc));
              mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
          }

          @Override
          public void onError(Status status) {
              Toast.makeText(MapsActivity.this, "" + status.toString(), Toast.LENGTH_SHORT).show();
          }
      });


  }


  @Override
  public void onMapReady(GoogleMap googleMap) {
      mMap = googleMap;

      mMap.setOnMyLocationButtonClickListener(this);
      mMap.setOnMyLocationClickListener(this);
      enableMyLocation();


      mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
          @Override
          public void onMapClick(LatLng point) {

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

              // Setting the position for the marker
              markerOptions.position(point);


              // changing the marker title
              double lat = point.latitude;
              double lng = point.longitude;
              Geocoder gc = new Geocoder(MapsActivity.this);

              List<Address> list = null;
              try {
                  list = gc.getFromLocation(lat, lng, 1);
              } catch (IOException e) {
                  e.printStackTrace();
              }
              Address address = list.get(0);

              String sublocality = address.getSubLocality();


              // Setting the title for the marker.
              // This will be displayed on taping the marker
              markerOptions.title(sublocality);

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

              // Animating to the touched position
              mMap.animateCamera(CameraUpdateFactory.newLatLng(point));

              // Placing a marker on the touched position
              mMap.addMarker(markerOptions);

          }
      });


  }

  private void enableMyLocation() {


      if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
              != PackageManager.PERMISSION_GRANTED) {
          // Permission to access the location is missing.
          PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                  Manifest.permission.ACCESS_FINE_LOCATION, true);
      } else if (mMap != null) {
          // Access to the location has been granted to the app.
          mMap.setMyLocationEnabled(true);
      }

  }

  @Override
  public boolean onMyLocationButtonClick() {
      Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
      // Return false so that we don't consume the event and the default behavior still occurs
      // (the camera animates to the user's current position).
      return false;
  }

  @Override
  public void onMyLocationClick(@NonNull Location location) {
      Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                        @NonNull int[] grantResults) {

      if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
          return;
      }

      if (PermissionUtils.isPermissionGranted(permissions, grantResults,
              Manifest.permission.ACCESS_FINE_LOCATION)) {
          // Enable the my location layer if the permission has been granted.
          enableMyLocation();
      } else {
          // Display the missing permission error dialog when the fragments resume.
          mPermissionDenied = true;
      }
  }

  @Override
  protected void onResumeFragments() {
      super.onResumeFragments();
      if (mPermissionDenied) {
          // Permission was not granted, display error dialog.
          showMissingPermissionError();
          mPermissionDenied = false;
      }
  }

  /**
  * Displays a dialog with error message explaining that the location permission is missing.
  */
  private void showMissingPermissionError() {
      PermissionUtils.PermissionDeniedDialog
              .newInstance(true).show(getSupportFragmentManager(), "dialog");
  }
}

Upvotes: 0

Views: 492

Answers (1)

Shahil Islam
Shahil Islam

Reputation: 77

Guys, I have resolved it.

Add the following lines in your on create below SupportMapFragent.

View myLocationButton = mapFragment.getView().findViewById(0x2);

        if (myLocationButton != null && myLocationButton.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
            // location button is inside of RelativeLayout
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) myLocationButton.getLayoutParams();

            // Align it to - parent BOTTOM|LEFT
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);
            params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);

            // Update margins, set to 80dp
            final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80,
                    getResources().getDisplayMetrics());
            params.setMargins(margin, margin, margin, margin);

            myLocationButton.setLayoutParams(params);
        }

Upvotes: 1

Related Questions