如何在android中获取经度和纬度的位置

时间:2014-08-12 09:49:35

标签: android location

所以我从互联网上获得了一段代码,让我从当前位置获得经纬度。我现在想要的是获得那个地方的位置。是的,我做了大量的研究,并从与我有相同要求的人(下图)从堆栈溢出中获取此代码。它可能对他们有用,但它并不适合我。我使用了纬度和经度示例,因为这段代码不起作用。问题是地址始终为空。我究竟做错了什么?为什么geocder.getFromLocation不起作用?我尝试记录地址aswel,然后得到[]。

private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
    String strAdd = "";
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(51.977315, 5.921753, 1);
        if (addresses != null) {
            Address returnedAddress = addresses.get(0);
            StringBuilder strReturnedAddress = new StringBuilder("");

            for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
            }
            strAdd = strReturnedAddress.toString();
            Log.w("My Current loction address", "" + strReturnedAddress.toString());
        } else {
            Log.w("My Current loction address", "No Address returned!");
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.w("My Current loction address", "Canont get Address!");
    }
    return strAdd;
}

1 个答案:

答案 0 :(得分:0)

Create Location Utility Class

public class LocationUtility {

private String currentLatitude = "";
private String currentLongitude = "";
private LocationManager mLocationManager = null;
private final int TEN_SECOND = 0;
private final int TEN_METRES = 1;
private final int TWO_MINUTES = 1000 * 60 * 2; // Better Location

String provider;

public LocationUtility(Activity activity) {
    mLocationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
    getCurrentLocation();
}

private boolean isGpsOn;

private void getCurrentLocation() {
    Location gpsLocation = null;
    Location networkLocation = null;
    mLocationManager.removeUpdates(listener);

    /*
     * Criteria criteria = new Criteria();
     * criteria.setAccuracy(Criteria.ACCURACY_FINE);
     * criteria.setCostAllowed(false);
     * 
     * String bestProviderName = mLocationManager.getBestProvider(criteria,
     * true);
     * 
     * if(bestProviderName!=null) Logger.d("bestProvider",
     * bestProviderName);
     */

    gpsLocation = requestUpdatesFromProvider(LocationManager.GPS_PROVIDER);
    networkLocation = requestUpdatesFromProvider(LocationManager.NETWORK_PROVIDER);
    isGpsOn = true;

    if (gpsLocation != null && networkLocation != null) {
        updateLocation(getBetterLocation(gpsLocation, networkLocation));
    } else if (gpsLocation != null) {
        updateLocation(gpsLocation);
    } else if (networkLocation != null) {
        updateLocation(networkLocation);
    } else {
        isGpsOn = false;
    }
}

public String getCurrentLatitude() {
    return currentLatitude;
}

public String getCurrentLongitude() {
    return currentLongitude;
}

private final LocationListener listener = new LocationListener() {

    @Override
    public void onLocationChanged(Location location) {
        if (location != null)
            updateLocation(location);
    }

    @Override
    public void onProviderDisabled(String provider) {

        if (provider != null)
            Logger.d(provider + " provider", "disabled");
    }

    @Override
    public void onProviderEnabled(String provider) {
        if (provider != null)
            Logger.d(provider + " provider", "enabled");

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Logger.d("status", "" + status);
    }
};

/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
        return provider2 == null;
    }
    return provider1.equals(provider2);
}

private Location getBetterLocation(Location newLocation,
        Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return newLocation;
    } else if (newLocation == null) {
        // A new location is always better than no location
        return currentBestLocation;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = newLocation.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    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 newLocation;
        // If the new location is more than two minutes older, it must be
        // worse
    } else if (isSignificantlyOlder) {
        return currentBestLocation;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (newLocation.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(newLocation.getProvider(),
            currentBestLocation.getProvider());

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

private Location requestUpdatesFromProvider(String provider) {
    Location location = null;
    if (mLocationManager.isProviderEnabled(provider)) {
        mLocationManager.requestLocationUpdates(provider, TEN_SECOND,TEN_METRES, listener);
        location = mLocationManager.getLastKnownLocation(provider);
    }
    return location;
}

private void updateLocation(Location location) {
    try {
        Logger.d("new Location",location.getLatitude() + " " + location.getLongitude());

        currentLatitude = String.valueOf(location.getLatitude());
        currentLongitude = String.valueOf(location.getLongitude());
    } catch (Exception e) {
        // if (e != null)
        // e.printStackTrace();
    }
}

/**
 * 
 * @return
 */
public boolean isGPSON() {

    return isGpsOn;
}

public void removeUpdates() {
    if (listener != null) {
        try {
            mLocationManager.removeUpdates(listener);
        } catch (Exception e) {
            // if (e != null)
            // e.printStackTrace();
        }
    }
}

}

编写此方法以获取当前纬度和经度

public static String[] getLatAndLong(Activity mContext) {
    LocationUtility mLocation = new LocationUtility(mContext);
    return new String[] { String.valueOf(mLocation.getCurrentLatitude()),String.valueOf(mLocation.getCurrentLongitude()),String.valueOf(mLocation.isGPSON()) };
}

将此内容写入您获取位置详细信息的主要活动

try {
        Geocoder geocoder;
        List<Address> addresses;
        geocoder = new Geocoder(this, Locale.getDefault());
        addresses = geocoder.getFromLocation(lat, Long, 1);

        //String address = addresses.get(0).getAddressLine(0);
        //String city = addresses.get(0).getAddressLine(1);
        //String newstring = city.replaceAll(",","");
        //String country = addresses.get(1).getAddressLine(2);

        try {
            if (addresses != null && addresses.size() >= 0) {
                strCity = addresses.get(0).getLocality();
                strCounty = addresses.get(0).getCountryName();
                strState = addresses.get(0).getAdminArea();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }