简体   繁体   English

如何将地图聚焦到用户位置?

[英]How to focusing map to user location?

I created a MapActivity that will be focusing the map to user location. 我创建了一个MapActivity ,它将地图聚焦到用户位置。

public void getMyLatLng() {
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    LocationListener ll = new LocationListener() {

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

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onLocationChanged(Location location) {
            myLatLng = new LatLng(location.getLatitude(),location.getLongitude());
        }
    };
    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll);
    lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    //myLatLng = new LatLng(myLoc.getLatitude(), myLoc.getLongitude());
}

I got java.lang.NullPointerException issue when it is run for first time. 第一次运行时遇到java.lang.NullPointerException问题。 But when I run it again, it works. 但是,当我再次运行它时,它可以工作。 And the second issue is, it'll work well when I put NETWORK_PROVIDER instead GPS_PROVIDER. 第二个问题是,当我放置NETWORK_PROVIDER而不是GPS_PROVIDER时,它将很好地工作。 Any advice to solve this issue? 有什么建议可以解决这个问题?

You can request location updates from both GPS and nework Something like this: 您可以从GPS和nework请求位置更新,例如:

 public class LocationService implements LocationListener {

    boolean isGPSEnabled = false;

    boolean isNetworkEnabled = false;

    boolean canGetLocation = false;

    final static long MIN_TIME_INTERVAL = 60 * 1000L;

    Location location;


    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute

    protected LocationManager locationManager;

    private CountDownTimer timer = new CountDownTimer(5 * 1000, 1000) {

        public void onTick(long millisUntilFinished) {

        }

        public void onFinish() {
            stopUsingGPS();
        }
    };

    public LocationService() {
        super(R.id.gps_service_id);
    }


    public void start() {
        if (Utils.isNetworkAvailable(context)) {

            try {


                timer.start();


                locationManager = (LocationManager) context
                        .getSystemService(Context.LOCATION_SERVICE);

                isGPSEnabled = locationManager
                        .isProviderEnabled(LocationManager.GPS_PROVIDER);

                isNetworkEnabled = locationManager
                        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        Location tempLocation = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (tempLocation != null
                                && isBetterLocation(tempLocation,
                                        location))
                            location = tempLocation;
                    }
                }
                if (isGPSEnabled) {

                    locationManager.requestSingleUpdate(
                            LocationManager.GPS_PROVIDER, this, null);
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        Location tempLocation = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (tempLocation != null
                                && isBetterLocation(tempLocation,
                                        location))
                            location = tempLocation;
                    }
                }

            } catch (Exception e) {
                onTaskError(e.getMessage());
                e.printStackTrace();
            }
        } else {
            onOfflineResponse(requestData);
        }
    }

    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(LocationService.this);
        }
    }

    public boolean canGetLocation() {
        locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return isGPSEnabled || isNetworkEnabled;
    }

    @Override
    public void onLocationChanged(Location location) {

        if (location != null
                && isBetterLocation(location, this.location)) {

            this.location = location;

        }
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

    @Override
    public Object getResponseObject(Object location) {
        return location;
    }

    public static boolean isBetterLocation(Location location,
            Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > MIN_TIME_INTERVAL;
        boolean isSignificantlyOlder = timeDelta < -MIN_TIME_INTERVAL;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location,
        // use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
            // If the new location is more than two minutes older, it must
            // be worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
                .getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Determine location quality using a combination of timeliness and
        // accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate
                && isFromSameProvider) {
            return true;
        }
        return false;
    }

}

Notice that every time we get a location we are comparing it with already known location to find of this new location is better by calling isBetterLocation. 请注意,每次获取位置时,我们都将其与已知位置进行比较,以通过调用isBetterLocation更好地找到该新位置。

To receive location form GPS satellite, need some times. 要从GPS卫星接收位置,需要一些时间。

If your testing location was indoor, GPS signal is too week so you may couldn't get locaion. 如果您的测试地点是室内,则GPS信号太周了,因此您可能无法获得定位。

Instead of using network provider, you can receive location when you were in buildings, but it has low accuracy than GPS. 您可以在建筑物中时接收位置信息,而无需使用网络提供商,但是它的精度比GPS低。

如果您在Android上使用google map api 2,则可以实现LocationSource以将地图强制到所需的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用户位置未显示在地图上 - User location is not displayed on the map 如何获取所有应用程序用户的位置并将其显示在地图上 - How to get location of all the app user and show it on map Android Maps-如何将地图自动居中到用户的当前位置? - Android Maps - how to automatically center the map to the user's current location? 我如何检索用户位置并向他显示地图 - how can i retrieve user location and show him the map 如何使用OverlayItem获取用户的当前位置并将其绘制在地图上 - How to get user's current location and plot it on the map using OverlayItem 如何使用Google Map v2在Android中长时间显示经纬度在Map中的用户输入位置? - How to show user input location in Map according to lat, long in android using Google Map v2? Android-缩放到用户位置并显示地图 - Android - Zoom to the user location and display the map 如何让天气信息默认显示用户当前位置的天气? Openweather map - How can I make the weather information default to display the weather in the user's current location? Openweather map 当我打开片段时,如何仅在 Google Map 中显示当前用户位置一次? - how I can show current user location in Google Map only once, when I open the fragment? 如何听焦点儿童事件 - How to listen focusing child event
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM