我需要使用gps显示用户当前位置。在启动时它会在海中显示一些随机位置,当我点击gps图标时,它会显示我当前的位置(带有光学图标的白色圆圈)。 如何在启动时显示?我是android / java的新手,所以随时都可以纠正我。
我的代码是:
public class MainMapsActivity extends FragmentActivity implements android.location.LocationListener {
GoogleMap googleMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_maps);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
@Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
}
答案 0 :(得分:3)
创建Location类的数据成员。
public static Location mLocation;
在地图上使用OnMyLocationChangeListener
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
mLocation = location;
displayCurrentLocation();
}
});
public void displayCurrentLocation(){
CameraPosition cameraPosition = new CameraPosition.Builder().
target(new LatLng(mLocation.getLatitude(), mLocation.getLongitude())).
tilt(60).
zoom(15).
bearing(0).
build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
希望它能起作用。
答案 1 :(得分:1)