0

I want to get the latitude and longitude , i tyr to use AsyncTask , but i can't see the log value , it's not working

What step do i miss ? any help would be grateful.

my global variable:

double editLatitude, editLongitude;

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.traffic_information_fragment, container, false);


        mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
        //it's my json url----------------------------------------------    
        new TrafficInformationTask().execute("http://maps.googleapis.com/maps/api/geocode/json?address=國泰綜合醫院+TW=true_or_false");

        return view;

    }

it's my AsyncTask:

public class TrafficInformationTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... strings) {
            String url = strings[0];
            try {
                String routeJson = getRoute(url);
                return routeJson;
            } catch (IOException ex) {
                Log.d(TAG, ex.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            showRoute(s);
        }
    }


    private String getRoute(String url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        int responseCode = connection.getResponseCode();
        StringBuilder jsonIn = new StringBuilder();
        if (responseCode == 200) {
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = bf.readLine()) != null) {
                jsonIn.append(line);
            }
        } else {
            Log.d(TAG, responseCode + "responseCode");
        }
        connection.disconnect();
        Log.d(TAG, jsonIn + "jsonIn");
        return jsonIn.toString();
    }
    //it's my parse step
    private void showRoute(String route) {
        try {
            JSONObject jsonObject = new JSONObject(route);
            JSONArray resultsArray = jsonObject.getJSONArray("results");
            JSONObject zeroJson = resultsArray.getJSONObject(0);
            JSONObject geometryJson = zeroJson.getJSONObject("geometry");
            editLatitude = geometryJson.getJSONObject("location").getDouble("lat");
            editLongitude = geometryJson.getJSONObject("location").getDouble("lng");
            //there is no value from log
            Log.d("editLatitude",editLatitude+"");
            Log.d("editLongitude",editLongitude+"");

        } catch (JSONException ex) {
            ex.printStackTrace();
        }
    }

json data

1
  • did the url return JSON data? Commented Jan 25, 2017 at 9:33

1 Answer 1

1

you can use Geocoder (https://developer.android.com/reference/android/location/Geocoder.html) to get laitude longitude

 public void Get_LatLng(){
    if(Geocoder.isPresent()){
        try {
            String location = "your_location_name";
            Geocoder gc = new Geocoder(this);
            List<Address> addresses= gc.getFromLocationName(location, 5); // get the Address Objects

            List<LatLng> ll = new ArrayList<LatLng>(addresses.size()); // A list to save the coordinates if they are available
            for(Address ad : addresses){
                if(ad.hasLatitude() && ad.hasLongitude()){
                    ll.add(new LatLng(ad.getLatitude(), ad.getLongitude()));
                    Log.d("editLatitude",ad.getLatitude());
                    Log.d("editLongitude",ad.getLongitude());
                }  
            }  
        } catch (IOException e) {
             // handle the exception
        }
    }
}

Geocoder may return null on some cases..that can be a issue

you can use HTTP request with Google map apis to get latitude longitude

use the following code:

 private class TrafficInformationTask extends AsyncTask<String, Void, String[]> {
   ProgressDialog dialog = new ProgressDialog(MainActivity.this);
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog.setMessage("Loading..");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @Override
    protected String[] doInBackground(String... params) {
        String response;
        try {
            response = getLatLongByURL("http://maps.google.com/maps/api/geocode/json?address=dhaka&sensor=false");
            Log.d("response",""+response);
            return new String[]{response};
        } catch (Exception e) {
            return new String[]{"error"};
        }
    }

    @Override
    protected void onPostExecute(String... result) {
        try {
            JSONObject jsonObject = new JSONObject(result[0]);

            double lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lng");

            double lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lat");

            Log.d("latitude", "" + lat);
            Log.d("longitude", "" + lng);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}


public String getLatLongByURL(String requestURL) {
    URL url;
    String response = "";
    try {
        url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        int responseCode = conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = br.readLine()) != null) {
                response += line;
            }
        } else {
            response = "";
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your information , but i see this stackoverflow.com/questions/17835426/… some advice don't support this function , so i decide to use json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.