Android 原生Api进行地面编码与逆地理编码

废话不说,直接上代码

异步执行编码转换

public class GeocodeAddressIntentService extends IntentService {

protected ResultReceiver resultReceiver;
private static final String TAG = "GEO_ADDY_SERVICE";

public GeocodeAddressIntentService() {
    super("GeocodeAddressIntentService");
}

@Override
protected void onHandleIntent(Intent intent) {
    Log.e(TAG, "onHandleIntent");
    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    String errorMessage = "";
    List
addresses = null; int fetchType = intent.getIntExtra(Constants.FETCH_TYPE_EXTRA, 0); Log.e(TAG, "fetchType == " + fetchType); if(fetchType == Constants.USE_ADDRESS_NAME) { String name = intent.getStringExtra(Constants.LOCATION_NAME_DATA_EXTRA); try { addresses = geocoder.getFromLocationName(name, 1); } catch (IOException e) { errorMessage = "Service not available"; Log.e(TAG, errorMessage, e); } } else if(fetchType == Constants.USE_ADDRESS_LOCATION) { double latitude = intent.getDoubleExtra(Constants.LOCATION_LATITUDE_DATA_EXTRA, 0); double longitude = intent.getDoubleExtra(Constants.LOCATION_LONGITUDE_DATA_EXTRA, 0); try { addresses = geocoder.getFromLocation(latitude, longitude, 1); } catch (IOException ioException) { errorMessage = "Service Not Available"; Log.e(TAG, errorMessage, ioException); } catch (IllegalArgumentException illegalArgumentException) { errorMessage = "Invalid Latitude or Longitude Used"; Log.e(TAG, errorMessage + ". " + "Latitude = " + latitude + ", Longitude = " + longitude, illegalArgumentException); } } else { errorMessage = "Unknown Type"; Log.e(TAG, errorMessage); } resultReceiver = intent.getParcelableExtra(Constants.RECEIVER); if (addresses == null || addresses.size() == 0) { if (errorMessage.isEmpty()) { errorMessage = "Not Found"; Log.e(TAG, errorMessage); } deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage, null); } else { for(Address address : addresses) { String outputAddress = ""; for(int i = 0; i < address.getMaxAddressLineIndex(); i++) { outputAddress += " --- " + address.getAddressLine(i); } Log.e(TAG, outputAddress); } Address address = addresses.get(0); ArrayList addressFragments = new ArrayList<>(); for(int i = 0; i < address.getMaxAddressLineIndex(); i++) { addressFragments.add(address.getAddressLine(i)); } Log.i(TAG, "Address Found"); deliverResultToReceiver(Constants.SUCCESS_RESULT, TextUtils.join(System.getProperty("line.separator"), addressFragments), address); } } private void deliverResultToReceiver(int resultCode, String message, Address address) { Bundle bundle = new Bundle(); bundle.putParcelable(Constants.RESULT_ADDRESS, address); bundle.putString(Constants.RESULT_DATA_KEY, message); resultReceiver.send(resultCode, bundle); } }

使用

public class MainActivity extends AppCompatActivity {

AddressResultReceiver mResultReceiver;

EditText latitudeEdit, longitudeEdit, addressEdit;
ProgressBar progressBar;
TextView infoText;
CheckBox checkBox;

boolean fetchAddress;
int fetchType = Constants.USE_ADDRESS_LOCATION;

private static final String TAG = "MAIN_ACTIVITY";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    longitudeEdit = (EditText) findViewById(R.id.longitudeEdit);
    latitudeEdit = (EditText) findViewById(R.id.latitudeEdit);
    addressEdit = (EditText) findViewById(R.id.addressEdit);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    infoText = (TextView) findViewById(R.id.infoText);
    checkBox = (CheckBox) findViewById(R.id.checkbox);

    mResultReceiver = new AddressResultReceiver(null);
}

