2015年12月15日 星期二

Android Address 取得地址

以座標來取得住址位置
http://developer.android.com/reference/android/location/Address.html

1./res/layout/activity_main.xml 放個TextView


    



2.MainAcitvity.java
package com.terryyamg.addressestest;

import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.widget.TextView;

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

public class MainActivity extends Activity {

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

        TextView tvAddress = (TextView) findViewById(R.id.tvAddress);

        Geocoder geocoder = new Geocoder(this);
        List<Address> addresses = null;
        double lat = 22.6721740;
        double lon = 120.3100350;
        try {
            addresses = geocoder.getFromLocation(lat, lon, 1); //放入座標
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressText = String.format("%s-%s%s%s%s",
                    address.getCountryName(), //國家
                    address.getAdminArea(), //城市
                    address.getLocality(), //區
                    address.getThoroughfare(), //路
                    address.getSubThoroughfare() //巷號
            );

            tvAddress.setText(addressText);
        }

    }

}


檔案下載:
https://github.com/terryyamg/AddressesTest
參考連結:
http://developer.android.com/reference/android/location/Address.html
http://wptrafficanalyzer.in/blog/android-reverse-geocoding-at-touched-location-in-google-map-android-api-v2/

2 則留言 :

  1. 您好 感謝您的分享!我下載了您的範例並執行了,但是我顯示的不是中文是英文,請問要怎麼轉換呢QQ?

    回覆刪除
    回覆
    1. 因為你的手機或模擬器的語言是英文語系,他會顯示預設語系,可以在
      Geocoder geocoder = new Geocoder(this, Locale.CHINESE);
      修改Local語系就好囉~

      刪除