【问题标题】:How to get complete address from latitude and longitude?如何从纬度和经度获得完整的地址?
【发布时间】:2012-03-13 15:08:22
【问题描述】:

我想从 android 中的纬度和经度中获取以下值

  1. 街道地址
  2. 城市/州
  3. 邮编
  4. 完整地址

如何做到这一点?

【问题讨论】:

  • 你需要使用谷歌的反向 API 来做同样的事情
  • 我有一个疑问,它完全免费,可以无限使用或定价?

标签: android google-maps location


【解决方案1】:
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());

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();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

欲知更多详情,请关注Android-Location-Address

【讨论】:

  • 您提供的地址是完整地址还是街道地址?
  • getAddressLine() 对于获取城市/国家/地区不可靠,因为地址行可能会因地理编码详细程度而异。请改用getLocality()getCountryName()
  • @Shubh - 试试这个网址 - "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + ","+ longitude + "&amp;sensor=true"。它将返回 Json 响应。
  • 地理编码器查找可能需要很长时间。将其称为单独的线程要好得多。如Google Doc example
  • 您无需指定Locale.getDefault()new Geocoder(this) 将自动使用默认语言环境。
【解决方案2】:

试试这个我的朋友

 private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
            String strAdd = "";
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            try {
                List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
                if (addresses != null) {
                    Address returnedAddress = addresses.get(0);
                    StringBuilder strReturnedAddress = new StringBuilder("");

                    for (int i = 0; i <= returnedAddress.getMaxAddressLineIndex(); i++) {
                        strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                    }
                    strAdd = strReturnedAddress.toString();
                    Log.w("My Current loction address", strReturnedAddress.toString());
                } else {
                    Log.w("My Current loction address", "No Address returned!");
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.w("My Current loction address", "Canont get Address!");
            }
            return strAdd;
        }

【讨论】:

  • 很好的答案。谢谢。
  • 在 for 循环中使用 i
  • 它给出 java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
【解决方案3】:

CityCountry 并不总是进入地址 Line 1 和 Line 2...

例如here

所以,

Geocoder geocoder = new Geocoder(context, Locale.getDefault());

