Изменить положение кнопки Google Maps "Мое местоположение"
Я использую Google Maps Android API v2, и мне нужен способ случайно разместить кнопку "Мое местоположение".
Я получаю кнопку "Мое местоположение" следующим образом:
GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
final GoogleMap map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
// This gets the button
map.setMyLocationEnabled(true);
Ответы
Ответ 1
Просто используйте GoogleMap.setPadding(левый, верхний, правый, нижний), который позволяет указать части карты, которые могут быть скрыты другими видами. Настройка дополнений переупорядочивает стандартные элементы управления картой, а обновления камеры будут использовать дополненную область.
https://developers.google.com/maps/documentation/android/map#map_padding
Ответ 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);
}
}
Ответ 3
Это может быть не лучшее решение, но вы можете разместить свою собственную кнопку над картой и обработать ее самостоятельно. Это потребует: -
1) Поместите карту в frameLayout и добавьте свою кнопку сверху. Например.
<FrameLayout
android:id="@+id/mapFrame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/mapFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.MapFragment"
map:mapType="normal"
map:uiCompass="true" />
<ImageButton
android:id="@+id/myMapLocationButton"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_gravity="bottom|right"
android:background="@drawable/myMapLocationDrawable"
android:contentDescription="My Location" />
</FrameLayout>
2) Отредактируйте настройки UI карт, чтобы кнопка не появлялась при вызове setMyLocationEnabled (true). Вы можете сделать это через map.getUiSettings(). setMyLocationButtonEnabled (ложь);
3) Обращайтесь с кликом новой кнопки, чтобы подражать тому, что делает кнопка. Например. вызвать mMap.setMyLocationEnabled(...); и скопируйте карту в текущее местоположение.
Надеюсь, что это поможет, или надеюсь, что кто-то придет долго с более простым решением для вас; -)
Ответ 4
Это уже объяснено выше. Просто небольшое дополнение к ответу fabLouis.
Вы также можете получить свой вид карты из SupportMapFragment.
/**
* Move the button
*/
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().
findFragmentById(R.id.map);
View mapView = mapFragment.getView();
if (mapView != null &&
mapView.findViewById(1) != null) {
// Get the button view
View locationButton = ((View) mapView.findViewById(1).getParent()).findViewById(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);
}
Ответ 5
Мне не кажется, что эти волшебные ID-идентификаторы используются, я предлагаю использовать теги для поиска MapView
children.
Вот мое решение для размещения кнопки Мое местоположение над элементами управления Масштабирование.
// Get map views
View location_button =_mapView.findViewWithTag("GoogleMapMyLocationButton");
View zoom_in_button = _mapView.findViewWithTag("GoogleMapZoomInButton");
View zoom_layout = (View) zoom_in_button.getParent();
// adjust location button layout params above the zoom layout
RelativeLayout.LayoutParams location_layout = (RelativeLayout.LayoutParams) location_button.getLayoutParams();
location_layout.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
location_layout.addRule(RelativeLayout.ABOVE, zoom_layout.getId());
Ответ 6
Я решил эту проблему в своем фрагменте карты, переместив мою кнопку местоположения в правый нижний угол обзора с помощью кода ниже, вот мои Maps Activity.java: -
добавьте эти строки кода в метод onCreate(),
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapView = mapFragment.getView();
mapFragment.getMapAsync(this);
и вот код onMapReady(): -
@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);
}
}
Надеюсь, это решит вашу проблему. Спасибо.
Ответ 7
См. метод ниже. Он живет внутри класса, который расширяет SupportMapFragment. Он отображает вид контейнера для кнопки и отображает его внизу, в центре по горизонтали.
/**
* Move my position button at the bottom of map
*/
private void resetMyPositionButton()
{
//deep paths for map controls
ViewGroup v1 = (ViewGroup)this.getView();
ViewGroup v2 = (ViewGroup)v1.getChildAt(0);
ViewGroup v3 = (ViewGroup)v2.getChildAt(0);
ViewGroup v4 = (ViewGroup)v3.getChildAt(1);
//my position button
View position = (View)v4.getChildAt(0);
int positionWidth = position.getLayoutParams().width;
int positionHeight = position.getLayoutParams().height;
//lay out position button
RelativeLayout.LayoutParams positionParams = new RelativeLayout.LayoutParams(positionWidth,positionHeight);
int margin = positionWidth/5;
positionParams.setMargins(0, 0, 0, margin);
positionParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
positionParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
position.setLayoutParams(positionParams);
}
Ответ 8
Во-первых, получите представление в Google Картах:
View mapView = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getView();
Затем найдите кнопку MyLocation (идентификатор от отладчика Android Studio):
View btnMyLocation = ((View) mapView.findViewById(1).getParent()).findViewById(2);
Наконец, просто установите новые параметры RelativeLayout для кнопки MyLocation (в этом случае выровняйте родительский правый + центр по вертикали):
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(80,80); // size of button in dp
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
params.setMargins(0, 0, 20, 0);
btnMyLocation.setLayoutParams(params);
Boom! Теперь вы можете перемещать его по своему желанию;)
Ответ 9
Если вы просто хотите включить индикацию местоположения (синяя точка), но не нужно использовать кнопку "Мое местоположение" по умолчанию:
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
Таким образом вы можете также нарисовать свою собственную кнопку, где хотите, без странных вещей вроде mapView.findViewById(1).getParent())
.
Ответ 10
У меня была та же проблема. В итоге я использовал средство просмотра иерархии, чтобы идентифицировать представление, используемое для отображения кнопки, и манипулировать ею. Очень хриплый, я знаю, но не мог понять по-другому.
Ответ 11
Это была битва, чтобы заставить эту работу работать. Но я сделал это, и в этом процессе также начали перемещать кнопки масштабирования. Вот мой полный код:
package com.squirrel.hkairpollution;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.LatLng;
public class MySupportMapFragment extends SupportMapFragment {
private static final String TAG = HKAirPollution.TAG;
public MySupportMapFragment() {
return;
}
@Override
public View onCreateView(LayoutInflater arg0, ViewGroup arg1, Bundle arg2) {
Log.v(TAG, "In overridden onCreateView.");
View v = super.onCreateView(arg0, arg1, arg2);
Log.v(TAG, "Initialising map.");
initMap();
return v;
}
@Override
public void onViewCreated (View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
resetButtons();
}
private void initMap(){
UiSettings settings = getMap().getUiSettings();
settings.setAllGesturesEnabled(true);
settings.setMyLocationButtonEnabled(true);
LatLng latLong = new LatLng(22.320542, 114.185715);
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(latLong,11));
}
/**
* Move my position button at the bottom of map
*/
private void resetButtons()
{
// Get a reference to the zoom buttons and the position button.
ViewGroup v1 = (ViewGroup)this.getView();
ViewGroup v2 = (ViewGroup)v1.getChildAt(0);
ViewGroup v3 = (ViewGroup)v2.getChildAt(0);
ViewGroup v4 = (ViewGroup)v3.getChildAt(1);
// The My Position button
View position = (View)v4.getChildAt(0);
int positionWidth = position.getLayoutParams().width;
int positionHeight = position.getLayoutParams().height;
// Lay out the My Position button.
RelativeLayout.LayoutParams positionParams = new RelativeLayout.LayoutParams(positionWidth,positionHeight);
int margin = positionWidth/5;
positionParams.setMargins(0, 0, 0, margin);
positionParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
positionParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
position.setLayoutParams(positionParams);
// The Zoom buttons
View zoom = (View)v4.getChildAt(2);
int zoomWidth = zoom.getLayoutParams().width;
int zoomHeight = zoom.getLayoutParams().height;
// Lay out the Zoom buttons.
RelativeLayout.LayoutParams zoomParams = new RelativeLayout.LayoutParams(zoomWidth, zoomHeight);
zoomParams.setMargins(0, 0, 0, margin);
zoomParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
zoomParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
zoom.setLayoutParams(zoomParams);
}
}
Ответ 12
Один из способов решения этой проблемы. Удалите кнопку по умолчанию и создайте свой собственный.
В операторе OnCreate добавьте следующее:
GoogleMap mMap = ((MapView) inflatedView.findViewById(R.id.mapview)).getMap();
LocationManager locationManager =
(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 2000, 1, this);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false); // delete default button
Imagebutton imgbtn = (ImageButton) view.findViewById(R.id.imgbutton); //your button
imgbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng(location.getLatitude(),
location.getLongitude()), 15));
}
});
Ответ 13
попробуйте этот код
private void resetMyPositionButton()
{
Fragment fragment = ( (SupportMapFragment) getSupportFragmentManager().findFragmentById( R.id.map ) );
ViewGroup v1 = (ViewGroup) fragment.getView();
ViewGroup v2 = (ViewGroup)v1.getChildAt(0);
ViewGroup v3 = (ViewGroup)v2.getChildAt(2);
View position = (View)v3.getChildAt(0);
int positionWidth = position.getLayoutParams().width;
int positionHeight = position.getLayoutParams().height;
//lay out position button
RelativeLayout.LayoutParams positionParams = new RelativeLayout.LayoutParams(positionWidth,positionHeight);
int margin = positionWidth/5;
positionParams.setMargins(margin, 0, 0, margin);
positionParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
positionParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
position.setLayoutParams(positionParams);
}
Ответ 14
До этого, вы можете удалить старое правило кнопки:
@Override
public void onMapReady(final GoogleMap googleMap) {
this.map = googleMap;
// Show location button
View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
// position on right bottom
Log.l(Arrays.toString(rlp.getRules()), L.getLogInfo());
int[] ruleList = rlp.getRules();
for (int i = 0; i < ruleList.length; i ++) {
rlp.removeRule(i);
}
Log.l(Arrays.toString(rlp.getRules()), L.getLogInfo());
//Do what you want to move this location button:
rlp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
}
Ответ 15
Вы можете использовать следующий подход:
View myLocationParent = ((View) getView().findViewById(1).getParent());
View myLocationParentParent = ((View) myLocationParent.getParent());
// my position button
int positionWidth = myLocationParent.getLayoutParams().width;
int positionHeight = myLocationParent.getLayoutParams().height;
// lay out position button
FrameLayout.LayoutParams positionParams = new FrameLayout.LayoutParams(
positionWidth, positionHeight);
positionParams.setMargins(0, 100, 0, 0);
myLocationParent.setLayoutParams(positionParams);
Ответ 16
Я добавил строку к своему фрагменту андроида: layout_marginTop ="атр/actionBarSize?"
Это помогло мне
Ответ 17
используйте это для нижнего правого местоположения
map.setMyLocationEnabled(true);
map.setPadding(0,1600,0,0);