2011-06-06 152 views
0

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

位置由用户在edittext中输入&点击搜索按钮,然后位置显示在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(); 
} 

+0

你为什么不使用locationManager。 – Stuti 2011-06-06 10:12:43

+0

在我的应用程序中,我使用了locationmanager,但没有在这里显示。 – 2011-06-06 11:01:22

+0

先看看夜空,找到北极星....;) – 2011-10-19 12:24:25

回答

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 - 所以你的概率bly希望看一下将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()方法选择您的位置提供程序。

+0

感谢stuti,这段代码在我的应用程序中工作得很好。 – 2011-06-07 05:58:38

+0

高兴地帮助:) – Stuti 2011-06-07 06:36:38

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; 
} 
+0

喂你pratik,这段代码也给出同样的错误。 – 2011-06-06 10:06:26

相关问题