安卓谷歌地图API V2缩放至当前位置

80
我正在摆弄 Maps API V2,以便更加熟悉它。我想要在地图上以用户当前的位置为中心开始。使用 map.setMyLocationEnabled(true); 语句,我可以在地图上显示我的当前位置。这也会在 UI 上添加按钮,将地图居中于我的当前位置。
我想在我的代码中模拟那个按钮的按下操作。我熟悉 LocationManagerLocationListener 类,并意识到使用它们是一种可行的替代方法,但居中和缩放到用户位置的功能似乎已经通过该按钮内置了。
如果 API 有一个显示用户当前位置的方法,那么肯定有更简单的方法来将其居中于位置,而不是使用 LocationManager/LocationListener 类,对吧?

重点是获取当前位置的地理坐标。您可以使用GPS库来获取它。一旦您获得了地理坐标,就很容易了。请参考以下链接以获取更多详细信息: https://dev59.com/kGMm5IYBdhLWcg3wi_m0#17519248 - user846316
10个回答

116

试试这段代码:

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));       
}

1
如果位置 == null 怎么办?请帮忙。 - jyomin
@jyomin 请在这里查看我如何获取用户位置的答案。它使用上述方法,并加入了一些故障保护来检查用户可能的下一个最佳位置。http://stackoverflow.com/a/14511032/845038 这可能会通过检查下一个最佳位置来解决获取空值的问题。 - DMCApps
1
这个解决方案很简单,而且非常有效。谢谢。 - Enkk
这在我的Android 4.2.1上无法工作,但在我的搭载Android 5的Nexus 7平板电脑上工作。你可以帮忙吗? - farid bekran
Google Play服务位置API比Android框架位置API(android.location)更受欢迎,作为向您的应用程序添加位置感知的方法。这种方法已经过时。请查看https://developer.android.com/training/location/index.html。 - Gokhan Arik

45
在实例化地图对象(来自fragment)之后,添加以下内容 -
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));
}

如果您需要任何指导,请随时询问,但它应该是自我解释的 - 只需为默认对象实例化我的位置对象即可...


1
我有同样的问题,但是当我尝试使用map.getMyLocation()时,它会警告我该方法已被弃用。现在应该怎么做才对? - Pam
15
"getMyLocation()方法已经废弃,应使用LocationClient替代。LocationClient提供了更好的位置查找和电源使用,并且被“我的位置”蓝点使用。请参阅示例应用程序文件夹中的MyLocationDemoActivity获取示例代码,或者查看位置开发者指南。" 下次如果有方法被废弃,只需阅读API,因为通常都会有替代方法。 - crazyPixel
5
LocationClient已被标记为过时。您需要使用LocationServices代替。 - Lars Nielsen
我猜 Constants.MAP_ZOOM 应该是我们定义的缩放级别? - AgentKnopf
此方法已被弃用,请使用FusedLocationProviderApi代替。回答已编辑。 - Marian Paździoch
显示剩余4条评论

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

16是缩放级别


1
但是如果不使用LocationManager和LocationListener,我该如何获取currentLocation?或者这不可能吗? - user139260
根据我的知识,这是不可能的。 我建议您不要使用位置管理器。 Google新推出了一个高精度、低电量消耗且易于实现的用户位置客户端。详情请参考:http://developer.android.com/google/play-services/location.html - SHASHIDHAR MANCHUKONDA
1
位置 location = map.getMyLocation(); map 是 GoogleMap 对象 - Venkat
你可以使用14.0f代替16。 - Däñish Shärmà

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);

        }
    });

2
很遗憾,此方法现已被弃用 :( - Antonio
1
如果你从当前位置滚动屏幕,几秒钟后你会跳回到当前位置,因为你的位置刚刚更新了。 - Jeffrey Liu

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"/>

1
欢迎来到Stack Overflow!虽然这段代码可能回答了问题,但最好还是包括问题的描述以及您的代码如何解决给定的问题。为了未来,请参考以下信息,了解如何在Stack Overflow上提供出色的答案:http://stackoverflow.com/help/how-to-answer - dirtydanee

5

以下是在 ViewModelFusedLocationProviderClient 内处理的方法,使用 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))
            }
        }

这是可取的吗?像 locationClient.lastLocation.addOnSuccessListener{} 这样更改多个项目? - Gilbert

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


请添加一些关于您的代码的解释,以及它如何回答问题的说明,并请正确格式化它。在将代码复制到 SO 之前,请将制表符转换为空格,因为制表符通常无法按预期呈现。 - Adi Inbar
以上解决方案加载地图碎片,并显示用户当前位置的中心位置,使用所需的缩放级别,在本例中我的缩放级别为(14.6)@AdiInbar。 - imm3000
请在答案中包含解释,而不是在评论中回复,并格式化代码。(顺便说一下,我并不是出于个人兴趣而问的。我在“低质量帖子”审核队列中遇到了你的答案,并建议你改进它,以避免进一步的反对和删除投票。) - Adi Inbar

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 ))
        }
    }

伟大的人,非常简单而且有效。 - Ahmed Rabee

2

这是在Google地图V2上使用缩放的当前位置功能。

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

3
"location" 出现了错误:无法解析符号“location”。 - beckah
问题是如何获取当前位置坐标,答案在这里:https://dev59.com/kGMm5IYBdhLWcg3wi_m0#17519248 - user846316

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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接