2014-03-02 36 views
1

有沒有一種方法可以從我當前的位置(Android)獲取城市的名稱?我知道如何讓lattitue /長,但如果有一個具體的例子,然後更好從我的位置查找城市名稱

謝謝

+0

也許有些網絡服務? –

+0

您需要GeoCoder類。 如果有幫助,請參閱此處。 [獲取當前位置的城市名稱] [1] [1]:http://stackoverflow.com/questions/18221614/how-i-can-get-the-city-name-of -My電流位置 – HexaHow

回答

1
 Geocoder gcd = new Geocoder(context, Locale.getDefault()); 
    try{ 
    List<Address> addresses = gcd.getFromLocation(lat, lon, 1);//lat and lon is the latitude and longitude in double 
    if (addresses.size() > 0) 
    String cityName=addresses.get(0).getLocality(); 
    } 
    catch (IOException e) {} 
    catch (NullPointerException e) {} 
1

只要使用谷歌的API

http://maps.googleapis.com/maps/api/geocode/json?latlng=<LAT>,<LNG>&sensor=true

把你的經度和緯度在正確的地方並使用JSONObject來解析結果

0

試試這個,希望它有幫助。原諒這個循環,只是從我最近的一項工作中拿出來。

看看這個link

Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault()); 
List<Address> addresses = geocoder.getFromLocation(latitude,longitude,1); 
for(int i=0; i<addresses.size(); ++i) 
{ 
    address = addresses.get(i); 
    string city = address.getLocality(); 
} 
0

可能是本文可能可以幫助你:http://www.devlper.com/2010/07/geocoding-and-reverse-geocoding-in-android/ 它還提供了它的源代碼。

否則,從here

public class AndroidFromLocation extends Activity { 

double LATITUDE = 37.42233; 
double LONGITUDE = -122.083; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    TextView myLatitude = (TextView)findViewById(R.id.mylatitude); 
    TextView myLongitude = (TextView)findViewById(R.id.mylongitude); 
    TextView myAddress = (TextView)findViewById(R.id.myaddress); 

    myLatitude.setText("Latitude: " + String.valueOf(LATITUDE)); 
    myLongitude.setText("Longitude: " + String.valueOf(LONGITUDE)); 

    Geocoder geocoder = new Geocoder(this, Locale.ENGLISH); 

    try { 
    List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1); 

    if(addresses != null) { 
    Address returnedAddress = addresses.get(0); 
    StringBuilder strReturnedAddress = new StringBuilder("Address:\n"); 
    for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) { 
    strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n"); 
    } 
myAddress.setText(strReturnedAddress.toString()); 
} 
else{ 
myAddress.setText("No Address returned!"); 
} 
} catch (IOException e) { 
// TODO Auto-generated catch block 
    e.printStackTrace(); 
myAddress.setText("Canont get Address!"); 
} 

} 
} 

此外,還要檢查這個具體的例子:http://www.smnirven.com/blog/2009/10/09/reverse-geocode-lookup-using-google-maps-api-on-android-revisited/here獲得完整的代碼。