我有一个带有mapView的活动。目前,我可以通过在代码中添加相应的经纬度来添加定位位置。
我很想让该应用用我现在的位置替换那些经久不衰的人。
我一直在尝试许多不同的方法,但是我不知道该怎么做。
我的代码如下:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
GoogleMap mMap
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Copenhagen and move the camera
LatLng Copenhagen = new LatLng(55.67594 , 12.56553);
mMap.addMarker(new MarkerOptions().position(Copenhagen).title("Marker in CBS"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(Copenhagen));
//zoom to position with level 15
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(Copenhagen, 15);
googleMap.animateCamera(cameraUpdate);
}
}
答案 0 :(得分:1)
使用此代码先获取您的当前位置:
public void getCurrentLocation() {
if (isPermisionAccess()) {
locationManager = (LocationManager) mActivity.getSystemService(LOCATION_SERVICE);
if (locationManager != null) {
Location gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location netLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gpsLocation != null) {
currentlatitude = gpsLocation.getLatitude();
currentlongitude = gpsLocation.getLongitude();
} else if (netLocation != null) {
currentlatitude = netLocation.getLatitude();
currentlongitude = netLocation.getLongitude();
}
}
}
}
private boolean isPermisionAccess() {
return (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
}
然后:
// Add a marker in myLocation and move the camera
LatLng myLocation = new LatLng(currentlatitude , currentlongitude );
mMap.addMarker(myLocation).title("Marker in CBS"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation ));
//zoom to position with level 15
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(myLocation , 15);
googleMap.animateCamera(cameraUpdate);
不要忘记:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />