我的代码完全没问题,我想在应用程序打开后立即在地图上获取用户位置。但该应用程序崩溃了。此外,该程序设置为更新位置并在其更改时添加标记,该标记也不起作用。这是代码
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
String provider;
@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);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Location location= locationManager.getLastKnownLocation(provider);
double lat =location.getLatitude();
double lng =location.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("Marker"));
// Add a marker and move the camera
}
@Override
public void onLocationChanged(Location location) {
Double lat = location.getLatitude();
Double lng = location.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 10));
Log.i("Latitude", lat.toString());
}
答案 0 :(得分:0)
试试这个。 如果位置在缓存中,则getLastKnownLocation返回,否则返回null 在那里添加支票
if(location!=null)
{
double lat =location.getLatitude();
double lng =location.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat,lng)).title("Marker"));
}
2解决方案使用google play services fusedlocation api以便更好地管理位置,请参阅此处http://coderzpassion.com/android-location-using-google-play-services/
3尝试使用addMarker
public void drawMarker(double lat,double lon)
{
if (mMap != null) {
MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lon)).title(" Maps Tutorial").snippet("Android Ruler");
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
// Moving Camera to a Location with animation
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude, longitude)).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mMap.addMarker(marker);
}
}
有关详细信息,请参阅此处http://coderzpassion.com/android-google-maps-v2-tutorial-with-markers/