我是一个非常庞大的工作应用,我在myLocation
中实施了MapLocation.class
,扩展了片段。
一切都工作正常,我的整个标记列表显示完美,但在myLocation
实施后,出现了一个奇怪的情况。
首次运行/安装条件(卸载前一个或清除数据后),标记会完美显示,但myLocation
无效,myLocation
图标也无法显示,即使是请求许可。
在第二次通过工作室或在从最近清除后再次启动应用程序时,位置与其位置上的图标完美匹配,但标记变得不可见。隐身,因为相机专注于Marker的位置,而不是代码中的myLocation
。
代码如下:
public class MetroLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
MapView mMapView;
private GoogleMap googleMap;
ArrayList<Double> arLat = new ArrayList<>();
ArrayList<Double> arLong = new ArrayList<>();
ArrayList<String> arName=new ArrayList<>();
ArrayList<String> arLine = new ArrayList<>();
double lng;
double lat;
LatLng latLng;
Marker mCurrLocation;
Location mLastLocation;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
private Cursor Lat;
private Cursor Long;
private Cursor Stations;
private MyDatabase db;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_metro_location, container, false);
mMapView = v.findViewById(R.id.mapLocation);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
db = new MyDatabase(getActivity());
Lat = db.getLat();
Long = db.getLong();
Stations = db.getStation();
Cursor line = db.getMetroLine();
for(Lat.moveToFirst(); !Lat.isAfterLast(); Lat.moveToNext()) {
arLat.add(Lat.getDouble(0));
}
for(Long.moveToFirst(); !Long.isAfterLast(); Long.moveToNext()) {
arLong.add(Long.getDouble(0));
}
for(Stations.moveToFirst(); !Stations.isAfterLast(); Stations.moveToNext()) {
arName.add(Stations.getString(0));
}
for(line.moveToFirst(); !line.isAfterLast(); line.moveToNext()) {
arLine.add(line.getString(0));
}
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(this);
return v;
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
@Override
public void onDestroy() {
super.onDestroy();
Lat.close();
Long.close();
Stations.close();
db.close();
mMapView.onDestroy();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocation != null) {
mCurrLocation.remove();
}
latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setSmallestDisplacement(2F);
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
googleMap.clear();
latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocation = googleMap.addMarker(markerOptions);
}
if (ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {
Toast.makeText(getActivity(),"Connection Suspended",Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(getActivity(),"Connection Failed",Toast.LENGTH_SHORT).show();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
googleMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
}
}
}
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
for(int j= 0;j<arLat.size();j++) {
double lat1 = arLat.get(j);
double long1 = arLong.get(j);
String name = arName.get(j);
String snippet = "Metro Station"+ " Line : " + arLine.get(j);
LatLng latLng = new LatLng(lat1, long1);
googleMap.addMarker(new MarkerOptions().position(latLng).title(name).snippet(snippet).flat(true).icon(
BitmapDescriptorFactory.fromResource(R.drawable.green)));
}
int i = arLat.size() / 2;
lat = arLat.get(i);
lng = arLong.get(i);
LatLng latLng1 = new LatLng(lat, lng);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng1).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
googleMap.setMyLocationEnabled(true);
} else {
checkLocationPermission();
}
} else {
buildGoogleApiClient();
googleMap.setMyLocationEnabled(true);
}
if (mMapView != null &&
mMapView.findViewById(Integer.parseInt("1")) != null) {
View locationButton = mMapView.findViewWithTag("GoogleMapMyLocationButton");
View locationButton1 = mMapView.findViewWithTag("GoogleMapCompass");
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 40, 253);
RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) locationButton1.getLayoutParams();
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0);
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_TOP,0);
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutParams1.bottomMargin = 100;
}
}
}
如果我的代码有错误,请提供帮助。
编辑 - 我已经体验到闪光灯会出现标记然后消失。其他一切都是一样的。此外,还需要重新启动位置,并显示该按钮。