【问题标题】:Print Longitude and Latitude in textbox Android在文本框Android中打印经度和纬度
【发布时间】:2012-01-03 10:47:32
【问题描述】:

我已经四处寻找,但找不到任何关于我正在寻找的直接线索。我正在尝试创建一个 Android 应用程序,该应用程序在按下按钮时拨出紧急号码(我已经开始工作)但无法显示位置(以经度和纬度显示),我尝试使用 Toast 和编辑文本框。我是 Android 开发的新手,所以想从简单的东西开始,但是 LongLat 部分很麻烦。任何帮助将不胜感激。

下面是我一直在篡改的代码,以便尝试获取 Long 和 Lat,然后在另一个文件中,我一直在尝试使用点击侦听器将其分配给按钮,以便当按钮为按下(在 main.xml 中),它将在文本字段或 toast 中显示 Long 和 Lat。

import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.TextView;
import android.content.Context;
import android.location.LocationManager;
import android.location.Criteria;



        public class EmergencyLocation extends Activity implements LocationListener {
            private TextView latituteField;
            private TextView longitudeField;
            private LocationManager locationManager;
            private String provider;

            /** Called when the activity is first created. **/
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                latituteField = (TextView) findViewById(R.id.TextView);
                longitudeField = (TextView) findViewById(R.id.long_lat);

                // Get the location manager
                locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                // Define the criteria how to select the location provider -> use
                // default
                Criteria criteria = new Criteria();
                provider = locationManager.getBestProvider(criteria, false);
                Location location = locationManager.getLastKnownLocation(provider);

                // Initialise the location fields
                if (location != null) {
                    System.out.println("Provider " + provider + " has been selected.");
                    int lat = (int) (location.getLatitude());
                    int lng = (int) (location.getLongitude());
                    latituteField.setText(String.valueOf(lat));
                    longitudeField.setText(String.valueOf(lng));
                } else {
                    latituteField.setText("Provider not available");
                    longitudeField.setText("Provider not available");
                }
            }








        private void TextView() {
            // TODO Auto-generated method stub

        }


        @Override
        public void onLocationChanged(Location arg0) {
            // TODO Auto-generated method stub

        }


        @Override
        public void onProviderDisabled(String arg0) {
            // TODO Auto-generated method stub

        }


        @Override
        public void onProviderEnabled(String arg0) {
            // TODO Auto-generated method stub

        }


        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
            // TODO Auto-generated method stub

        }} 

【问题讨论】:

  • 贴出你的代码...这将有助于理解...
  • 那是我得到的代码并试图适应。

标签: android location latitude-longitude


【解决方案1】:

首先,你需要设置一个LocationManager

LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

// set preferred provider based on the best accuracy possible
Criteria fineAccuracyCriteria = new Criteria();
fineAccuracyCriteria.setAccuracy(Criteria.ACCURACY_FINE);
String preferredProvider = manager.getBestProvider(fineAccuracyCriteria, true);

现在,您必须创建一个LocationListener。在这种情况下,它调用方法updateLocation()

LocationListener listener = new LocationListener() {
        public void onLocationChanged(Location location) {
            // called when a new location is found by the network location provider.
            updateLocation(location);
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {}

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}
    };

编辑:

然后,您必须使用您的LocationManager 注册侦听器(并尝试获取缓存的位置):

manager.requestLocationUpdates(preferredProvider, 0, 0, listener);
// get a fast fix - cached version
updateLocation(manager.getLastKnownLocation());

最后,updateLocation() 方法:

private void updateLocation(Location location) {
    if (location == null)
        return;

    // save location details
    latitude = (float) location.getLatitude();
    longitude = (float) location.getLongitude();        
}

EDIT2:

好的,刚刚看到您的代码。为了使它工作,只需移动几位:

/** Called when the activity is first created. **/
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    latituteField = (TextView) findViewById(R.id.TextView);
    longitudeField = (TextView) findViewById(R.id.long_lat);

    // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the location provider -> use
    // default
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    locationManager.requestLocationUpdates(provider, 0, 0, this);
    Location location = locationManager.getLastKnownLocation(provider);
    onLocationChanged(location);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    locationManager.removeUpdates(this);
}

@Override
public void onLocationChanged(Location location) {
   if (location != null) {
       System.out.println("Provider " + provider + " has been selected.");
       int lat = (int) (location.getLatitude());
       int lng = (int) (location.getLongitude());
       latituteField.setText(String.valueOf(lat));
       longitudeField.setText(String.valueOf(lng));
   } else {
       latituteField.setText("Provider not available");
       longitudeField.setText("Provider not available");
   }
}

希望对你有帮助!

