首页 文章

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

提问于
浏览
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();
}

2 回答

  • 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()方法选择您的位置提供程序 .

  • 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;
    }
    

相关问题