【问题标题】:How to Get City Name by Latitude &Longitude in android?如何在android中通过纬度和经度获取城市名称?
【发布时间】:2014-04-14 23:04:35
【问题描述】:

我想按当前位置的城市名称,但我有纬度和经度。如何得到它?我使用按钮单击然后我得到双值纬度和经度。我在下面的代码。请帮助我。

谢谢!!

Button btnShowLocation;

    GPSTracker gps;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {       
                // create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // check if GPS enabled     
                if(gps.canGetLocation()){

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    // \n is for new line
                    Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();    
                }else{

                    gps.showSettingsAlert();
                }

            }
        });

我编辑了下面的代码,但没有得到城市名,请帮帮我!!!

Button btnShowLocation;

    GPSTracker gps;
    String CityName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // check if GPS enabled
                if (gps.canGetLocation()) {

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    Geocoder geocoder = new Geocoder(
                            AndroidGPSTrackingActivity.this, Locale
                                    .getDefault());
                    List<Address> addresses;
                    try {
                        Log.v("log_tag", "latitude" + latitude);
                        Log.v("log_tag", "longitude" + longitude);
                        addresses = geocoder.getFromLocation(latitude,
                                longitude, 1);
                        Log.v("log_tag", "addresses+)_+++" + addresses);
                        CityName = addresses.get(0).getAddressLine(0);
                        Log.v("log_tag", "CityName" + CityName);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    // \n is for new line
                    Toast.makeText(
                            getApplicationContext(),
                            "Your Location is - \nLat: " + latitude
                                    + "\nLong: " + longitude, Toast.LENGTH_LONG)
                            .show();
                } else {

                    gps.showSettingsAlert();
                }

            }
        });

但我在下面得到错误::::

03-11 17:01:46.465: W/System.err(27587): java.io.IOException: Service not Available
03-11 17:01:46.465: W/System.err(27587):    at android.location.Geocoder.getFromLocation(Geocoder.java:136)
03-11 17:01:46.465: W/System.err(27587):    at com.example.gpstracking.AndroidGPSTrackingActivity$1.onClick(AndroidGPSTrackingActivity.java:81)
03-11 17:01:46.465: W/System.err(27587):    at android.view.View.performClick(View.java:4191)
03-11 17:01:46.475: W/System.err(27587):    at android.view.View$PerformClick.run(View.java:17229)
03-11 17:01:46.475: W/System.err(27587):    at android.os.Handler.handleCallback(Handler.java:615)
03-11 17:01:46.475: W/System.err(27587):    at android.os.Handler.dispatchMessage(Handler.java:92)
03-11 17:01:46.475: W/System.err(27587):    at android.os.Looper.loop(Looper.java:137)
03-11 17:01:46.475: W/System.err(27587):    at android.app.ActivityThread.main(ActivityThread.java:4960)
03-11 17:01:46.475: W/System.err(27587):    at java.lang.reflect.Method.invokeNative(Native Method)
03-11 17:01:46.475: W/System.err(27587):    at java.lang.reflect.Method.invoke(Method.java:511)
03-11 17:01:46.475: W/System.err(27587):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
03-11 17:01:46.475: W/System.err(27587):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
03-11 17:01:46.475: W/System.err(27587):    at dalvik.system.NativeStart.main(Native Method)
03-11 17:02:21.335: W/IInputConnectionWrapper(27587): getSelectedText on inactive InputConnection
03-11 17:02:21.335: W/IInputConnectionWrapper(27587): setComposingText on inactive InputConnection
03-11 17:02:21.425: W/IInputConnectionWrapper(27587): getExtractedText on inactive InputConnection

【问题讨论】:

标签: android map gps location


【解决方案1】:

使用这个:

 Geocoder geocoder = new Geocoder(this, Locale.getDefault());
 List<Address> addresses = geocoder.getFromLocation(MyLat, MyLong, 1);
 String cityName = addresses.get(0).getAddressLine(0);
 String stateName = addresses.get(0).getAddressLine(1);
 String countryName = addresses.get(0).getAddressLine(2);

有关详细的谷歌地图示例,请查看以下链接: http://www.demoadda.com/demo/android/load-googlemap_107

对于后台位置更新: http://www.demoadda.com/demo/android/download-android-background-location-update-service-demo_21

