Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

android - Get current location using json

Hi i a m writing an application whih gets the current latitude and longitude and convert it to corrsponding address.i can get the lattitude and longitutde but how to convert it to the corresponding address using json. i am new to json. i tried some sample codes butnot getting the address

This is my code

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();

pls help me

thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To change back human readable format, you can also use Geocoder but that is not working sometimes because google play service problem. I used this json geocodeing as second option for in case.

Please refer Google Geocoding API

Workflow is pass your latitude and longitude and get current location. Request url gonna be like this.

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

Hopefully, this answer will help you.

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;
}

As my experience, only device generated latitude and longitude will work. Then call

String currentLocation = getCurrentLocationViaJSON(lat, lng);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...