【问题标题】:Android Map app doesn't always go to current locationAndroid 地图应用程序并不总是转到当前位置
【发布时间】:2016-04-01 12:35:08
【问题描述】:

我以为我已经解决了(在其他人的帮助下)。我希望我的地图应用程序直接转到我当前的位置,但超过 50% 的时间,它最初会显示上次使用它的位置,我必须单击“当前位置的中心”按钮(右上角)让它去那里。我能做些什么来让这项工作 100% 完成?相关代码如下。感谢您的帮助。

public class LocateMe extends FragmentActivity
{

private GoogleMap mMap; // Might be null if Google Play services APK is not available.

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

    if (mMap != null) {
        mMap.setMyLocationEnabled(true);
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

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

        try {
            Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
            if (location != null)
            {
                mMap.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(00)                // Sets the orientation of the camera to north
                        .tilt(00)                   // Sets the tilt of the camera to 0 degrees
                        .build();                   // Creates a CameraPosition from the builder
                mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // ---
    }
}

@Override
protected void onResume()
{
    super.onResume();
    setUpMapIfNeeded();
}

/**
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
 * installed) and the map has not already been instantiated.. This will ensure that we only ever
 * call {@link #setUpMap()} once when {@link #mMap} is not null.
 * <p/>
 * If it isn't installed {@link SupportMapFragment} (and
 * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
 * install/update the Google Play services APK on their device.
 * <p/>
 * A user can return to this FragmentActivity after following the prompt and correctly
 * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
 * have been completely destroyed during this process (it is likely that it would only be
 * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
 * method in {@link #onResume()} to guarantee that it will be called.
 */
private void setUpMapIfNeeded()
{
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap()
{
    mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}

【问题讨论】:

  • locationManager.getLastKnownLocation 获取系统已知的最后一个位置。它尚未检测到您已更改位置,因此它会显示以前的已知位置
  • 谢谢,但我认为 CameraPosition 中的 .target 行(获取新的纬度和经度)会在执行 animateCamera 后转到当前位置。
  • .target 设置相机的位置。新 LatLng 没有获取当前位置。它只是从位置对象设置 latlong,这是最后一个已知位置。
  • 我必须承认我有点困惑。您能否让我知道我需要对代码进行哪些更改才能实现我的目标。谢谢。

标签: android google-maps location


【解决方案1】:

您可以实现LocationListener,它会在设备获得新的位置数据时通知。

public class LocateMe extends FragmentActivity implements LocationListener {

private GoogleMap mMap; // Might be null if Google Play services APK is not available.

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

        if (mMap != null) {
            mMap.setMyLocationEnabled(true);
            mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        // -------
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, this);
            Criteria criteria = new Criteria();

            try {
                Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
                if (location != null) {
                    mMap.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(00)                // Sets the orientation of the camera to north
                    .tilt(00)                   // Sets the tilt of the camera to 0 degrees
                    .build();                   // Creates a CameraPosition from the builder
                    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        // ---
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

/**
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
 * installed) and the map has not already been instantiated.. This will ensure that we only ever
 * call {@link #setUpMap()} once when {@link #mMap} is not null.
 * <p/>
 * If it isn't installed {@link SupportMapFragment} (and
 * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
 * install/update the Google Play services APK on their device.
 * <p/>
 * A user can return to this FragmentActivity after following the prompt and correctly
 * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
 * have been completely destroyed during this process (it is likely that it would only be
 * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
 * method in {@link #onResume()} to guarantee that it will be called.
 */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
            .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }

    @Override
    public void onLocationChanged(Location location) {
        LatLng latLng = new LatLng(location.getLatitude, location.getLongitude);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(17));
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

这将在每次更改位置时更新您的地图,因此当您启动应用程序时,相机将在设备获得新位置后立即更新,此代码未经测试,因此可能需要进行一些更改,但我希望对你有帮助。

【讨论】:

  • 感谢 Eduard 的时间和麻烦。我已经进行了您建议的更改,但现在运行程序时出现问题(与您的代码无关),所以我无法对其进行测试。其他问题解决后会回复您。
  • 好的,如果您需要更多帮助,请告诉我。
  • 其他问题现已解决!我正在运行你修改过的程序,至少它没有崩溃。一切似乎都很好,但我需要出去走一段距离或开车去某个地方看看应用程序是否更新了位置。它正在下雨。索德定律!当它停止时,我会冒险出去。注意这个空间。
  • 对不起爱德华。还是不行。当应用程序最初启动时,它仍然有 50% 的时间回到上次关闭时的位置。一旦打开,当我走路或开车时,蓝色(我在这里)点的位置正确移动(它总是这样做),但显示屏的中心不会随着点移动。如果手机侧身或左右晃动,该应用程序的行为就像我按下了“在我的位置”按钮并且确实刷新并以我的位置为中心。真的很奇怪。我会发誓你的解决方案会奏效。
  • 再次对不起爱德华。还是不行。可能是我的错。而且我还从编译器收到一条警告消息,说从未使用过 onLocationChanged。我想你已经在这方面花费了足够的时间,我感谢你。按下“在我的位置”按钮没什么大不了的。干杯。
猜你喜欢
  • 2014-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 2023-04-02
  • 2017-01-02
相关资源
最近更新 更多