如何使用 viewpager 在选项卡布局中添加地图?
How to add map in tab layout with viewpager?
MapFragment Image
我想用 viewpager 在选项卡布局中显示地图视图。正如您在图片上方看到的那样。我正在获取我的纬度和经度,但它没有显示我所在位置的地图和标记。
这是我的这个片段的代码class
public class MapFragment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private MapView mapView;
private static final int MY_PERMISSION_REQUEST_CODE = 0;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 1;
private LocationRequest mlocationRequest;
private GoogleApiClient mgoogleApiClient;
private Location mlastlocation;
private static int UPDATE_INTERVAL = 1000;
private static int FASTEST_INTERVAL = 3000;
private static int DISPLACEMENT = 10;
DatabaseReference ref;
GeoFire geofire;
Marker myCurrentMarker;
public MapFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_map, container, false);
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
ref = FirebaseDatabase.getInstance().getReference("MyLocation");
geofire = new GeoFire(ref);
setUpLocation();
return view;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
if (checkPlaySercives()) {
buildGoogleApiClient();
creatLocationRequest();
displayLocation();
}
}
break;
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PERMISSION_REQUEST_CODE);
} else {
if (checkPlaySercives()) {
buildGoogleApiClient();
creatLocationRequest();
displayLocation();
}
}
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
mlastlocation =
LocationServices.FusedLocationApi.getLastLocation(mgoogleApiClient);
if (mlastlocation != null) {
final double latitude = mlastlocation.getLatitude();
final double longitute = mlastlocation.getLongitude();
final LatLng latLng = new LatLng(latitude, longitute);
geofire.setLocation("You", new GeoLocation(latitude, longitute),
new GeoFire.CompletionListener() {
@Override
public void onComplete(String key, DatabaseError error)
{
if (myCurrentMarker != null)
myCurrentMarker.remove();
// mMap.addMarker(new
MarkerOptions().position(latLng).title("Your location"));
//
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
getLatitude(latitude);
getLongitude(getLongitude(longitute));
Toast.makeText(getActivity(), latitude + " "
+longitute, Toast.LENGTH_SHORT).show();
}
});
}
}
public static double getLatitude(double lat) {
return lat;
}
public static double getLongitude(double lng) {
return lng;
}
private void creatLocationRequest() {
mlocationRequest = new LocationRequest();
mlocationRequest.setInterval(UPDATE_INTERVAL);
mlocationRequest.setFastestInterval(FASTEST_INTERVAL);
mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mlocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void buildGoogleApiClient() {
mgoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mgoogleApiClient.connect();
}
private boolean checkPlaySercives() {
int resultCode =
GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
else {
Toast.makeText(getActivity(), "This device is not supported",
Toast.LENGTH_LONG).show();
}
return false;
}
return true;
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
@Override
public void onLocationChanged(Location location) {
mlastlocation = location;
displayLocation();
}
// @Override
// public void onStatusChanged(String provider, int status, Bundle
extras) {
//
// }
//
// @Override
// public void onProviderEnabled(String provider) {
//
// }
//
// @Override
// public void onProviderDisabled(String provider) {
//
// }
@Override
public void onConnected(@Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
}
private void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mgoogleApiClient,
mlocationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
mgoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
// @Override
// public void onResume() {
// mapView.onResume();
// super.onResume();
// }
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
此代码在 activity 上工作得很好,但在选项卡布局 viewpager 中出现问题。
提前致谢!
XML
中的地图视图
<com.google.android.gms.maps.MapView
android:id="@+id/my_test_map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Java代码:
private MapView mMapView;
private GoogleMap mGoogleMap;
...
...
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
mMapView = (MapView) findViewById(R.id.my_test_map);
mMapView.onCreate(getArguments());
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity());
final GoogleMap.OnMarkerClickListener markerClickListener = this;
mMapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap gmap) {
mGoogleMap = gmap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//fill markers
//add marker listener
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
这个示例代码来自我的一个项目,在片段中与 viewpager 一起工作得很好。
当我检查你的代码时,有一行你忘记调用了。
mMapView.onResume();
在您的 mapView.onCreate(savedInstanceState) 下添加此行;
MapFragment Image
我想用 viewpager 在选项卡布局中显示地图视图。正如您在图片上方看到的那样。我正在获取我的纬度和经度,但它没有显示我所在位置的地图和标记。 这是我的这个片段的代码class
public class MapFragment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private MapView mapView;
private static final int MY_PERMISSION_REQUEST_CODE = 0;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 1;
private LocationRequest mlocationRequest;
private GoogleApiClient mgoogleApiClient;
private Location mlastlocation;
private static int UPDATE_INTERVAL = 1000;
private static int FASTEST_INTERVAL = 3000;
private static int DISPLACEMENT = 10;
DatabaseReference ref;
GeoFire geofire;
Marker myCurrentMarker;
public MapFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_map, container, false);
mapView = (MapView) view.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
ref = FirebaseDatabase.getInstance().getReference("MyLocation");
geofire = new GeoFire(ref);
setUpLocation();
return view;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
if (checkPlaySercives()) {
buildGoogleApiClient();
creatLocationRequest();
displayLocation();
}
}
break;
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PERMISSION_REQUEST_CODE);
} else {
if (checkPlaySercives()) {
buildGoogleApiClient();
creatLocationRequest();
displayLocation();
}
}
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
mlastlocation =
LocationServices.FusedLocationApi.getLastLocation(mgoogleApiClient);
if (mlastlocation != null) {
final double latitude = mlastlocation.getLatitude();
final double longitute = mlastlocation.getLongitude();
final LatLng latLng = new LatLng(latitude, longitute);
geofire.setLocation("You", new GeoLocation(latitude, longitute),
new GeoFire.CompletionListener() {
@Override
public void onComplete(String key, DatabaseError error)
{
if (myCurrentMarker != null)
myCurrentMarker.remove();
// mMap.addMarker(new
MarkerOptions().position(latLng).title("Your location"));
//
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
getLatitude(latitude);
getLongitude(getLongitude(longitute));
Toast.makeText(getActivity(), latitude + " "
+longitute, Toast.LENGTH_SHORT).show();
}
});
}
}
public static double getLatitude(double lat) {
return lat;
}
public static double getLongitude(double lng) {
return lng;
}
private void creatLocationRequest() {
mlocationRequest = new LocationRequest();
mlocationRequest.setInterval(UPDATE_INTERVAL);
mlocationRequest.setFastestInterval(FASTEST_INTERVAL);
mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mlocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void buildGoogleApiClient() {
mgoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mgoogleApiClient.connect();
}
private boolean checkPlaySercives() {
int resultCode =
GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
else {
Toast.makeText(getActivity(), "This device is not supported",
Toast.LENGTH_LONG).show();
}
return false;
}
return true;
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
@Override
public void onLocationChanged(Location location) {
mlastlocation = location;
displayLocation();
}
// @Override
// public void onStatusChanged(String provider, int status, Bundle
extras) {
//
// }
//
// @Override
// public void onProviderEnabled(String provider) {
//
// }
//
// @Override
// public void onProviderDisabled(String provider) {
//
// }
@Override
public void onConnected(@Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
}
private void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mgoogleApiClient,
mlocationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
mgoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
// @Override
// public void onResume() {
// mapView.onResume();
// super.onResume();
// }
@Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
此代码在 activity 上工作得很好,但在选项卡布局 viewpager 中出现问题。
提前致谢!
XML
中的地图视图<com.google.android.gms.maps.MapView
android:id="@+id/my_test_map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Java代码:
private MapView mMapView;
private GoogleMap mGoogleMap;
...
...
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
mMapView = (MapView) findViewById(R.id.my_test_map);
mMapView.onCreate(getArguments());
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity());
final GoogleMap.OnMarkerClickListener markerClickListener = this;
mMapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap gmap) {
mGoogleMap = gmap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//fill markers
//add marker listener
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
这个示例代码来自我的一个项目,在片段中与 viewpager 一起工作得很好。
当我检查你的代码时,有一行你忘记调用了。
mMapView.onResume();
在您的 mapView.onCreate(savedInstanceState) 下添加此行;