在Android中如何从经纬度获取地址?

在Android中如何从经纬度获取地址?,android,google-maps,google-maps-api-3,Android,Google Maps,Google Maps Api 3,我正在构建一个android应用程序,其中我正在使用TouchableWrapper类获取纬度和经度。当用户移除手指时,相机中心位置纬度和经度将被解析并显示在toast中。 现在我所需要的就是位于纬度和经度的地址。 下面是我用来获取纬度和经度的代码: public class MainActivity extends FragmentActivity implements TouchActionDown, TouchActionUp { CameraPosition mDownCamer

我正在构建一个android应用程序,其中我正在使用
TouchableWrapper
类获取纬度和经度。当用户移除手指时,相机中心位置纬度和经度将被解析并显示在toast中。 现在我所需要的就是位于
纬度和经度的地址。
下面是我用来获取纬度和经度的代码:

public class MainActivity extends FragmentActivity implements TouchActionDown, TouchActionUp {
    CameraPosition mDownCameraPosition;
    CameraPosition mUpCameraPosition;
    ImageView submitbtn,mappoint;
    String addressfixed,completed;
    EditText whitebord;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maintut);

        // get data views
        mappoint = (ImageView) findViewById(R.id.mappoint);
        whitebord = (EditText) findViewById(R.id.searchmapedit);
        mappoint.setImageResource(R.drawable.point);
        submitbtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                onBackPressed();
            }
        });
        getMap().getMap().setMyLocationEnabled(true);
        getMap().getMap().setOnMapLoadedCallback(
                new GoogleMap.OnMapLoadedCallback() {
                    @Override
                    public void onMapLoaded() {
                        Location myLocation = getMap().getMap().getMyLocation();
                        LatLng myLatLng = new LatLng(myLocation.getLatitude(),
                                myLocation.getLongitude());

                        CameraPosition myPosition = new CameraPosition.Builder()
                                .target(myLatLng).zoom(17).bearing(90).tilt(30)
                                .build();
                        getMap().getMap().animateCamera(
                                CameraUpdateFactory
                                        .newCameraPosition(myPosition));
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // check google play services
        int isAvailable = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (isAvailable != ConnectionResult.SUCCESS) {
            GooglePlayServicesUtil.getErrorDialog(isAvailable, this, 1).show();
        }
    }

    @Override
    public void onTouchDown(MotionEvent event) {
        mDownCameraPosition = getMap().getMap().getCameraPosition();
    }

        @Override
    public void onTouchUp(MotionEvent event) {
    mUpCameraPosition = getMap().getMap().getCameraPosition();
    getMap().getMap().clear();// to remove previous marker
    MarkerOptions options = new MarkerOptions()
            .title("This is your selected place to host game")
            .position(
                    new LatLng(mUpCameraPosition.target.latitude,
                            mUpCameraPosition.target.longitude));
    new GetAddressTask(getApplicationContext()).execute();

}
private SupportMapFragment getMap() {
    return ((SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map));
}

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];
        Location markerLocation = getMap().getMap().getMyLocation();

        List<Address> addresses = null;
        try {
            if (mByMap && markerLocation != null) {
                addresses = geocoder.getFromLocation(markerLocation.getLatitude(),
                        markerLocation.getLongitude(), 1);
            } else if (!mByMap && location != null) {
                addresses = geocoder.getFromLocation(mUpCameraPosition.target.latitude,
                        mUpCameraPosition.target.longitude, 1);
            }
        } catch (IOException exception) {
            Log.e("ComplaintLocation",
                    "IO Exception in getFromLocation()", exception);
  //                handler.post(new Runnable() {
  //
  //                    @Override
  //                    public void run() {
 //                     Toast.makeText(mContext,
//                              mContext.getString("Updating your location failed"),
//                              Toast.LENGTH_SHORT).show();
 //                 }
//              });
            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));
  //            Log.d("LOCATION", "Using " + mProvider);

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

        String mStreet,mHouseNumber,mLatitude,mLongtitude,mPostalCode,mCity;
        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;
        }
        Toast.makeText(getApplicationContext(), mStreet,
                   Toast.LENGTH_LONG).show();
    }
}


private boolean mByMap;