public void onRadioButtonClicked(View view) {
    boolean checked = ((RadioButton) view).isChecked();

    switch (view.getId()) {
        case R.id.radioAddress:
            if (checked) {
                fetchAddress = false;
                fetchType = Constants.USE_ADDRESS_NAME;
                longitudeEdit.setEnabled(false);
                latitudeEdit.setEnabled(false);
                addressEdit.setEnabled(true);
                addressEdit.requestFocus();
            }
            break;
        case R.id.radioLocation:
            if (checked) {
                fetchAddress = true;
                fetchType = Constants.USE_ADDRESS_LOCATION;
                latitudeEdit.setEnabled(true);
                latitudeEdit.requestFocus();
                longitudeEdit.setEnabled(true);
                addressEdit.setEnabled(false);
            }
            break;
    }
}

public void onButtonClicked(View view) {
    Intent intent = new Intent(this, GeocodeAddressIntentService.class);
    intent.putExtra(Constants.RECEIVER, mResultReceiver);
    intent.putExtra(Constants.FETCH_TYPE_EXTRA, fetchType);
    if (fetchType == Constants.USE_ADDRESS_NAME) {
        if (addressEdit.getText().length() == 0) {
            Toast.makeText(this, "Please enter an address name", Toast.LENGTH_LONG).show();
            return;
        }
        intent.putExtra(Constants.LOCATION_NAME_DATA_EXTRA, addressEdit.getText().toString());
    } else {
        if (latitudeEdit.getText().length() == 0 || longitudeEdit.getText().length() == 0) {
            Toast.makeText(this,
                    "Please enter both latitude and longitude",
                    Toast.LENGTH_LONG).show();
            return;
        }
        intent.putExtra(Constants.LOCATION_LATITUDE_DATA_EXTRA,
                Double.parseDouble(latitudeEdit.getText().toString()));
        intent.putExtra(Constants.LOCATION_LONGITUDE_DATA_EXTRA,
                Double.parseDouble(longitudeEdit.getText().toString()));
    }
    infoText.setVisibility(View.INVISIBLE);
    progressBar.setVisibility(View.VISIBLE);
    Log.e(TAG, "Starting Service");
    startService(intent);
}

class AddressResultReceiver extends ResultReceiver {
    public AddressResultReceiver(Handler handler) {
        super(handler);
    }

    @Override
    protected void onReceiveResult(int resultCode, final Bundle resultData) {
        if (resultCode == Constants.SUCCESS_RESULT) {
            final Address address = resultData.getParcelable(Constants.RESULT_ADDRESS);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressBar.setVisibility(View.GONE);
                    infoText.setVisibility(View.VISIBLE);
                    infoText.setText("Latitude: " + address.getLatitude() + "\n" +
                            "Longitude: " + address.getLongitude() + "\n" +
                            "Address: " + resultData.getString(Constants.RESULT_DATA_KEY));
                    goToNaviActivity(MainActivity.this,"",address.getLatitude(),address.getLongitude(),"1","0");

                }
            });
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressBar.setVisibility(View.GONE);
                    infoText.setVisibility(View.VISIBLE);
                    infoText.setText(resultData.getString(Constants.RESULT_DATA_KEY));
                }
            });
        }
    }
}

/**
 * 启动高德App进行导航
 * @param poiname 非必填 POI 名称
 * @param lat 必填 纬度
 * @param lon 必填 经度
 * @param dev 必填 是否偏移(0:lat 和 lon 是已经加密后的,不需要国测加密; 1:需要国测加密)
 * @param style 必填 导航方式(0 速度快; 1 费用少; 2 路程短; 3 不走高速;4 躲避拥堵;5 不走高速且避免收费;6 不走高速且躲避拥堵;7 躲避收费和拥堵;8 不走高速躲避收费和拥堵))
 */
public  void goToNaviActivity(Context context, String poiname , Double lat , Double lon , String dev , String style){
    StringBuffer stringBuffer  = new StringBuffer("androidamap://navi?sourceApplication=")
            .append("");
    if (!TextUtils.isEmpty(poiname)){
        stringBuffer.append("&poiname=").append(poiname);
    }
    stringBuffer
            .append("&lat=").append(lat)
            .append("&lon=").append(lon)
            .append("&destination=").append(context)
            .append("&dev=").append(dev)
            .append("&style=").append(style);

    Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse(stringBuffer.toString()));
    intent.setPackage("com.autonavi.minimap");
    startActivity(intent);
}
}

你可能感兴趣的:(Android 原生Api进行地面编码与逆地理编码)