android - 如何从Android中的经纬度获取地址?

标签 android google-maps google-maps-api-3

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

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

如有任何帮助,我们将不胜感激。

最佳答案

可以通过GeoCoder对象获取地址 请注意,您将收到一份建议地址列表。 在这个例子中我取第一个

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

关于android - 如何从Android中的经纬度获取地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27244763/

相关文章:

java - 如何在 ScrollView 中缩放 TextView ?

Android AudioRecord StartRecording - 应用挂起

android - Volley 不会为我的自定义请求调用 getParams?

android - 'Maps SDK for Android v.3.0.0 BETA' 是否适用于没有 Google Play 服务的设备?

android - 在该 View 外单击时 View 消失

javascript - 根据需要在 Google map 中展开标记

android - 在 androidx 中使用自定义字体

json - 地理编码城市+州,因为它们会定期添加到谷歌表格中?

javascript - 如何使用 Google Maps API v3 突出显示地址?

jquery - 使用 Google map FitBounds() 函数的缓动函数