// Lookup address via reverse geolocation
public void lookUpAddress (boolean byMap) {
    mByMap = byMap;
    if (Geocoder.isPresent()) {
//          (new GetAddressTask(mContext)).execute(mCurrentBestLocation);
    }
}

    private SupportMapFragment getMap() {
        return ((SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map));
    }
}
public类MainActivity扩展了FragmentActivity实现了触地动作,触地动作{
CameraPosition mDownCameraPosition;
摄像机定位多摄像机定位;
ImageView submitbtn,mappoint;
字符串地址固定,已完成;
EditText whitebord;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maintut);
//获取数据视图
mappoint=(ImageView)findViewById(R.id.mappoint);
whitebord=(EditText)findViewById(R.id.searchmapedit);
mappoint.setImageResource(R.drawable.point);
submitbtn.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
onBackPressed();
}
});
getMap().getMap().setMyLocationEnabled(true);
getMap().getMap().setOnMapLoadedCallback(
新的GoogleMap.OnMapLoadedCallback(){
@凌驾
加载时的公共无效(){
位置myLocation=getMap().getMap().getMyLocation();
LatLng myLatLng=新LatLng(myLocation.getLatitude(),
myLocation.getLongitude());
CameraPosition myPosition=新建CameraPosition.Builder()
.目标(myLatLng).变焦(17).方位(90).倾斜(30)
.build();
getMap().getMap().animateCamera(
照相机更新工厂
.newCameraPosition(myPosition));
}
});
}
@凌驾
受保护的void onResume(){
super.onResume();
//查看谷歌播放服务
int isAvailable=GooglePlayServicesUtil
.isGooglePlayServicesAvailable(此);
如果(isAvailable!=ConnectionResult.SUCCESS){
GooglePlayServicesUtil.getErrorDialog(isAvailable,this,1.show();
}
}
@凌驾
公共无效onTouchDown(运动事件){
mDownCameraPosition=getMap().getMap().getCameraPosition();
}
@凌驾
公共无效onTouchUp(运动事件){
mUpCameraPosition=getMap().getMap().getCameraPosition();
getMap().getMap().clear();//删除上一个标记
MarkerOptions选项=新的MarkerOptions()
.title(“这是您选择的游戏主办地”)
.职位(
新LatLng(mUpCameraPosition.target.latitude,
mUpCameraPosition.target.longitude);
新建GetAddressTask(getApplicationContext()).execute();
}
私有SupportMapFragment getMap(){
返回((SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map));
}
公共类GetAddressTask扩展了AsyncTask{
公共GetAddressTask(上下文){
超级();
mContext=上下文;
}
@凌驾
受保护的字符串doInBackground(android.location.location…params){
地理编码器=
新的地理编码器(mContext,Locale.getDefault());
android.location.location location=params[0];
位置标记位置=getMap().getMap().getMyLocation();
列表地址=空;
试一试{
if(mByMap&&markerLocation!=null){
addresses=geocoder.getFromLocation(markerLocation.getLatitude(),
markerLocation.getLongitude(),1);
}如果(!mByMap&&location!=null),则为else{
地址=地理编码器.getFromLocation(mUpCameraPosition.target.latitude,
mUpCameraPosition.target.longitude,1);
}
}捕获(IOException异常){
Log.e(“投诉地点”,
“getFromLocation()中的IO异常”,异常);
//handler.post(新的Runnable(){
//
//@覆盖
//公开募捐{
//Toast.makeText(mContext,
//mContext.getString(“更新位置失败”),
//吐司。长度(短)。show();
//                 }
//              });
返回(“试图获取地址的IO异常”);
}捕获(IllegalArgumentException异常){
String errorString=“非法参数”+
Double.toString(location.getLatitude())+“,”+
Double.toString(location.getLongitude())+“传递到地址服务”;
Log.e(“LocationSampleActivity”,errorString,exception);
返回错误字符串;
}
if(addresses!=null&&addresses.size()>0){
地址=地址。获取(0);
if(address.getMaxAddressLineIndex()>0){
返回字符串格式(
%s/%s/%s/%s/%s/%s/%s“,
address.getLatitude(),//0
address.getLongitude(),//1
address.getthoroughure(),//2
address.getSubthoroughe(),//3
address.getPostalCode(),//4
address.getLocation());//5
}否则{
返回字符串格式(
“%s/%s/%s/%s”,
address.getLatitude(),//0
地址。
package com.stackoverflow.hitesh.geocoder;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

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);
Geocoder geocoder;
List<Address> yourAddresses;
geocoder = new Geocoder(this, Locale.getDefault());
yourAddresses= geocoder.getFromLocation(yourLatitude, yourLongitude, 1);

if (yourAddress.size() > 0)
{
 String yourAddress = yourAddresses.get(0).getAddressLine(0);
 String yourCity = yourAddresses.get(0).getAddressLine(1);
 String yourCountry = yourAddresses.get(0).getAddressLine(2);
}
 @Override
public void onCameraChange(CameraPosition cameraPosition)
{
    mGoogleMap.setOnMapLoadedCallback(this);
}


  @Override
public void onMapLoaded()
{
     LatLng position = mGoogleMap.getCameraPosition().target;
     double Lat = position.latitude;
     double Long = position.longitude;

     Geocoder geocoder;
     List<Address> addresses;
     geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
     try
      {
        addresses = geocoder.getFromLocation(Lat, Long, 1); 
        if (addresses != null && addresses.size() > 0)
        {
          String address = addresses.get(0).getAddressLine(0); 
          String address11 = addresses.get(0).getAddressLine(1);
          String city = addresses.get(0).getLocality();
         }
       }
       catch (IOException e) {
        }
   }
mGoogleMap.setOnCameraChangeListener(this);