List<Address> addresses  = geocoder.getFromLocation(latitude,longitude, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String zip = addresses.get(0).getPostalCode();
String country = addresses.get(0).getCountryName();

【讨论】:

    【解决方案4】:

    最后一个技巧是从 Lat-Long 获取地址(地理坐标)。您可以简单地点击通过纬度和经度的谷歌地图网络服务。它只是一个 GET-Method 网络服务。

    它将返回 JSON 响应,可以轻松解析以获取地址。这个网址是:

    http://maps.googleapis.com/maps/api/geocode/json?latlng=32,75&sensor=true
    

    您可以将 32,75 替换为 lat,long

    【讨论】:

    • 这是否记录在任何地方...?
    • 现在已弃用。
    • 您现在无法在没有身份验证的情况下向该 API 请求
    【解决方案5】:

    在 onCreate()..

    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, this);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(bestProvider);
    
        if (location == null) {
            Toast.makeText(getApplicationContext(), "GPS signal not found",
                    3000).show();
        }
        if (location != null) {
            Log.e("location", "location--" + location);
            Log.e("latitude at beginning",
                    "@@@@@@@@@@@@@@@" + location.getLatitude());
            onLocationChanged(location);
        }
    

    在onLocationChanged()中编写代码

    @Override
    public void onLocationChanged(Location location) {
    
        Geocoder geocoder;
        List<Address> addresses;
        geocoder = new Geocoder(this, Locale.getDefault());
    
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    
        Log.e("latitude", "latitude--" + latitude);
    
        try {
            Log.e("latitude", "inside latitude--" + latitude);
            addresses = geocoder.getFromLocation(latitude, longitude, 1);
    
            if (addresses != null && addresses.size() > 0) {
                String address = addresses.get(0).getAddressLine(0); 
                String city = addresses.get(0).getLocality();
                String state = addresses.get(0).getAdminArea();
                String country = addresses.get(0).getCountryName();
                String postalCode = addresses.get(0).getPostalCode();
                String knownName = addresses.get(0).getFeatureName(); 
    
                locationTxt.setText(address + " " + city + " " + country);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    【讨论】:

      【解决方案6】:

      您正在寻找术语“地理编码”。

      短篇小说是你需要做的:

      Geocoder geocoder = new Geocoder(this, Locale.getDefault());
      List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
      

      要了解更多信息,您应该阅读地理编码器here

      【讨论】:

      【解决方案7】:
        public static String getAddressFromLatLng(Context context, LatLng latLng) {
          Geocoder geocoder;
          List<Address> addresses;
          geocoder = new Geocoder(context, Locale.getDefault());
          try {
              addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
              return addresses.get(0).getAddressLine(0);
          } catch (Exception e) {
              e.printStackTrace();
              return "";
          }
      }
      

      【讨论】:

        【解决方案8】:

        使用 Geocoder 类很容易从纬度和经度中获取完整的地址。遵循代码示例。希望这会有所帮助!

         if (l != null) {
                val lat = l.latitude
                val lon = l.longitude
        
                val geocoder = Geocoder(this, Locale.getDefault())
                val addresses: List<Address>
        
                addresses = geocoder.getFromLocation(lat, lon, 1) 
        
                val address = addresses[0].getAddressLine(0)
                val address2 = addresses[0].getAddressLine(1)
                val city = addresses[0].locality
                val state = addresses[0].adminArea
                val country = addresses[0].countryName
                val postalCode = addresses[0].postalCode
                val knownName = addresses[0].featureName
        
                val message =
                        "Emergency situation. Call for help. My location is: " + address + "." + "http://maps.google.com/maps?saddr=" + lat + "," + lon
        
            }
        

        您只能使用地址值,因为它会为您提供所有完整的地址。如果您需要单个组件,也可以使用其他组件。

        【讨论】:

          【解决方案9】:

          只需使用此方法并传递您的经度、经度即可。

          public static void getAddress(Context context, double LATITUDE, double LONGITUDE{
              //Set Address
              try {
                  Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                  List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
          
                  if (addresses != null && addresses.size() > 0) {
                      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();
                      String postalCode = addresses.get(0).getPostalCode();
                      String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
                      Log.d(TAG, "getAddress:  address" + address);
                      Log.d(TAG, "getAddress:  city" + city);
                      Log.d(TAG, "getAddress:  state" + state);
                      Log.d(TAG, "getAddress:  postalCode" + postalCode);
                      Log.d(TAG, "getAddress:  knownName" + knownName);
                  }
          
              } catch (IOException e) {
                  e.printStackTrace();
              }
              return;
          }
          

          【讨论】:

            【解决方案10】:

            如果你使用Kotlin语言,我创建这个方法直接获取地址位置

            private fun getAddress(latLng: LatLng): String {
                val geocoder = Geocoder(this, Locale.getDefault())
                val addresses: List<Address>?
                val address: Address?
                var addressText = ""
            
                addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)
            
                if (addresses.isNotEmpty()) {
                    address = addresses[0]
                    addressText = address.getAddressLine(0)
                } else{
                    addressText = "its not appear"
                }
                return addressText
            }
            

            但是当你调用这个方法时,这个方法只是返回字符串值

            如果您想获取所有地址,只需使用此方法/功能

            fun getAddress(latLng: LatLng){
                val geocoder = Geocoder(this, Locale.getDefault())
                val addresses: List<Address>?
                val address: Address?
                var fulladdress = ""
                addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)
            
                if (addresses.isNotEmpty()) {
                    address = addresses[0]
                    fulladdress = address.getAddressLine(0) // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex
                    var city = address.getLocality();
                    var state = address.getAdminArea();
                    var country = address.getCountryName();
                    var postalCode = address.getPostalCode();
                    var knownName = address.getFeatureName(); // Only if available else return NULL
                } else{
                    fulladdress = "Location not found"
                }
            }
            

            【讨论】:

            • 太棒了,正是我想要的……谢谢 Azhar
            【解决方案11】:
              Geocoder geocoder =new Geocoder(mContext, Locale.getDefault());
             // Get the current location from the input parameter list
              Location loc = params[0];
             // Create a list to contain the result address
              List<Address> addresses = null;
              try {
                 addresses = geocoder.getFromLocation(loc.getLatitude(),
                         loc.getLongitude(), 10);
             } catch (IOException e1) {
                       Log.e("LocationSampleActivity","IO Exception in getFromLocation()");
                  e1.printStackTrace();
            
             } catch (IllegalArgumentException e2) {
             // Error message to post in the log
             String errorString = "Illegal arguments " +
                     Double.toString(loc.getLatitude()) +
                     " , " +
                     Double.toString(loc.getLongitude()) +
                     " passed to address service";
             Log.e("LocationSampleActivity", errorString);
             e2.printStackTrace();
            
             }
             Address address=null;
             String zip=null;
             String city=null;
             String state=null;
             StringBuffer st=new StringBuffer();
             // If the reverse geocode returned an address
             if (addresses != null && addresses.size() > 0) {
             String       add=addresses.get(0).getAddressLine(0)+","
              +addresses.get(0).getSubAdminArea()+","
              +addresses.get(0).getSubLocality();
              city=addresses.get(0).getLocality();
              state=addresses.get(0).getAdminArea();
                 // Get the first address
              for(int i=0 ;i<addresses.size();i++){
              address = addresses.get(i);
               if(address.getPostalCode()!=null){
            zip=address.getPostalCode();
            break;
                 }
            
                  }
            

            【讨论】:

              【解决方案12】:

              您可以轻松使用以下代码获取地址。

              import java.io.IOException;
              import java.util.List;
              import java.util.Locale;
              
              import android.app.AlertDialog;
              import android.app.Service;
              import android.content.Context;
              import android.content.DialogInterface;
              import java.io.IOException;
              import java.util.List;
              import java.util.Locale;
              
              import android.app.AlertDialog;
              import android.app.Service;
              import android.content.Context;
              import android.content.DialogInterface;
              import android.content.Intent;
              import android.location.Address;
              import android.location.Geocoder;
              import android.location.Location;
              import android.location.LocationListener;
              import android.location.LocationManager;
              import android.os.Bundle;
              import android.os.IBinder;
              import android.provider.Settings;
              
              public class GPSService extends Service implements LocationListener {
              
              // saving the context for later use
              private final Context mContext;
              
              // if GPS is enabled
              boolean isGPSEnabled = false;
              // if Network is enabled
              boolean isNetworkEnabled = false;
              // if Location co-ordinates are available using GPS or Network
              public boolean isLocationAvailable = false;
              
              // Location and co-ordinates coordinates
              Location mLocation;
              double mLatitude;
              double mLongitude;
              
              // Minimum time fluctuation for next update (in milliseconds)
              private static final long TIME = 30000;
              // Minimum distance fluctuation for next update (in meters)
              private static final long DISTANCE = 20;
              
              // Declaring a Location Manager
              protected LocationManager mLocationManager;
              
              public GPSService(Context context) {
                  this.mContext = context;
                  mLocationManager = (LocationManager) mContext
                          .getSystemService(LOCATION_SERVICE);
              
              }
              
              /**
               * Returs the Location
               * 
               * @return Location or null if no location is found
               */
              public Location getLocation() {
                  try {
              
                      // Getting GPS status
                      isGPSEnabled = mLocationManager
                              .isProviderEnabled(LocationManager.GPS_PROVIDER);
              
                      // If GPS enabled, get latitude/longitude using GPS Services
                      if (isGPSEnabled) {
                          mLocationManager.requestLocationUpdates(
                                  LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
                          if (mLocationManager != null) {
                              mLocation = mLocationManager
                                      .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                              if (mLocation != null) {
                                  mLatitude = mLocation.getLatitude();
                                  mLongitude = mLocation.getLongitude();
                                  isLocationAvailable = true; // setting a flag that
                                                              // location is available
                                  return mLocation;
                              }
                          }
                      }
              
                      // If we are reaching this part, it means GPS was not able to fetch
                      // any location
                      // Getting network status
                      isNetworkEnabled = mLocationManager
                              .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
              
                      if (isNetworkEnabled) {
                          mLocationManager.requestLocationUpdates(
                                  LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
                          if (mLocationManager != null) {
                              mLocation = mLocationManager
                                      .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                              if (mLocation != null) {
                                  mLatitude = mLocation.getLatitude();
                                  mLongitude = mLocation.getLongitude();
                                  isLocationAvailable = true; // setting a flag that
                                                              // location is available
                                  return mLocation;
                              }
                          }
                      }
                      // If reaching here means, we were not able to get location neither
                      // from GPS not Network,
                      if (!isGPSEnabled) {
                          // so asking user to open GPS
                          askUserToOpenGPS();
                      }
              
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
                  // if reaching here means, location was not available, so setting the
                  // flag as false
                  isLocationAvailable = false;
                  return null;
              }
              
              /**
               * Gives you complete address of the location
               * 
               * @return complete address in String
               */
              public String getLocationAddress() {
              
                  if (isLocationAvailable) {
              
                      Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
                      // Get the current location from the input parameter list
                      // Create a list to contain the result address
                      List<Address> addresses = null;
                      try {
                          /*
                           * Return 1 address.
                           */
                          addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
                      } catch (IOException e1) {
                          e1.printStackTrace();
                          return ("IO Exception trying to get address:" + e1);
                      } catch (IllegalArgumentException e2) {
                          // Error message to post in the log
                          String errorString = "Illegal arguments "
                                  + Double.toString(mLatitude) + " , "
                                  + Double.toString(mLongitude)
                                  + " passed to address service";
                          e2.printStackTrace();
                          return errorString;
                      }
                      // If the reverse geocode returned an address
                      if (addresses != null && addresses.size() > 0) {
                          // Get the first address
                          Address address = addresses.get(0);
                          /*
                           * Format the first line of address (if available), city, and
                           * country name.
                           */
                          String addressText = String.format(
                                  "%s, %s, %s",
                                  // If there's a street address, add it
                                  address.getMaxAddressLineIndex() > 0 ? address
                                          .getAddressLine(0) : "",
                                  // Locality is usually a city
                                  address.getLocality(),
                                  // The country of the address
                                  address.getCountryName());
                          // Return the text
                          return addressText;
                      } else {
                          return "No address found by the service: Note to the developers, If no address is found by google itself, there is nothing you can do about it.";
                      }
                  } else {
                      return "Location Not available";
                  }
              
              }
              
              
              
              /**
               * get latitude
               * 
               * @return latitude in double
               */
              public double getLatitude() {
                  if (mLocation != null) {
                      mLatitude = mLocation.getLatitude();
                  }
                  return mLatitude;
              }
              
              /**
               * get longitude
               * 
               * @return longitude in double
               */
              public double getLongitude() {
                  if (mLocation != null) {
                      mLongitude = mLocation.getLongitude();
                  }
                  return mLongitude;
              }
              
              /**
               * close GPS to save battery
               */
              public void closeGPS() {
                  if (mLocationManager != null) {
                      mLocationManager.removeUpdates(GPSService.this);
                  }
              }
              
              /**
               * show settings to open GPS
               */
              public void askUserToOpenGPS() {
                  AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext);
              
                  // Setting Dialog Title
                  mAlertDialog.setTitle("Location not available, Open GPS?")
                  .setMessage("Activate GPS to use use location services?")
                  .setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
                      public void onClick(DialogInterface dialog, int which) {
                          Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                          mContext.startActivity(intent);
                          }
                      })
                      .setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
                          public void onClick(DialogInterface dialog, int which) {
                              dialog.cancel();
                              }
                          }).show();
              }
              
              /** 
               * Updating the location when location changes
               */
              @Override
              public void onLocationChanged(Location location) {
                  mLatitude = location.getLatitude();
                  mLongitude = location.getLongitude();
              }
              
              @Override
              public void onProviderDisabled(String provider) {
              }
              
              @Override
              public void onProviderEnabled(String provider) {
              }
              
              @Override
              public void onStatusChanged(String provider, int status, Bundle extras) {
              }
              
              @Override
              public IBinder onBind(Intent arg0) {
                  return null;
              }
              
              }
              

              【讨论】:

                【解决方案13】:

                你可以创建类

                public class GeoLocation {
                
                private Context mContext;
                
                private String mLatitude;
                private String mLongtitude;
                private String mStreet;
                private String mHouseNumber;
                private String mPostalCode;
                private String mCity;
                
                private Location mMarkerLocation;
                
                public GeoLocation (Context context) {
                    mContext = context;
                }
                
                public String getStreet () {
                    return mStreet;
                }
                
                public String getHouseNumber () {
                    return mHouseNumber;
                }
                
                public String getPostalCode () {
                    return mPostalCode;
                }
                
                public String getCity () {
                    return mCity;
                }
                
                public String getLatitude () {
                    return mLatitude;
                }
                
                public String getLongtitude () {
                    return mLongtitude;
                }
                
                // Lookup address via reverse geolocation
                // Call this one
                public void lookUpAddress (Location markerLocation) {
                    mMarkerLocation = markerLocation;
                    if (Geocoder.isPresent()) {
                        (new GetAddressTask(mContext)).execute();
                    }
                }
                
                public class GetAddressTask extends AsyncTask<android.location.Location, Void, String> {
                
                    public GetAddressTask (Context context) {
                        super();
                        mContext = context;
                    }
                
                    @Override
                    protected String doInBackground (android.location.Location... params) {
                        Geocoder geocoder =
                                new Geocoder(mContext, Locale.getDefault());
                        android.location.Location location = params[0];
                
                        List<Address> addresses = null;
                        try {
                            if (mMarkerLocation != null) {
                                addresses = geocoder.getFromLocation(mMarkerLocation.getLatitude(),
                                        mMarkerLocation.getLongitude(), 1);
                            }
                        } catch (IOException exception) {
                            Log.e("ComplaintLocation",
                                    "IO Exception in getFromLocation()", exception);
                
                            return ("IO Exception trying to get address");
                        } catch (IllegalArgumentException exception) {
                            String errorString = "Illegal arguments " +
                                    Double.toString(location.getLatitude()) + " , " +
                                    Double.toString(location.getLongitude()) + " passed to address service";
                            Log.e("LocationSampleActivity", errorString, exception);
                
                            return errorString;
                        }
                
                        if (addresses != null && addresses.size() > 0) {
                            Address address = addresses.get(0);
                
                            if (address.getMaxAddressLineIndex() > 0) {
                                return String.format(
                                        "%s/%s/%s/%s/%s/%s",
                                        address.getLatitude(), // 0
                                        address.getLongitude(), // 1
                                        address.getThoroughfare(), // 2
                                        address.getSubThoroughfare(), //3
                                        address.getPostalCode(), // 4
                                        address.getLocality()); // 5
                            } else {
                                return String.format(
                                        "%s/%s/%s/%s",
                                        address.getLatitude(), // 0
                                        address.getLongitude(), // 1
                                        address.getPostalCode(), // 2
                                        address.getLocality()); // 3
                            }
                        } else return "No address found";
                    }
                
                    // Format address string after lookup
                    @Override
                    protected void onPostExecute (String address) {
                
                        String[] addressFields = TextUtils.split(address, "/");
                        Log.d("ADDRESS ARRAY", Arrays.toString(addressFields));
                
                        // Workaround: doInBackground can only return Strings instead of, for example, an
                        // Address instance or a String[] directly. To be able to use TextUtils.isEmpty()
                        // on fields returned by this method, set each String that currently reads "null" to
                        // a null reference
                        for (int fieldcnt = 0; fieldcnt < addressFields.length; ++fieldcnt) {
                            if (addressFields[fieldcnt].equals("null"))
                                addressFields[fieldcnt] = null;
                        }
                
                        switch (addressFields.length) {
                            case 4:
                                mStreet = null;
                                mHouseNumber = null;
                                mLatitude = addressFields[0];
                                mLongtitude = addressFields[1];
                                mPostalCode = addressFields[2];
                                mCity = addressFields[3];
                                break;
                            case 6:
                                mLatitude = addressFields[0];
                                mLongtitude = addressFields[1];
                                mStreet = addressFields[2];
                                mHouseNumber = addressFields[3];
                                mPostalCode = addressFields[4];
                                mCity = addressFields[5];
                                break;
                            default:
                                mLatitude = null;
                                mLongtitude = null;
                                mStreet = null;
                                mHouseNumber = null;
                                mPostalCode = null;
                                mCity = null;
                                break;
                        }
                
                        Log.d("GeoLocation Street", mStreet);
                        Log.d("GeoLocation No.", mHouseNumber);
                        Log.d("GeoLocation Postalcode", mPostalCode);
                        Log.d("GeoLocation Locality", mCity);
                        Log.d("GeoLocation Lat/Lng", "[" + mLatitude + ", " + mLongtitude + 
                    "]");
                    }
                 }
                   }
                

                然后你使用它实例化它

                GeoLocation geoLocation = new GeoLocation(getActivity()); // or (this) if 
                called from an activity and not from a fragment
                mGeoLocation.lookUpAddress(LOCATION_FROM_MAP);
                

                【讨论】:

                  【解决方案14】:

                  似乎还没有人提供 Google Docs (https://developer.android.com/training/location/display-address#java) 建议的解决方案。正确的解决方案应该使用 IntentService 进行网络调用以进行反向地理编码。

                  使用意图服务而不是 AsyncTask,因为它不绑定到任何特定活动。 IE。它有自己的生命周期。地理编码完成后,IntentService 将自行停止。

                  public class GeocodingService extends IntentService {
                  
                      public GeocodingService() {
                          super("GeocodingService");
                      }
                  
                  
                      @Override
                      protected void onHandleIntent(@Nullable Intent intent) {
                          if (intent == null) {
                              return;
                          }
                  
                          Geocoder geocoder = new Geocoder(this, Locale.getDefault());
                          String errorMessage = "";
                          BCCDatabase BCCDatabase = skicompanion.skicompanion.storage.BCCDatabase.getInstance(getApplicationContext());
                  
                          // Get the location passed to this service through an extra.
                          Location location = intent.getParcelableExtra(
                                  "location");
                          long trackID = intent.getLongExtra("trackID", -1);
                  
                          List<Address> addresses = null;
                          String addressString = "";
                  
                          try {
                              addresses = geocoder.getFromLocation(
                                      location.getLatitude(),
                                      location.getLongitude(),
                                      1);
                          } catch (IOException ioException) {
                              // Catch network or other I/O problems.
                              errorMessage = "service not available";
                              Log.d(Constants.SkiCompanionDebug, errorMessage, ioException);
                          } catch (IllegalArgumentException illegalArgumentException) {
                              // Catch invalid latitude or longitude values.
                              errorMessage = "invalid lat long used";
                              Log.d(Constants.SkiCompanionDebug, errorMessage + ". " +
                                      "Latitude = " + location.getLatitude() +
                                      ", Longitude = " +
                                      location.getLongitude(), illegalArgumentException);
                          }
                  
                          // Handle case where no address was found.
                          if (addresses == null || addresses.size()  == 0) {
                              if (errorMessage.isEmpty()) {
                                  errorMessage = "no address found";
                                  Log.d(Constants.SkiCompanionDebug, errorMessage);
                              }
                          } else {
                              if(addresses.get(0).getLocality() != null){
                                  addressString += addresses.get(0).getLocality() + ", ";
                              }
                              if(addresses.get(0).getAdminArea() != null){
                                  addressString += addresses.get(0).getAdminArea() + ", ";
                              }
                              if(addresses.get(0).getCountryName() != null){
                                  addressString += addresses.get(0).getCountryName();
                              }
                              //updating DB
                              BCCDatabase.setTrackLocation(trackID, addressString);
                  
                              Log.d(Constants.SkiCompanionDebug, "address found: "+ addressString);
                          }
                      }
                  }
                  

                  【讨论】:

                  • 我同意,您应该使用 IntentService 进行反向地理编码。
                  【解决方案15】:

                  使用它对我有用:D

                  获取经纬度的json数据。

                  https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyAr29XeWWAeWZcrOgjjfs3iSnqkWtAz4No&latlng=2.1812,102.4266&sensor=true

                  用你自己的地方改变纬度,经度。

                  https://maps.googleapis.com/maps/api/geocode/json?key=&latlng="latitude","longitude"&sensor=true

                  您可以使用自己的密钥更改 。

                  需要在谷歌控制台中为新的 api 密钥启用 api 服务。

                  希望对你有帮助:D

                  【讨论】:

                    【解决方案16】:

                    1 - 您在 onCreate 方法中为 LocationManager 和 LocationListener 创建变量。

                    2 - 检查是否有权限,因此执行位置更新并从 locationManager 获取 lastKnownLocation 否则您请求权限

                    3 - 在主类中创建 onRequestPermissionResult 并检查是否有权限然后执行位置更新

                    4 - 创建包含 Geocoder 变量的分离方法并创建一个列表以放置您所在位置的坐标, 为了安全起见,您检查列表是否存在以及我们想要在该列表中的每个信息是否存在,然后您使用 (getThoroughfare ==> for Street Address), (getLocality ==> for City / State), (getPostalCode = => 用于 Zip),(getAdminArea ==> 用于完整地址)

                    5 - 最后,您在使用(lastKnownLocation 参数 ==> 以在应用程序运行时显示地址)和 onLocationChanged (位置参数 ==> 以在位置更改时显示地址)检查权限后调用该方法

                    代码部分:

                    LocationManager locationManager;
                    
                    LocationListener locationListener;
                    
                    @SuppressLint("MissingPermission")
                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                    
                        super.onCreate(savedInstanceState);
                    
                        setContentView(R.layout.activity_main);
                    
                        locationManager  = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
                    
                        locationListener = new LocationListener() {
                    
                            @Override
                            public void onLocationChanged(Location location) {
                    
                                updateLocation(location);
                    
                            }
                            @Override public void onStatusChanged(String provider, int status, Bundle extras) {
                    
                            }
                            @Override
                            public void onProviderEnabled(String provider) {
                            }
                            @Override
                            public void onProviderDisabled(String provider) {
                            }
                        };
                    
                        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                    
                            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                    
                            Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    
                            updateLocation(lastKnownLocation);
                    
                        }else {
                    
                            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                        }
                    }
                    
                    @Override
                    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
                    
                        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                    
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    
                            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
                    
                                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                            }
                        }
                    }
                    
                    
                    public void updateLocation ( Location location){
                    
                    
                        Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
                        try {
                            List<Address> listAddresses = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
                    
                            String address = "Could not find location :(";
                    
                            if (listAddresses != null && listAddresses.size() > 0) {
                    
                                if (listAddresses.get(0).getThoroughfare() != null) {
                    
                                    address = listAddresses.get(0).getThoroughfare() + " ";
                                }
                    
                                if (listAddresses.get(0).getLocality() != null) {
                    
                                    address += listAddresses.get(0).getLocality() + " ";
                                }
                    
                                if (listAddresses.get(0).getPostalCode() != null) {
                    
                                    address += listAddresses.get(0).getPostalCode() + " ";
                                }
                    
                                if (listAddresses.get(0).getAdminArea() != null) {
                    
                                    address += listAddresses.get(0).getAdminArea();
                                }
                            }
                    
                            Log.i("Address",address);
                    
                        } catch (Exception e) {
                    
                            e.printStackTrace();
                    
                        }
                    }
                    }
                    

                    【讨论】:

                      【解决方案17】:

                      尝试使用地理编码器使用以下代码:

                        Geocoder gcd = new Geocoder(MainActivity.this, Locale.getDefault());
                        List<Address> geoAddresses = geoAddresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                        if (geoAddresses.size() > 0) {
                            String mUserLocation = "";
                            for (int i = 0; i < 4; i++) { //Since it return only four value we declare this as static.
                                 mUserLocation = mUserLocation + geoAddresses.get(0).getAddressLine(i).replace(",", "") + ", ";
                              } 
                          }
                      

                      【讨论】:

                        【解决方案18】:
                        public String getAddress(LatLng latLng) {
                            String cAddress = "";
                            if (latLng == null) {
                                errorMessage = "no_location_data_provided";
                                Log.wtf(TAG, errorMessage);
                                return "";
                            }
                            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
                        
                            // Address found using the Geocoder.
                            List<Address> addresses = null;
                        
                            try {
                                // Using getFromLocation() returns an array of Addresses for the area immediately
                                // surrounding the given latitude and longitude. The results are a best guess and are
                                // not guaranteed to be accurate.
                                addresses = geocoder.getFromLocation(
                                        latLng.latitude,
                                        latLng.longitude,
                                        // In this sample, we get just a single address.
                                        1);
                            } catch (IOException ioException) {
                                // Catch network or other I/O problems.
                                errorMessage = "service_not_available";
                                Log.e(TAG, errorMessage, ioException);
                            } catch (IllegalArgumentException illegalArgumentException) {
                                // Catch invalid latitude or longitude values.
                                errorMessage = "invalid_lat_long_used";
                                Log.e(TAG, errorMessage + ". " +
                                        "Latitude = " + latLng.latitude +
                                        ", Longitude = " + latLng.longitude, illegalArgumentException);
                            }
                        
                            // Handle case where no address was found.
                            if (addresses == null || addresses.size() == 0) {
                                if (errorMessage.isEmpty()) {
                                    errorMessage = "no_address_found";
                                    Log.e(TAG, errorMessage);
                                }
                            } else {
                                Address address = addresses.get(0);
                                ArrayList<String> addressFragments = new ArrayList<String>();
                                // Fetch the address lines using {@code getAddressLine},
                                // join them, and send them to the thread. The {@link android.location.address}
                                // class provides other options for fetching address details that you may prefer
                                // to use. Here are some examples:
                                // getLocality() ("Mountain View", for example)
                                // getAdminArea() ("CA", for example)
                                // getPostalCode() ("94043", for example)
                                // getCountryCode() ("US", for example)
                                // getCountryName() ("United States", for example)
                                String allAddress = "";
                                for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                                    addressFragments.add(address.getAddressLine(i));
                                    allAddress += address.getAddressLine(i) + " ";
                                }
                                if (address.getAdminArea() != null) {
                                    state = address.getAdminArea();
                                } else {
                                    state = "";
                                }
                                if (address.getLocality() != null) {
                                    city = address.getLocality();
                                } else {
                                    city = "";
                                }
                                if (address.getPostalCode() != null) {
                                    postalCode = address.getPostalCode();
                                } else {
                                    postalCode = "";
                                }
                        
                                Log.i(TAG, "address_found");
                                //driverAddress = TextUtils.join(System.getProperty("line.separator"), addressFragments);
                                cAddress = allAddress;
                                Log.e("result", cAddress.toString());
                            }
                            return cAddress;
                        }
                        

                        您可以使用此方法对正确的完整地址进行地理编码

                        【讨论】:

                          【解决方案19】:

                          使用地理编码器可以得到类似的东西!

                                     try {
                                          Geocoder geo = new Geocoder(MapsActivity.this.getApplicationContext(), Locale.getDefault());
                                          List<Address> addresses = geo.getFromLocation(origin.latitude, origin.longitude, 1);
                                          address.setText("Loading...");
                                          if (addresses != null && addresses.size() > 0) {
                                              String locality = addresses.get(0).getAddressLine(0);
                                              String country = addresses.get(0).getCountryName();
                                              String state = addresses.get(0).getAdminArea();
                                              String sub_admin = addresses.get(0).getSubAdminArea();
                                              String city = addresses.get(0).getFeatureName();
                                              String pincode = addresses.get(0).getPostalCode();
                                              String locality_city = addresses.get(0).getLocality();
                                              String sub_localoty = addresses.get(0).getSubLocality();
                                              if (locality != null && country != null) {
                                                  address.setText(locality + ", " + (sub_localoty != null ? sub_localoty + ", " : "")  + (locality_city != null ? locality_city + ", " : "" ) + (city != null ? city + ", " : "")  + (sub_admin != null ? sub_admin + ", " : "") + (state != null ? state + ", " : "") + country + ", " + (pincode != null ? pincode : ""));
                                              } else {
                                                  address.setText("Location could not be fetched...");
                                              }
                                          }
                                      } catch (Exception e) {
                                          address.setText("Location could not be fetched...");
                                          e.printStackTrace(); // getFromLocation() may sometimes fail
                                      }
                          

                          【讨论】:

                            【解决方案20】:

                            接受 kotlin 格式的答案

                            private fun getAddressInfo(latitude:Double, longitude:Double){
                                val geocoder = Geocoder(this, Locale.getDefault())
                                val addresses: List<Address> = geocoder.getFromLocation(latitude, longitude, 1)
                            
                                val address: String = addresses[0].getAddressLine(0)
                                val city: String = addresses[0].locality
                                val state: String = addresses[0].adminArea
                                val country: String = addresses[0].countryName
                                val postalCode: String = addresses[0].postalCode
                                val knownName: String = addresses[0].featureName
                            }
                            

                            【讨论】:

                              【解决方案21】:

                              您可以这样做以获取纬度和经度的完整地址:

                                public class MainActivity extends AppCompatActivity {
                              
                                       ...
                              
                                private Geocoder geocoder;
                                private TextView mAddressTxtVu;
                              
                                       ...
                              
                              
                                // I assume that you got latitude and longitude correctly 
                              
                                mLatitude  =  20.23232
                                mLongitude =  32.999
                              
                                String errorMessage = "";
                              
                                geocoder = new Geocoder(context, Locale.getDefault());
                              
                                List<Address> addresses = null;
                              
                                try {
                                            addresses = geocoder.getFromLocation(
                                                     mlattitude,
                                                     mlongitude,
                                                     1);
                                    } catch (IOException e) {
                                            errorMessage = getString(R.string.service_not_available);
                                            Log.e(TAG, errorMessage, e);
                                    } catch (IllegalArgumentException illegalArgumentException) {
                                                      // Catch invalid latitude or longitude values.
                                            errorMessage = getString(R.string.invalid_lat_long_used);
                                            Log.e(TAG, errorMessage + ". " + "Latitude = " + mlattitude +", Longitude = " + mlongitude, illegalArgumentException);
                                    }
                              
                                    // Handle case where no address was found.
                                    if (addresses == null || addresses.size() == 0) {
                                           if (errorMessage.isEmpty()) {
                                                    errorMessage = getString(R.string.no_address_found);
                                                    Log.e(TAG, errorMessage);
                                           }
                              
                                    } else {
                                           Address address = addresses.get(0);
                                           ArrayList<String> addressFragments = new ArrayList<String>();
                              
                                           // Fetch the address lines using getAddressLine,
                                           // join them, and send them to the thread.
                                           for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
                                                    addressFragments.add(address.getAddressLine(i));
                                           }
                                           // Log.i(TAG, getString(R.string.address_found));
                              
                              
                                  mAddressTxtVu.setText(TextUtils.join(System.getProperty("line.separator"),
                                                              addressFragments));
                                                  }
                              

                              【讨论】:

                                【解决方案22】:

                                您需要传递纬度和经度值。

                                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();
                                            String postalCode = addresses.get(0).getPostalCode();
                                            String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
                                
                                            System.out.println(address+"-------------");
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                

                                【讨论】:

                                  【解决方案23】:

                                  试试这个代码(工作)

                                  public void GetLocation() throws IOException {
                                  
                                      LocationManager locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
                                  
                                      if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                                              || (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
                                  
                                          ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
                                          }, 200);
                                  
                                          return;
                                      } else {
                                  
                                  
                                  
                                          locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, new LocationListener() {
                                              @Override
                                              public void onLocationChanged(Location location) {
                                                  Log.d(TAG, "onLocationChanged: " + location.getLongitude() + " , " + location.getLatitude());
                                  
                                              }
                                  
                                              @Override
                                              public void onStatusChanged(String s, int i, Bundle bundle) {
                                                  Log.d(TAG, "onStatusChanged: " + s);
                                  
                                              }
                                  
                                              @Override
                                              public void onProviderEnabled(String s) {
                                  
                                              }
                                  
                                              @Override
                                              public void onProviderDisabled(String s) {
                                  
                                              }
                                          });
                                          Criteria criteria = new Criteria();
                                          String bestProvider = locationManager.getBestProvider(criteria, true);
                                          Location location = locationManager.getLastKnownLocation(bestProvider);
                                  
                                          if (location == null) {
                                              Toast.makeText(context, "GPS signal not found",
                                                      Toast.LENGTH_LONG).show();
                                          }
                                          if (location != null) {
                                              Log.e("location", "location--" + location);
                                              Log.e("latitude at beginning",
                                                      "@@@@@@@@@@@@@@@" + location.getLatitude());
                                              // onLocationChanged(location);
                                          }
                                  
                                  
                                          Geocoder geocoder;
                                          List<Address> addresses;
                                          geocoder = new Geocoder(context, Locale.getDefault());
                                          addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 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();
                                          String postalCode = addresses.get(0).getPostalCode();
                                          String knownName = addresses.get(0).getFeatureName();
                                  
                                          Log.d(TAG, "GetLocation: address " + address + " city " + city + " state " + state + " country " + country + " postalCode " + postalCode + " knownName " + knownName);
                                      }
                                  }
                                  

                                  【讨论】:

                                    猜你喜欢
                                    • 1970-01-01
                                    • 2017-04-09
                                    • 1970-01-01
                                    • 2019-10-30
                                    • 2021-06-29
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 1970-01-01
                                    • 2017-10-19
                                    相关资源
                                    最近更新 更多