【发布时间】:2023-03-31 18:51:01
【问题描述】:
我希望在定位服务禁用或从 GPS 更改为无线或无线更改为 GPS 时显示地图。我尝试了更多,但应用程序崩溃了。
任何帮助将不胜感激。提前谢谢你。
java代码
if (servicesOK()) {
setContentView(R.layout.map);
if (initMap()) {
Toast.makeText(this, "Ready to map", Toast.LENGTH_SHORT).show();
gotoLocation();
} else {
Toast.makeText(this, "Map not available", Toast.LENGTH_SHORT)
.show();
}
} else {
setContentView(R.layout.activity_error);
}
}
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable,
this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, "can't connect to Google Play Services",
Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean initMap() {
if (Gmap == null) {
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
Gmap = mapFrag.getMap();
}
return (Gmap != null);
}
private void gotoLocation() {
// Enable my location layer of Google map
Gmap.setMyLocationEnabled(true);
// get LocationManger object from system service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// create criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
Gmap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Get latitude of the current location
double latitude = myLocation.getLatitude();
// Get longitude of the current location
double longitude = myLocation.getLongitude();
// create latlng object for the current location
LatLng latlng = new LatLng(latitude, longitude);
}
【问题讨论】:
-
我现在也遇到了同样的问题,请问您解决了吗?请更新我们。
标签: android gps google-maps-api-2