Android 谷歌地图 API V2 缩放到当前位置

问题描述 投票:0回答:10

我试图弄乱 Maps API V2 以更加熟悉它,并且我正在尝试以用户当前位置为中心启动地图。使用

map.setMyLocationEnabled(true);
语句,我可以在地图上显示我当前的位置。这还会将按钮添加到 UI,使地图以我当前的位置为中心。

我想在我的代码中模拟那个按钮的按下。我熟悉

LocationManager
LocationListener
类,并意识到使用它们是一个可行的选择,但居中和放大用户位置的功能似乎已经通过按钮内置。

如果 API 有显示用户当前位置的方法,那么肯定有比使用

LocationManager
/
LocationListener
类更简单的方法来定位位置,对吧?

android google-maps location google-maps-android-api-2
10个回答
115
投票

试试这个编码:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();

Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));

    CameraPosition cameraPosition = new CameraPosition.Builder()
        .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
        .zoom(17)                   // Sets the zoom
        .bearing(90)                // Sets the orientation of the camera to east
        .tilt(40)                   // Sets the tilt of the camera to 30 degrees
        .build();                   // Creates a CameraPosition from the builder
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));       
}

45
投票

在实例化地图对象(来自片段)之后添加这个 -

private void centerMapOnMyLocation() {

    map.setMyLocationEnabled(true);

    location = map.getMyLocation();

    if (location != null) {
        myLocation = new LatLng(location.getLatitude(),
                location.getLongitude());
    }
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
            Constants.MAP_ZOOM));
}

如果您需要任何指导,请询问,但它应该是自我解释的——只需将 myLocation 对象实例化为默认对象...


21
投票
youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));

16 是缩放级别


16
投票
    mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {

                CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
                CameraUpdate zoom=CameraUpdateFactory.zoomTo(11);
                mMap.moveCamera(center);
                mMap.animateCamera(zoom);

        }
    });

10
投票

试试这个代码:

private GoogleMap mMap;


LocationManager locationManager;


private static final String TAG = "";

@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(map);
    mapFragment.getMapAsync(this);

    arrayPoints = new ArrayList<LatLng>();
}

@Override
public void onMapReady(GoogleMap googleMap) {


    mMap = googleMap;


    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);


    LatLng myPosition;


    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    googleMap.setMyLocationEnabled(true);
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(provider);


    if (location != null) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        myPosition = new LatLng(latitude, longitude);


        LatLng coordinate = new LatLng(latitude, longitude);
        CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 19);
        mMap.animateCamera(yourLocation);
    }
}

}

不要忘记在 AndroidManifest.xml 上添加权限。

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

5
投票

这里是如何在

ViewModel
FusedLocationProviderClient
里面做的,用Kotlin写代码

locationClient.lastLocation.addOnSuccessListener { location: Location? ->
            location?.let {
                val position = CameraPosition.Builder()
                        .target(LatLng(it.latitude, it.longitude))
                        .zoom(15.0f)
                        .build()
                map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
            }
        }

4
投票
private void setUpMapIfNeeded(){
    if (mMap == null){
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();//invoke of map fragment by id from main xml file

     if (mMap != null) {
         mMap.setMyLocationEnabled(true);//Makes the users current location visible by displaying a blue dot.

         LocationManager lm=(LocationManager)getSystemService(LOCATION_SERVICE);//use of location services by firstly defining location manager.
         String provider=lm.getBestProvider(new Criteria(), true);

         if(provider==null){
             onProviderDisabled(provider);
              }
         Location loc=lm.getLastKnownLocation(provider);


         if (loc!=null){
             onLocationChanged(loc);
      }
         }
     }
}

    // Initialize map options. For example:
    // mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

@Override
public void onLocationChanged(Location location) {

   LatLng latlng=new LatLng(location.getLatitude(),location.getLongitude());// This methods gets the users current longitude and latitude.

    mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));//Moves the camera to users current longitude and latitude
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng,(float) 14.6));//Animates camera and zooms to preferred state on the user's current location.
}

    // TODO Auto-generated method stub


3
投票

看看这个:

    fun requestMyGpsLocation(context: Context, callback: (location: Location) -> Unit) {
        val request = LocationRequest()
        //        request.interval = 10000
        //        request.fastestInterval = 5000
        request.numUpdates = 1
        request.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        val client = LocationServices.getFusedLocationProviderClient(context)

        val permission = ContextCompat.checkSelfPermission(context,
            Manifest.permission.ACCESS_FINE_LOCATION )
        if (permission == PackageManager.PERMISSION_GRANTED) {
            client.requestLocationUpdates(request, object : LocationCallback() {
                override fun onLocationResult(locationResult: LocationResult?) {
                val location = locationResult?.lastLocation
                if (location != null)
                    callback.invoke(location)
            }
         }, null)
       }
     }

    fun zoomOnMe() {
        requestMyGpsLocation(this) { location ->
            mMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(
                LatLng(location.latitude,location.longitude ), 13F ))
        }
    }

2
投票

这正在为谷歌地图 V2 缩放当前位置

 double lat= location.getLatitude();
 double lng = location.getLongitude();
 LatLng ll = new LatLng(lat, lng);
 googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));

0
投票

在 kotlin 中,您将获得当前位置,然后像这样移动相机

map.isMyLocationEnabled = true
fusedLocationClient.lastLocation
    .addOnSuccessListener { location: Location? ->
        if (location != null) {
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(location.latitude, location.longitude), 14f))
        }
    }

您也可以使用此功能为移动设置动画

map.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(location.latitude, location.longitude), 14f))
© www.soinside.com 2019 - 2024. All rights reserved.