Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save silentsudo/e61280e842a8654b8b09 to your computer and use it in GitHub Desktop.
Save silentsudo/e61280e842a8654b8b09 to your computer and use it in GitHub Desktop.
Android Maps v2 MyLocation Button Position

Change MyLocation button position

It's easy to enable Zoom and MyLocation buttons but annoying to change where they overlay the Map.

Options

  1. Use Map padding (are that will not overlap map controls)
  2. Disable them and implement your own (probably safer than hack below)
  3. Find the buttons by id and alter the layout params

Resources:

Example 1:

 private void setUpMap() {
 
    // Find myLocationButton view
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    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 10dp
        final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,
              getResources().getDisplayMetrics());
        params.setMargins(margin, margin, margin, margin);
        
        myLocationButton.setLayoutParams(params);
    }
}

Example 2:

public class MapFragment extends SupportMapFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View mapView = super.onCreateView(inflater, container, savedInstanceState);   
      
        // Get the button view 
        View locationButton = ((View) mapView.findViewById(1).getParent()).findViewById(2);
      
        // and next place it, for exemple, on bottom right (as Google Maps app)
        RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
      
        // position on right bottom
        rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
        rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        rlp.setMargins(0, 0, 30, 30);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment