2016-03-02 65 views
3

如何從我當前的位置在android中查找附近的城市或城鎮。我可以得到像ATM,醫院這樣最近的地方。但是,我無法獲得最近的城鎮名稱。從我當前所在的位置附近的城市或城鎮

+0

您可以嘗試的地方API或從谷歌地圖API ...你有什麼已經嘗試過? –

+0

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=lat,lng&radius=5000&types=food&sensor=true&key=APIKEY 我試過這個網址..我無法從這個城市獲得url – karthik

+0

由於URL中的輸出顯示,您的API密鑰無效。在console.developers.google.com上生成一個新密鑰並嘗試使用該密鑰。 –

回答

1

下面是一個例子:

https://github.com/yangjiandong/proAndroid4DevCode/blob/master/Full%20Worked%20Sample%20Projects/Chapter_13_Where_Am_I_Part_3/src/com/paad/whereami/WhereAmI.java#L14

 private void updateWithNewLocation(Location location) { 
    TextView myLocationText; 
    myLocationText = (TextView)findViewById(R.id.myLocationText); 

    String latLongString = "No location found"; 
    String addressString = "No address found"; 

    if (location != null) { 
     double lat = location.getLatitude(); 
     double lng = location.getLongitude(); 
     latLongString = "Lat:" + lat + "\nLong:" + lng; 

     double latitude = location.getLatitude(); 
     double longitude = location.getLongitude(); 
     Geocoder gc = new Geocoder(this, Locale.getDefault()); 

     try { 
     List<Address> addresses = gc.getFromLocation(latitude, longitude, 1); 
     StringBuilder sb = new StringBuilder(); 
     if (addresses.size() > 0) { 
      Address address = addresses.get(0); 

      for (int i = 0; i < address.getMaxAddressLineIndex(); i++) 
      sb.append(address.getAddressLine(i)).append("\n"); 

      sb.append(address.getLocality()).append("\n"); 
      sb.append(address.getPostalCode()).append("\n"); 
      sb.append(address.getCountryName()); 
     } 
     addressString = sb.toString(); 
     } catch (IOException e) {} 
    } 

    myLocationText.setText("Your Current Position is:\n" + 
          latLongString + "\n\n" + addressString); 
    } 

    private final LocationListener locationListener = new LocationListener() { 
    public void onLocationChanged(Location location) { 
     updateWithNewLocation(location); 
    } 
+0

我只能從上面的代碼中獲得當前位置地址..我需要在10或15公里附近的城市或城鎮名稱。 – karthik

0

我提供一個鏈接,你可以找到工作的來源代碼,我已經在我的應用程序嘗試在這裏我張貼鏈接希望你發現這有用。

Web link

here is output of code

+0

使用此鏈接我可以得到附近的地方只..我想要附近的城市 – karthik

+0

請看看這個網站http://www.androidhive.info/2012/08/android-working-with-google-places-and-地圖教程/ – SmashCode

相關問題