如何找到特定位置的经度和纬度?

时间:2011-06-06 09:52:25

标签: android

如何查找特定位置的经度和纬度?

用户在edittext&amp ;;中输入位置点击搜索按钮,然后该位置将显示在googlemap中。

我使用了以下代码,但这是错误的“服务不可用”


Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try {
     address=geoCoder.getFromLocationName(txtlocation.getText().toString(), 1).get(0);
     double longi=address.getLongitude();
     double latit=address.getLatitude();
     System.out.println("longitude:--- " +longi);
     System.out.println("latitude:---" +latit);

} catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     Toast.makeText(MapRouteActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}

2 个答案:

答案 0 :(得分:2)

尝试使用

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);  Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); double longitude = location.getLongitude(); double latitude = location.getLatitude(); 

对getLastKnownLocation()的调用没有阻塞 - 这意味着如果当前没有位置,它将返回null - 所以你可能想要看看将LocationListener传递给requestLocationUpdates()方法,这将给出您异步更新您的位置。

private final LocationListener locationListener = new LocationListener() {     public void onLocationChanged(Location location) {         longitude = location.getLongitude();         latitude = location.getLatitude();     } } 

lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener); 

如果您想使用GPS,则需要为您的应用程序提供ACCESS_FINE_LOCATION权限。

您可能还想在GPS不可用时添加ACCESS_COARSE_LOCATION权限,并使用getBestProvider()方法选择您的位置提供程序。

答案 1 :(得分:0)

试试这段代码

public static String getLatLng(Context context,String addr){
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
    String add = "";
    try{
        List<Address> addresses = geocoder.getFromLocationName(addr, 5);

        for(int i=0;i<1;i++){
            Address obj = addresses.get(i);
            for(int j=0;j<obj.getMaxAddressLineIndex();j++){
                add = obj.getAddressLine(j);
                add = add + "\nCountryName " + obj.getCountryName();
                add = add + "\nCountryCode " + obj.getCountryCode();
                add = add + "\nAdminArea " + obj.getAdminArea();
                add = add + "\nPostalCode " + obj.getPostalCode();
                add = add + "\nSubAdminArea " + obj.getSubAdminArea();
                add = add + "\nFeatureName " + obj.getFeatureName();
                add = add + "\nLocality " + obj.getLocality();
                add = add + "\n" + obj.getSubThoroughfare();
                add = add + "\nurl " + obj.getUrl();
                add = add + "\nLatitude " + obj.getLatitude();
                add = add + "\nLongitude " + obj.getLongitude();
            }
            add = add+"\n";
        }

        Log.v("IGA", "Address" + add);

    }catch(Exception e){
        e.printStackTrace();
        add = e.toString();
    }
    return add;
}