I am writing an application in android using Google map-V2 API. I want to over lay action bar just as in the Google map application. And I enabled "My Location " button. The problem now is that my location button is under the action bar. Is there any way to re-position this button. I want to make an app some what similar to Maps. I am new to android so please help.
You can set padding to the map.
This solved the problem - overlays over the map on the top (I used 48 dips, but you can overlay action bar and then get actual height of it (?android:attr/actionBarSize))
mapFragment.getMap().setPadding(0, dpToPx(48), 0, 0);
(DP to PX function is from this SO answer)
You can reposition your location button easily
View plusMinusButton = suppormanagerObj.getView().findViewById(1);
View locationButton = suppormanagerObj.getView().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);
you can also set padding after setting alignment of the location button
mMap.setPadding(0, 0, 30, 105);
You can not alter the MyLocationButton in any way, but enable and disable it. There is already a request for this.
Feel free to disable the button and just implement your own one.
You would have something like this:
mMap.getUiSettings().setMyLocationButtonEnabled(false);
I solved this problem in my map fragment by re positioning my location button to the right bottom corner of view using code below,
here is my Maps Activity.java :-
add this lines of code in onCreate() method,
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapView = mapFragment.getView();
mapFragment.getMapAsync(this);
and here is onMapReady() code :-
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
if (mapView != null &&
mapView.findViewById(Integer.parseInt("1")) != null) {
// Get the button view
View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
// and next place it, on bottom right (as Google Maps app)
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
// position on right bottom
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 30, 30);
}
}
I hope, this will solve your problem. Thanks.
Instead of the findViewById solutions, I used the findViewWithTag to get a reference to the button. Using a string seemed more readable and reliable to me.
View myLocationButton = mMap.findViewWithTag("GoogleMapMyLocationButton");
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) myLocationButton.getLayoutParams();
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
Just use GoogleMap.setPadding(left, top, right, bottom), which allows you to indicate parts of the map that may be obscured by other views. Setting padding re-positions the standard map controls, and camera updates will use the padded region.
https://developers.google.com/maps/documentation/android/map#map_padding
Related
I have this code
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(mainLocation);
builder.include(userLocation);
LatLngBounds bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 0);
mMap.animateCamera(cu);
And this works it shows bounds but i would like to show bounds on the top half of the screen (is there a way to put offset y?).
(Hope this picture will explain things better)
If I understand you correctly, what you get now is that map is centered, meaning your provided locations are centered on the map. And you want those locations to be on the upper part of the screen.
It seems there is not such an API, that would allow to apply padding to bottom only.
You can add a fake location to LatLngBounds.Builder at the lower part of the screen, now the CameraUpdate would include that point also, which will shift your 2 real points on the upper part.
You can use the setPadding method from the GoogleMap object.
In your case you will need to add a bottom padding:
mMap.setPadding(0, 0, 0, 150);
Maybe late, but i solved this. I make bottom padding for map, before call animateCamera, and return padding after update.
val heightValue = (Resources.getSystem().displayMetrics.heightPixels * 0.5).toInt()
map.setPadding(0,0,0,heightValue)
val update = CameraUpdateFactory.newLatLngBounds(bounds,50)
map.animateCamera(update,object:GoogleMap.CancelableCallback{
override fun onFinish() {
inUi {
map.setPadding(0,0,0,0)
}
}
override fun onCancel() {}
})
Here is the best solution I found to achieve this effect.
You force the padding you need before animating the camera, and immediately after, you reset the padding to whatever ever value.
map.setPadding(left, top, right, bottom) // In your example, this will be the only non-zero value.
animateCamera(cameraUpdate) // Trigger the animation
map.setPadding(0, 0, 0, 0) // Reset the padding
I am using Mapbox android sdk for my map application, i want to use pointer icon('myIcon' in this case) which always points in the direction where user is moving.
I here is my code :
public void addMarker(MapboxMap mapboxmap) {
// marker view options : setting location and icon
MarkerViewOptions options = new MarkerViewOptions()
.position(latLng)
.anchor(0.5f, 0.5f)
.icon(myIcon);
MarkerView view = options.getMarker();
// added marker on map
mapboxMap.addMarker(options);
}
With marker views we don't expose a way to do this, and your only option is to adjust the marker rotation when the camera is rotated. A better solution would be to use runtime styling and a symbol layer. An example of this can be found in our demo app. To ensure that the marker always points in the correct direction you can use the icon-rotation-alignment property and set it to map. Hope this helps!
Setting rotation on location update {like setRotation(angle_you_want_to_set)} worked of me.
Example :
public void addMarker(MapboxMap mapboxmap, float angle) {
// marker view options : setting location and icon
MarkerViewOptions options = new MarkerViewOptions()
.position(latLng)
.anchor(0.5f, 0.5f)
//set angle of ration for icon
.setRotation(angle)
.icon(myIcon);
MarkerView view = options.getMarker();
// added marker on map
mapboxMap.addMarker(options);
}
I'am using maps api v2 in my app. I have to show my current location and target location on the map such that both the locations are visible (at the greatest possible zoom level) on the screen. Here is what i have tried so far...
googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapFragment)).getMap();
if(googleMap != null){
googleMap.setMyLocationEnabled(true);
LatLng targetLocationLatLng = new LatLng(modelObject.getLattitude(), modelObject.getLongitude());
LatLng currentLocationLatLng = new LatLng(this.currentLocationLattitude, this.currentLocationLongitude);
googleMap.addMarker(new MarkerOptions().position(targetLocationLatLng).title(modelObject.getLocationName()).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon)));
LatLngBounds bounds = new LatLngBounds(currentLocationLatLng, targetLocationLatLng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 3));
}
App is force closing due to the following :
java.lang.IllegalStateException: Map size should not be 0. Most likely, layout has not yet occured for the map view.
How can i get max possible zoom level? Please help me.
In my project I use the com.google.android.gms.maps.model.LatLngBounds.Builder
Adapted to your source code it should look something like this:
Builder boundsBuilder = new LatLngBounds.Builder();
boundsBuilder.include(currentLocationLatLng);
boundsBuilder.include(targetLocationLatLng);
// pan to see all markers on map:
LatLngBounds bounds = boundsBuilder.build();
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 3));
A good method to avoid this problem is to use a ViewTreeObserver to the layout containing the map fragment and a listener, to ensure that the layout has first been initialised (and hasn't a width=0) using addOnGlobalLayoutListener, as below:
private void zoomMapToLatLngBounds(final LinearLayout layout,final GoogleMap mMap, final LatLngBounds bounds){
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds,OVERVIEW_MAP_PADDING));
}
});
}
This question already has answers here:
Change position of Google Maps API's "My location" button
(17 answers)
Closed 4 years ago.
I have added a map fragment (API v2) to my app with the map covering the whole screen and a semi-transparent actionbar on top.
The activity uses a theme with android:windowActionBarOverlay set to true.
I have also enabled the "MyLocationButton" on the map, but since the map covers the full height of the screen, the button is covered by the action bar.
How can I make the map fragment draw the location button below the action bar or at the bottom of the screen instead?
Instead of creating your own button, just move the build in button according to the action bar size.
This code works for me and the button is just where the button should be (like in google maps):
// Gets the my location button
View myLocationButton = getSherlockActivity().findViewById(R.id.MainContainer).findViewById(2);
// Checks if we found the my location button
if (myLocationButton != null){
int actionBarHeight = 0;
TypedValue tv = new TypedValue();
// Checks if the os version has actionbar in it or not
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
if (getSherlockActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
// Before the action bar was added to the api
else if(getSherlockActivity().getTheme().resolveAttribute(com.actionbarsherlock.R.attr.actionBarSize, tv, true)){
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
// Sets the margin of the button
ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(myLocationButton.getLayoutParams());
marginParams.setMargins(0, actionBarHeight + 20, 20, 0);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
myLocationButton.setLayoutParams(layoutParams);
}
Just put this code in the onActivityCreated (if you will put it in the onCreateOptionsMenu, it will not support version before 3.0 - because the life cycle there is different.
Another thing, the "R.id.MainContainer" is the container of the map fragment.
I'm using ActionBar Sherlock, but it will work also for regular action bar with a few modifications..
Below (especially in fixMapControlLocations) i've addressed this with ActionBarSherlock.
Issues I had were on narrow screens, and the split action bar having the wrong offset depending on rotation. The isNarrow check through sherlock lets me know if its narrow.
Another key change is i'm setting the padding of the myLocation's parent's parent view. This picks up all controls inside, and based on hierarchyviewer is how google maps is doing it. The Google attribution logo is on the next parent up the tree in a Surface object. Not looking like that is easily movable, so i'm probably just going to end up loosing the bottom action bar's transparency effect to stay in compliance.
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
setUpMapIfNeeded();
getSupportActionBar().setBackgroundDrawable(d);
getSupportActionBar().setSplitBackgroundDrawable(d);
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getExtendedMap();
// Check if we were successful in obtaining the map.
if (map != null) {
setUpMap();
}
}
}
private void setUpMap() {
fixMapControlLocations();
.....
}
private void fixMapControlLocations() {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
int actionBarHeight = 0;
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}
View myLocationParent = ((View)mapFragment.getView().findViewById(1).getParent());
View myLocationParentParent = ((View)myLocationParent.getParent());
myLocationParentParent.setPadding(0, actionBarHeight, 0, isNarrow()?actionBarHeight:0);
}
public boolean isNarrow() {
return ResourcesCompat.getResources_getBoolean(getApplicationContext(),
R.bool.abs__split_action_bar_is_narrow);
}
You can accomplish this with the recently-added GoogleMap.setPadding() method:
map.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
From the API docs:
This method allows you to define a visible region on the map, to signal to the map that portions of the map around the edges may be obscured, by setting padding on each of the four edges of the map. Map functions will be adapted to the padding. For example, the zoom controls, compass, copyright notices and Google logo will be moved to fit inside the defined region, camera movements will be relative to the center of the visible region, etc.
Also see the description of how padding works in GoogleMap.
This has already been filed as an enhancement (please star it if you haven't already) http://code.google.com/p/gmaps-api-issues/issues/detail?id=4670
As a temporary workaround I have added my own find location button below the actionbar (my map fragment is in a RelativeLayout so I just did alignParentRight and set appropriate margin top).
Then in my onClickHandler I did this:
public void onClickHandler(View target) {
switch (target.getId()) {
case R.id.my_fml_btn:
mMap.setMyLocationEnabled(true);
View fmlBtn = mMapWrapper.findViewById(2); //mMapWrapper is my RelativeLayout
if (fmlBtn != null) fmlBtn.setVisibility(View.INVISIBLE);
break;
}
}
I used hierarchyviewer to find the id of the button that was added by the maps api. It just happens to be the 2nd view added to the map (and set to invisible).
You can of course you can fiddle about with LayoutParams to offset this button rather than hide it but this button only appears after you setMyLocationEnabled to true! (in my use case I prefer to let the user decide before firing up the gps)
Make sure you use ?android:attr/actionBarSize (or ?attr/actionBarSize if you're using ActionBarSherlock) to correctly offset the content of the fragment.
Depending of the effect you're trying to accomplish, either apply this value as margin or padding. I'm guessing that because of the semi-transparant ActionBar, you'll want to try padding, in order to still have the map appear behind it (and keep the see-through effect). I'm just not 100% sure whether padding will actually move the 'Locate me' button down... If not, then probably applying a margin is your only other option.
See here for an example and more details on this attribute.
How can i customize the position of the builtin zoom controls in a GoogleMap V2 ?
There are a lot of questions related to this topic for the Version 1 of Google Maps library.
Placing Zoom Controls in a MapView
How to reposition built-in zoom controls in MapView?
How to layout zoom Control with setBuiltInZoomControls(true)?
However, i wasn't able to find any questions in relation to the V2 of the library.
In the V2, there's no method
(LinearLayout) mapView.getZoomControls();
all the previously mentioned questions becomes obsolete.
Thanks in advance
Depending on what you're trying to do, you might find GoogleMap.setPadding() useful (added in September 2013).
map.setPadding(leftPadding, topPadding, rightPadding, bottomPadding);
From the API docs:
This method allows you to define a visible region on the map, to signal to the map that portions of the map around the edges may be obscured, by setting padding on each of the four edges of the map. Map functions will be adapted to the padding. For example, the zoom controls, compass, copyright notices and Google logo will be moved to fit inside the defined region, camera movements will be relative to the center of the visible region, etc.
Also see the description of how padding works in GoogleMap.
Yes, you can change position of ZoomControl and MyLocation button with small hack.
In my sample I have SupportMapFragment, which is inflated from xml layout.
View ids for ZoomControl and MyLocation button:
ZoomControl id = 0x1
MyLocation button id = 0x2
Code to update ZoomControl position:
// Find map fragment
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
// Find ZoomControl view
View zoomControls = mapFragment.getView().findViewById(0x1);
if (zoomControls != null && zoomControls.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
// ZoomControl is inside of RelativeLayout
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) zoomControls.getLayoutParams();
// Align it to - parent top|left
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
// Update margins, set to 10dp
final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,
getResources().getDisplayMetrics());
params.setMargins(margin, margin, margin, margin);
}
I use MapFragment not SupportMapFragment:
import android.util.TypedValue;
in onCreate
// Find map fragment
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapview);
int ZoomControl_id = 0x1;
int MyLocation_button_id = 0x2;
// Find ZoomControl view
View zoomControls = mapFragment.getView().findViewById(ZoomControl_id);
if (zoomControls != null && zoomControls.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
// ZoomControl is inside of RelativeLayout
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) zoomControls.getLayoutParams();
// Align it to - parent top|left
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
// Update margins, set to 10dp
final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,
getResources().getDisplayMetrics());
params.setMargins(margin, margin, margin, margin);
}
Just for the record:
Navigation-controls are 0x4
So in total:
#LayoutRes final int ZOOM_CONTROL_ID = 0x1;
#LayoutRes final int MY_LOCATION_CONTROL_ID = 0x2;
#LayoutRes final int NAVIGATION_CONTROL_ID = 0x4;