【发布时间】:2017-04-05 10:29:23
【问题描述】:
我正在尝试在我的应用内的 Google 地图片段中添加“我的位置”按钮。到目前为止,这是我的代码:
package com.example.sander.app;
公共类 GoogleMaps 扩展 Fragment 实现 OnMapReadyCallback {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_gmaps, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MapView mapView = (MapView) view.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
mapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mapView.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng marker = new LatLng(51.9244201, 4.4777325);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(marker, 12));
googleMap.addMarker(new MarkerOptions().title("Testing").position(new LatLng(53.92, 4.47)));
googleMap.addMarker(new MarkerOptions().title("Hello Google Maps!").position(marker));
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true); // This is how I had implemented the setMyLocationEnabled method
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
}
}
我已经将权限添加到我的 AndroidManifest.xml 和 googleMap.setMyLocationEnable(true);不起作用。
谁能帮我将按钮添加到我的 Google 地图片段中
【问题讨论】:
-
地图中的位置按钮 googleMap.setMyLocationEnabled(true);应该工作
-
您能发布一下您是如何实现 setMyLocationEnable(true) 的吗?您在 Manifest 中添加了哪些权限?
-
我已将其添加到代码中
-
只是为了确定,但您是否检查过 MapReady 上的方法是否会被调用?
-
@MichaelMeyer 我不知道。我确实知道我的地图显示在我的应用程序中并且放置标记有效!
标签: android google-maps android-fragments