【问题标题】:Getting current location android获取当前位置android
【发布时间】:2016-04-26 17:02:50
【问题描述】:

应用程序应该获取我的当前位置并将其标记在地图上,而不是我的项目只是崩溃。代码如下:

public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mMap.setMyLocationEnabled(true);
    }
   LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    Location myLocation = locationManager.getLastKnownLocation(provider);
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    double latitude = myLocation.getLatitude();
    double longitude = myLocation.getLongitude();
    LatLng Me = new LatLng(latitude, longitude);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(Me));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
    mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));

}

任何想法如何解决它,或者这里有什么问题? (这是 GoogleMaps 项目,所有需要的权限都被授予 btw)

【问题讨论】:

  • 好吧,您正在尝试获取一个位置,而不必获得这样做的权限 (getLastKnownLocation())。除此之外,请编辑您的问题并发布崩溃的 Java 堆栈跟踪。
  • 如果你说它崩溃了你的堆栈跟踪在哪里
  • 我不好,我会尽快添加跟踪。我没有确切解释那里发生了什么:应用程序运行,然后突然关闭,并显示“您的项目已停止”之类的消息

标签: android location maps locationmanager


【解决方案1】:

您可以为此使用 LocationManager:

locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
    latitude=location.getLatitude();
    longitude=location.getLongitude();
    Log.d("GPS","lat :  "+latitude);
    Log.d("GPS","long :  "+longitude);
}

然后您只需在地图中显示位置,如this 教程中所示。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2011-07-15
    • 1970-01-01
    • 2018-12-21
    • 2012-01-22
    • 2016-07-30
    • 1970-01-01
    • 2012-03-05
    • 2017-04-01
    相关资源
    最近更新 更多