How to directly move camera to current location in Google Maps Android API v2?

前端 未结 4 886
Happy的楠姐
Happy的楠姐 2020-12-04 16:41

Without clicking any button, how to directly get the current location and move the camera to it.
Also, I found that there is a button on the right top of the map. When c

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 16:51

    make sure you have these permissions:

    
    
    

    Then make some activity and register a 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) { }
    }
    

    map.xml

    
    
    

提交回复
热议问题