ChatGPT解决这个技术问题 Extra ChatGPT

Android Google Maps API V2 缩放到当前位置

我正在尝试使用 Maps API V2 来更加熟悉它,并且我正在尝试以用户当前位置为中心启动地图。使用 map.setMyLocationEnabled(true); 语句,我可以在地图上显示我的当前位置。这还将按钮添加到 UI 中,以使地图以我当前位置为中心。

我想在我的代码中模拟那个按钮按下。我熟悉 LocationManagerLocationListener 类,并意识到使用它们是一种可行的替代方法,但似乎已经通过按钮内置了居中和放大用户位置的功能。

如果 API 有显示用户当前位置的方法,那么肯定有比使用 LocationManager/LocationListener 类更容易以位置为中心的方法,对吧?

这里的重点是获取当前位置的地理坐标。您可以使用 GPS 库来获取它。一旦你有了地理坐标,它就变得微不足道了。有关详细信息,请参阅以下内容:stackoverflow.com/questions/17519198/…

C
Chris Stillwell

试试这个编码:

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

如果位置 == null 怎么办..请帮忙
@jyomin 在此处查看我关于如何获取用户位置的答案。它使用上述方法和一点故障保险来检查用户的下一个最佳位置。 stackoverflow.com/a/14511032/845038 这可能会通过检查下一个最佳位置来解决获取 null 的问题。
这个解决方案很简单,而且很有效。谢谢你。
这对我在 android 4.2.1 上不起作用,但在我的带有 android 5 的 nexus 7 平板电脑上工作。你能帮忙吗?
The Google Play services location APIs are preferred over the Android framework location APIs (android.location) as a way of adding location awareness to your app. 此方法已过时。请检查developer.android.com/training/location/index.html
c
crazyPixel

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

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 对象实例化为默认对象...


我有同样的问题,但是当我尝试使用 map.getMyLocation() 时,它警告我这个方法已被弃用。现在正确的方法是什么?
“getMyLocation() 此方法已弃用。请改用 LocationClient。LocationClient 提供改进的位置查找和电源使用,并由“我的位置”蓝点使用。请参阅示例应用程序文件夹中的 MyLocationDemoActivity 示例代码,或 Location Developer指导。” (取自 android 开发者网站)下次只要阅读 API,如果某些东西被弃用,就会有替代品
LocationClient 已被标记为过时。您必须改用 LocationServices
我猜 Constants.MAP_ZOOM 应该是我们定义的缩放级别?
@Zainodis 你猜对了。作为一个经验法则,每当我写一些依赖于一些先前数据或应该获取的数据的东西时,我都会将它初始化为一些默认值。
S
Smern
youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));

16 是缩放级别


但是如何在不使用 LocationManager 和 LocationListener 的情况下获取 currentLocation?或者那不可能?
据我所知,这是不可能的。我建议你不要使用位置管理器。用户定位客户端,精度高,电池功耗低,易于实现。developer.android.com/google/play-services/location.html 谷歌新推出
位置 location = map.getMyLocation();地图是 GoogleMap 对象
这个解决方案简单而迷人
你可以使用 14.0f 而不是 16
m
mz87
    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);

        }
    });

不幸的是,这种方法现在已被弃用:(
如果您滚动离开您的位置,几秒钟后您将跳回您当前的位置,因为您的位置刚刚更新。
G
Gustavo

试试这个代码:

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

欢迎来到堆栈溢出!虽然这段代码可能会回答问题,但最好包含对问题所在的描述,以及您的代码将如何解决给定问题。对于未来,这里有一些信息,如何在 Stack Overflow 上破解一个很棒的答案:stackoverflow.com/help/how-to-answer
o
onmyway133

以下是在 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{}
i
imm3000
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 之前将制表符转换为空格,因为制表符通常不会按预期呈现。
上面的解决方案加载了一个地图片段,并使用所需的缩放级别显示用户当前位置的中心位置,在这种情况下,我的是 (14.6)@AdiInbar
请在答案中包含解释而不是在评论中回复,并格式化代码。 (仅供参考,我不是出于个人兴趣而问的。我在低质量帖子审核队列中遇到了您的答案,并建议您对其进行改进以避免进一步的否决和删除投票。)
D
Dan Alboteanu

看一下这个:

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

伟大的人,非常简单和工作
B
Bill the Lizard

这适用于 Google Map V2 缩放的当前位置

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

location 抛出错误:Can not resolute symbol 'location'
问题是如何获取当前位置坐标,答案在这里:stackoverflow.com/a/17519248/846316