我创建了一个Android活动来显示Google地图。 我会将地图置于当前用户位置的中心,但我无法弄清楚如何去做。
这是我目前的代码:
Location location = getMyLocation();
LatLng userPos = new LatLng(location.getLatitude(), location.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(userPos, zoomLevel));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(userPos)
.zoom(17)
.bearing(90)
.tilt(40)
.build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
此代码的来源是answer(我从中复制了getMyLocation())和此solution,但它们不起作用。在这两种情况下它根本不起作用:中心没有设置,很奇怪也没有设置缩放级别。
如果我只使用此代码(没有当前用户位置):
map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(42.564241, 12.22759), zoomLevel));
即使设置了缩放级别,它也没有问题。
可能是什么问题?
答案 0 :(得分:1)
确保您拥有以下权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
然后进行一些活动并注册LocationListener
package com.example.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class LocationActivity extends SherlockFragmentActivity implements
LocationListener {
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
map = ((SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME, MIN_DISTANCE, this); //You can also use
LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override
public void onProviderEnabled(String provider) { }
@Override
public void onProviderDisabled(String provider) { }
}'