【讨论】:

  • 我认为@Mayank Saini 的答案更适合如果想了解具体情况。地址行最终可能包含比必要更多的信息(如子位置)。 'addresses.get(0).getCountryName()` 也将有助于获取国家/地区名称。
  • 如果您只想要城市名称,那么您应该改用addresses.get(0).getLocality()addresses.get(0).getAddressLine(0) 可能会根据地址为您提供除城市名称之外的更多信息(阅读Geocoder 文档)。但是 Locality 会准确地为您提供 cityName。 :)
  • 不要使用地理编码器。它会在很多设备上引发异常。
  • @kiShan 出现问题 ni some device not found city?你能帮我吗..
  • 有时地理编码器返回空值。您可以检查结果并再次调用结果。
【解决方案2】:

在你的 onClick 上添加这个:

Geocoder gcd = new Geocoder(AndroidGPSTrackingActivity.this, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) 
    System.out.println(addresses.get(0).getLocality());

【讨论】:

  • 记录您的纬度和经度并检查它们是否为 0。
【解决方案3】:
gps = new LocationAddress(getActivity());
if (gps.canGetLocation()) {
  double latitude = gps.getLatitude();
  double longitude = gps.getLongitude();
  Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
  //List<Address> addresses =geocoder.getFromLocation(latitude, longitude, 1);

  try {
    List < Address > addresses = geocoder.getFromLocation(latitude, longitude, 1);
    String address = addresses.get(0).getSubLocality();
    String cityName = addresses.get(0).getLocality();
    String stateName = addresses.get(0).getAdminArea();
    txt_paddress.setText(address);
    txt_city.setText(cityName);
    txt_state.setText(stateName);

  } catch (IOException e) {
    e.printStackTrace();
  }
} else {
  gps.showSettingsAlert();
}

【讨论】:

  • 一些解释会很好,请编辑你的答案
【解决方案4】:

使用它并将您的 lat long 值传递给它。

    Geocoder geocoder;
    List<Address> addresses;
    geocoder = new Geocoder(getContext(), Locale.getDefault());

    try {
        addresses = geocoder. getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
        String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        String city = addresses.get(0).getLocality();
        String state = addresses.get(0).getAdminArea();
        String country = addresses.get(0).getCountryName();else return NULL
    } catch (IOException e) {
        e.printStackTrace();
    }

【讨论】:

    【解决方案5】:

    对于我的国家(越南)getLocality 将返回 null,addresses.get(0).getAddressLine(0) 将返回地区而非城市

    所以我会这样做

    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
    
    int maxAddressLine = addresses.get(0).getMaxAddressLineIndex();
    
    String countryName = addresses.get(0).getAddressLine(maxAddressLine);
    String stateName = addresses.get(0).getAddressLine(maxAddressLine-1);
    String cityName = addresses.get(0).getAddressLine(maxAddressLine-2);
    

    【讨论】:

      【解决方案6】:

      使用地理编码器。传递经纬度,得到城市名称和地址。

      try {
      
          Geocoder geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
          List < Address > addresses = geo.getFromLocation(latitude, longitude, 1);
          if (addresses.isEmpty()) {
              addres.setText("Waiting for Location");
          } else {
              if (addresses.size() > 0) {
                  addres.setText(addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() + ", " + addresses.get(0).getAdminArea() + ", " + addresses.get(0).getCountryName());
                  //Toast.makeText(getApplicationContext(), "Address:- " + addresses.get(0).getFeatureName() + addresses.get(0).getAdminArea() + addresses.get(0).getLocality(), Toast.LENGTH_LONG).show();
              }
          }
      } catch (Exception e) {
          e.printStackTrace(); // getFromLocation() may sometimes fail
      }
      

      【讨论】:

        【解决方案7】:

        我只需要显示国家和城市名称,所以我使用以下代码 在这里,我使用“en”始终以英语而不是用户区域语言显示国家和城市名称。否则你可以Locale.getDefault()方法。

         double latitude = location.getLatitude();
         double longitude = location.getLongitude();
        
         Locale locale = new Locale("en"); //OR Locale.getDefault()
        
         Geocoder geocoder = new Geocoder(MainActivity.this, locale);
         List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
        
         updatedCity = addresses.get(0).getLocality();
        
         if (updatedCity == null) {
             updatedCity = addresses.get(0).getAdminArea();
         }
        
         updatedCountry = addresses.get(0).getCountryName();
        

        【讨论】:

          【解决方案8】:

          以上任何一个答案都不能解决我的问题

          印度尼西亚的情况,您可以拨打addresses.get(0).getSubAdminArea()获取城市名称

          【讨论】:

            猜你喜欢
            • 2013-12-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-10-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多