How do you programmatically change the width & height of Google Maps v2 (support Fragment)?
Asked Answered
M

4

21

How do you programatically change the width and height of a com.google.android.gms.maps.SupportMapFragment? I'd imagine you might be able to wrap it in a viewgroup with match_parent, but I'm hoping not to nest if I don't have to (honestly not even sure it works).

 <fragment xmlns:android="http://schemas.android.com/apk/res/android"
                    android:id="@+id/storefront_map"
                    class="com.google.android.gms.maps.SupportMapFragment"
                    android:layout_width="match_parent"
                    android:layout_height="250dp"
                    />

To give context, I'd like to expand the map from one height to another on map click.

mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
    @Override
    public void onMapClick(LatLng latLng) {
       expandMap(); // not sure how to do this programatically.
    }
});

Any help would be great!

Mattern answered 30/1, 2014 at 23:6 Comment(0)
M
41

I figured it out largely with the help of Programmatically set google map fragment visibility (API2).

mMapFragment = (SupportMapFragment) (getSupportFragmentManager()
            .findFragmentById(R.id.storefront_map));
ViewGroup.LayoutParams params = mMapFragment.getView().getLayoutParams();
params.height = 900;
mMapFragment.getView().setLayoutParams(params);
Mattern answered 31/1, 2014 at 15:29 Comment(0)
R
4

this is an example using onConfigurationChanged() method :

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setContentView(R.layout.main);
    findViewById(R.id.storefront_map).getLayoutParams().width = 400;
}
Richert answered 30/1, 2014 at 23:22 Comment(1)
I updated my question to give better context of what I want to do.Mattern
F
3

Fastest (with less code lines) way i found:

ViewGroup.MarginLayoutParams parms = (ViewGroup.MarginLayoutParams) rlLocation.getLayoutParams();
    parms.bottomMargin = 100;
    parms.topMargin = 100;
Fletcherfletcherism answered 3/4, 2017 at 16:23 Comment(1)
You normally would want to resize the map to accommodate another element. If the element has a fixed size, like it was in my case, setting a margin to the size of the inserted element is preferable. Good tip, thank you.Merriemerrielle
D
1

You should not fix height of a map... set it according to screen height & width.

DisplayMetrics displaymetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int height = displaymetrics.heightPixels;

        ViewGroup.LayoutParams params = mMapFragment.getView().getLayoutParams();
        params.height = height/2;
        mMapFragment.getView().setLayoutParams(params);
Destroyer answered 4/11, 2016 at 12:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.