【问题标题】:Zoom on current user location displayed放大显示的当前用户位置
【发布时间】:2013-01-08 06:05:28
【问题描述】:

我正在使用 Android 版 Google 地图 v2。我想显示当前用户位置并放大它。 这是FragmentActivity中的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_activity);

    mMap = ((SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.mapFragment_mapActivity)).getMap();
    if (mMap == null) {
        Toast.makeText(this, R.string.mapCreationProblem, Toast.LENGTH_LONG)
                .show();
        finish();
        return;
    }
    mMap.setMyLocationEnabled(true);
    Location currentLocation = mMap.getMyLocation();
    if(currentLocation!=null){
       LatLng currentCoordinates = new LatLng(
                            currentLocation.getLatitude(),
                            currentLocation.getLongitude());
       mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentCoordinates, 10));
    }
}

地图工作正常,当前位置上的蓝点也工作正常。但似乎currentLocation 始终为空。所以我无法放大当前位置。

有谁知道原因吗?

【问题讨论】:

    标签: android android-maps android-maps-v2


    【解决方案1】:

    这是一个 getMyLocation() 的实现,为查找人员位置提供了额外的保护。我只是在管理地图片段的活动中拥有它。

    private Location getMyLocation() {
        // Get location from GPS if it's available
        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    
        // Location wasn't found, check the next most accurate place for the current location
        if (myLocation == null) {
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            // Finds a provider that matches the criteria
            String provider = lm.getBestProvider(criteria, true);
            // Use the provider to get the last known location
            myLocation = lm.getLastKnownLocation(provider);
        }
    
        return myLocation;
    }
    

    谢谢, 德曼

    【讨论】:

    • @DanieleVitali 很高兴我能帮上忙!
    • 仍然为空。但是我的当前位置显示在地图上
    【解决方案2】:

    尝试使用 LocationManager:

    LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location currentLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    

    【讨论】:

    • 是的,我想过。但我想知道为什么 getMyLocation() 返回 null。
    • @DanieleVitali 从这个 stackoverflow.com/a/13830598/845038 的外观来看,已经报告了针对此不断返回 null 的问题。位置管理器似乎是您最好的选择。我已经发布了我的 getMyLocation() 实现,它与上面的基本相同,但有轻微的故障保护。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 2018-08-23
    相关资源
    最近更新 更多