简体   繁体   中英

accurate latitude and longitude of current location in android

In my application, I am showing map with marker at the current location's latitude and longitude.And I use Map.setMyLocationEnabled(true) for user to interact with their location.

What my problem is setMyLocationEnabled method and my location - lat,long code is marks different positions as follows:

地图

I have used the following code to get Latitude and Longitude of current location:

    LocationManager locationManager = (LocationManager)  getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(provider);
    if(location!=null){
        latitude = location.getLatitude();
        longitude = location.getLongitude();
         --------- 
         }

How to get accurate latitude and longitude of my current location as google's setLocationEnabled provided?

Green flag marker is my marker and blue dot is android provided.

Instead of using LocationManager, add yourself to GoogleMap's location client via setOnMyLocationChangeListener. It returns the same location blue dot is pointing to.

I think problem is that you are using the getLastKnownLocation() method.

Location location = locationManager.getLastKnownLocation(provider);

This method does not returns the latest location, but the last known location from the selected location provider. As stated in the documentation here .

Returns a Location indicating the data from the last known location fix obtained from the given provider.

This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.

Probably the google map ( using Map.setMyLocationEnabled(true) ) is marking your latest location, while the location received from locationManager.getLastKnownLocation() is a bit old and misplaced.This may be the reason why you're getting both markers at different positions.

For accuracy, you should implement proper Location Listener and try to get the latest location cordinates from Location Manager. Good information is available in the training docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM