2

嗨,我写了一个应用程序,它获取当前的经度和纬度并将其转换为corrsponding address.i可以得到lattitude和longitutde,但如何使用json将其转换为相应的地址。我是json的新手。我尝试了一些示例代码butnot获取地址使用json获取当前位置

这是我的代码

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

import android.content.Context; 
import android.location.Address; 
import android.location.Geocoder; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import android.util.Log; 
import android.view.Menu; 
import android.widget.Toast; 

import com.google.android.gms.maps.CameraUpdate; 
import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
import com.google.android.gms.maps.model.CameraPosition; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.LatLngBounds; 
import com.google.android.gms.maps.model.Marker; 
import com.google.android.gms.maps.model.MarkerOptions; 
import com.google.android.maps.GeoPoint; 



public class GMapActivity extends FragmentActivity { 
private GoogleMap map; 


     @Override 

     protected void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.activity_map); 
       LocationManager locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 

       LocationListener locListener = new GpsActivity(getBaseContext()); 
     locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener); 


       if (map == null) { 
        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 
          .getMap(); 

       map.setMyLocationEnabled(true); 


       } 
     } 

     @Override 
     public boolean onCreateOptionsMenu(Menu menu) { 
       // Inflate the menu; this adds items to the action bar if it is present. 
       getMenuInflater().inflate(R.menu.map, menu); 
       return true; 
     } 



       private class GpsActivity implements LocationListener{ 
        Marker marker; 
        Context mcontext; 
        public GpsActivity(Context context){ 
          super(); 
          mcontext=context; 
        } 
        @Override 
        public void onLocationChanged(Location location) { 
          // TODO Auto-generated method stub 
          if (location != null) { 

            double latitude=location.getLatitude(); 

            double longitude=location.getLongitude(); 

            LatLng gpslocation=new LatLng(latitude,longitude); 


            Toast.makeText(getApplicationContext(),"" +gpslocation, 
                 Toast.LENGTH_LONG).show(); 

请帮我

在此先感谢

回答

13

要变回人类可读的格式,还可以使用地理编码但有时候因为谷歌播放服务问题而不起作用。以防万一,我使用这个json地理编码作为第二个选项。

请参阅Google Geocoding API

工作流是通过你的经度和纬度,并获得当前位置。请求网址会是这样的。

String reqURL = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat+","+lng +"&sensor=true"; 

希望这个答案能帮助你。

public static JSONObject getLocationInfo(double lat, double lng) { 

    HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat+","+lng +"&sensor=true"); 
    HttpClient client = new DefaultHttpClient(); 
    HttpResponse response; 
    StringBuilder stringBuilder = new StringBuilder(); 

    try { 
     response = client.execute(httpGet); 
     HttpEntity entity = response.getEntity(); 
     InputStream stream = entity.getContent(); 
     int b; 
     while ((b = stream.read()) != -1) { 
      stringBuilder.append((char) b); 
     } 
    } catch (ClientProtocolException e) { 
    } catch (IOException e) { 
    } 

    JSONObject jsonObject = new JSONObject(); 
    try { 
     jsonObject = new JSONObject(stringBuilder.toString()); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

    return jsonObject; 
} 

public static String getCurrentLocationViaJSON(double lat, double lng) { 

    JSONObject jsonObj = getLocationInfo(lat, lng); 
    Log.i("JSON string =>", jsonObj.toString()); 

    String currentLocation = "testing"; 
    String street_address = null; 
    String postal_code = null; 

    try { 
     String status = jsonObj.getString("status").toString(); 
     Log.i("status", status); 

     if(status.equalsIgnoreCase("OK")){ 
      JSONArray results = jsonObj.getJSONArray("results"); 
      int i = 0; 
      Log.i("i", i+ "," + results.length()); //TODO delete this 
      do{ 

       JSONObject r = results.getJSONObject(i); 
       JSONArray typesArray = r.getJSONArray("types"); 
       String types = typesArray.getString(0); 

       if(types.equalsIgnoreCase("street_address")){ 
        street_address = r.getString("formatted_address").split(",")[0]; 
        Log.i("street_address", street_address); 
       }else if(types.equalsIgnoreCase("postal_code")){ 
        postal_code = r.getString("formatted_address"); 
        Log.i("postal_code", postal_code); 
       } 

       if(street_address!=null && postal_code!=null){ 
        currentLocation = street_address + "," + postal_code; 
        Log.i("Current Location =>", currentLocation); //Delete this 
        i = results.length(); 
       } 

       i++; 
      }while(i<results.length()); 

      Log.i("JSON Geo Locatoin =>", currentLocation); 
      return currentLocation; 
     } 

    } catch (JSONException e) { 
     Log.e("testing","Failed to load JSON"); 
     e.printStackTrace(); 
    } 
    return null; 
} 

至于我的经验,只有设备生成的纬度和经度会工作。 然后调用

String currentLocation = getCurrentLocationViaJSON(lat, lng); 
+0

感谢u..yeah我试图gecoder我有同样的问题,一些领带我必须重新启动设备以获取address.i是新来的JSON所以这将是非常有益的IY您提供一些示例教程链接或代码片段。再次感谢你的帮助。 – user2298758

+0

这是如何处理json响应http://www.androidhive.info/2012/01/android-json-parsing-tutorial/祝你好运! – Megamind

+0

请参考我的回答。我编辑过。 – Megamind