【讨论】:

  • 这一切都在一个类文件中吗?例如,我有一个名为 EmergencyLocation.java 的文件都在那个文件中吗?我之前尝试过创建两个文件,一个使用 LocationListiner,另一个使用 onClick,这样我可以通过触摸按钮来显示它,但它不起作用。
  • 如果这是您将在应用程序中使用 LocationManager 的唯一地方,它会做得很好。如果您打算重用它,最好的办法是使用单独的类(或 Application 对象)来管理您的 LocationManager 并注册侦听器并在需要时取消注册。在 updateLocation() 中,只要它与您的 UI 属于同一类,您就可以更新所需的信息。但请记住,您可能会在实际从 LocationManager 收到任何信息之前单击该按钮。在这种情况下,请参阅我编辑的帖子。
  • 是的,我只打算在一个文件中使用一次 LocationListener。因此,Long 和 Lat 可以由用户自行决定显示,我只是无法显示它,可能是我尝试过的代码不起作用,所以没有什么可显示的!
  • 非常感谢您的所有帮助,我似乎只是在做一个越来越大的哈希。我被告知这是一个简单的项目,而不是那样找到它!砍掉和改变我的代码,我想我可能已经删除了关键位。 Eclipse 提供我不明白的建议啊哈。
【解决方案2】:

很简单。我使用 locationListener 作为 Location 类中的属性。这是我的做法:

package com.rifsoft.android.helper.location;

import com.rifsoft.android.helper.IListener;

import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class Location implements IListener
{
  public final static int IDX_LATITIDE = 0;
  public final static int IDX_LONGITUDE = 1;

  private double[] lastLocation =  {0.0, 0.0};  
  private LocationManager locationManager = null;
  private ILocation activity = null;

  private LocationListener locationListener  = new LocationListener()
  {
      public void onLocationChanged(android.location.Location location) 
      {
        // TODO: http://developer.android.com/guide/topics/location/obtaining-user-location.html#BestEstimate
        lastLocation[IDX_LATITIDE] = location.getLatitude();
        lastLocation[IDX_LONGITUDE] = location.getLongitude();
        activity.onLocationChange();
      }

      public void onStatusChanged(String provider, int status, Bundle extras) {}

      public void onProviderEnabled(String provider) {}

      public void onProviderDisabled(String provider) {}
  };

  /**
   * Constructor, needs LocationManager
   * @param activity Activity that will receive the notification when location has changed
   * @param locationManager LocationManager
   */
  public Location(final ILocation act, LocationManager lm) throws LocationException
  {
    if (lm == null)
    {
      throw new LocationException(LocationException.ERR_NULL_LOCATION_MANAGER);
    }

    if (act == null)
    {
      throw new LocationException(LocationException.ERR_NULL_ILOCATION);
    }

    locationManager = lm;
    activity = act;

    registerListener();   

    android.location.Location lastCachedLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (lastCachedLocation != null)
    {
      lastLocation[IDX_LATITIDE] = lastCachedLocation.getLatitude();
      lastLocation[IDX_LONGITUDE] = lastCachedLocation.getLatitude();
    }
  }

  /**
   * Retuns last known most accurate location as latitude, longitude
   * @return Latitude, Longitude
   */
  public double[] getLastLocation()
  {
    return lastLocation;
  }

  @Override
  public void registerListener() 
  {   
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);   
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);   
  }

  @Override
  public void unRegisterListener() 
  {
    locationManager.removeUpdates(locationListener);    
  }
}

然后 activity.onLocationChange() 就像

  public void onLocationChange() 
  {
    locationUpdated = true;

    double[] coordinates = location.getLastLocation();

    EditText lon = (EditText) activity.findViewById(R.id.longitude_value);
    lon.setText(String.valueOf(coordinates[Location.IDX_LONGITUDE]));

    EditText lat = (EditText) activity.findViewById(R.id.latitude_value);   
    lat.setText(String.valueOf(coordinates[Location.IDX_LATITIDE]));
  }

【讨论】:

  • 我个人已经阻止了 EditTexts 以便立即进行可视化调试。我编辑了我的答案。我看到你在下面谈论“全在一个班级”。它不必是那样的。这取决于您如何组织和设计代码。我个人更喜欢把大班分成小班。还建议使用接口。最后但同样重要的是,我建议您在尝试为 Android 编程之前阅读 Android 文档。
  • lastLocation[IDX_LATITIDE] = location.getLatitude(); lastLocation[IDX_LONGITUDE] = location.getLongitude();活动.onLocationChange();位置无法解析为变量,知道为什么吗?为什么要阻止 EditTexts?我一直在阅读Beginning ANdroid,但找不到关于这个主题的任何内容,在屏幕上阅读大量文字让我的眼睛蒙上了一层阴影。
  • 抱歉,有暴风雨,断电了十秒钟,显然它传达了我所说的一些内容。
  • 哦,好的,没问题。我猜你的意思是 lastLocation 无法解决?因为 location 作为参数传递...这是因为这是我班级的另一个属性。我会发布整个课程,这样你就可以看到我是如何做到的。我使用这个 Location 类作为通用助手,所以我可以在任何其他项目中重用这个相同的类。请记住,我不会发布任何复制粘贴代码,因为我没有时间而且这不是我的风格。我希望您了解如何做而不是复制粘贴。
  • 太棒了,不,我不想这样复制和粘贴,我想知道发生了什么!书告诉我一件事,互联网告诉我另一件事。改变了我的代码现在太荒谬了!用不同的代码打开了几个选项卡,看看我可以先开始工作(如果有的话)。非常感谢您抽出宝贵时间提供帮助。谢谢。
猜你喜欢
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
  • 2019-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-17
相关资源
最近更新 更多