Phil
Phil

Reputation: 83

Android add Json object to google marker

I am trying to add data i read from an API to be the Lat and Long of my markers.

I can't seem to get my head around how it should work, and anything i think off fails.

Here is my code: package com.fly.plane;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import com.fly.plane.R;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.MapFragment;
    import com.google.android.gms.maps.SupportMapFragment;

    import com.google.android.gms.maps.model.BitmapDescriptorFactory;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.Marker;
    import com.google.android.gms.maps.model.MarkerOptions;


    import android.R.array;
    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.util.Log;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;

   public class MyMapActivity extends ListActivity {

    private ProgressDialog pDialog;

    // URL to get data JSON
    private static String url = "http://edmundgentle.com/snippets/flights/api.php";

    // JSON Node speeds
    private static final String TAG_data = "data";
    private static final String TAG_BEARING = "bearing";
    private static final String TAG_speed = "speed";
    private static final String TAG_ARR = "arr";
    private static final String TAG_ARR_TIME = "time";
    private static final String TAG_ARR_LAT = "lat";
    private static final String TAG_ARR_LON = "lon";
    private static final String TAG_DEP = "dep";
    private static final String TAG_DEP_TIME = "time";
    private static final String TAG_DEP_LAT = "lat";
    private static final String TAG_DEP_LON = "lon";

    // data JSONArray
    JSONArray data = null;

    // Hashmap for ListView (just for testing)
    ArrayList<HashMap<String, String>> contactList;

    // Hashmap for ListView
    ArrayList<String> ct;

    private GoogleMap mMap; 
    public double latt = 0;
    public double lng = 0;
    public ArrayList<Integer> dLat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_map);


    // create markers   
    mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    List<Marker> markers = new ArrayList<Marker>();
    for (int i = 0; i < 5 ; i++)
    {
            Marker marker =  mMap.addMarker(new MarkerOptions()
            .position(new LatLng(latt, lng))
            .title("Hello world")
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.planemarker)));
            markers.add(marker);
            latt = Double.parseDouble(ct.get(i));
            lng = i;    

        }


    contactList = new ArrayList<HashMap<String, String>>();

    ct = new ArrayList<String>();

    //ListView lv = getListView();

    new Getdata().execute();


    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class Getdata extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MyMapActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            HTTPHandler sh = new HTTPHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, HTTPHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    data = jsonObj.getJSONArray(TAG_data);

                    // looping through All data
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject c = data.getJSONObject(i);

                        String bearing = c.getString(TAG_BEARING);
                        String speed = c.getString(TAG_speed);

                        // departure node is JSON Object
                        JSONObject dep = c.getJSONObject(TAG_DEP);
                        String dtime = dep.getString(TAG_DEP_TIME);
                        String dlat = dep.getString(TAG_DEP_LAT);
                        String dlon = dep.getString(TAG_DEP_LON);

                        //dLat.add( Integer.parseInt(dep.getString(TAG_DEP_LAT)));

                        // arrival node is JSON Object
                        JSONObject arr = c.getJSONObject(TAG_ARR);
                        String atime = arr.getString(TAG_ARR_TIME);
                        String alat = arr.getString(TAG_ARR_LAT);
                        String alon = arr.getString(TAG_ARR_LON);

                        ArrayList<String> test = new ArrayList<String>();

                        test.add(alat);

                        ct.addAll(test);

                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_BEARING, bearing);
                        contact.put(TAG_speed, speed);
                        contact.put(TAG_DEP_TIME, dtime);
                        contact.put("atime", atime);


                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MyMapActivity.this, contactList,
                    R.layout.list_item, new String[] { TAG_speed,TAG_DEP_TIME, "atime"
                             }, new int[] { R.id.speed,
                            R.id.departure, R.id.arrival });

            setListAdapter(adapter);
        }

    }

}

Json

{
"data": [
  {
     "dep": {
        "time": "06:00:00",
        "lat": 51.469603,
        "lon": -0.453566
     },
     "arr": {
        "time": "08:35:00",
        "lat": 38.770043,
        "lon": -9.128165
     },
     "speed": 605.78072182431,
     "bearing": -150.48169437461
  },
  {
     "dep": {
        "time": "06:00:00",
        "lat": 51.469603,
        "lon": -0.453566
     },
     "arr": {
        "time": "08:35:00",
        "lat": 38.770043,
        "lon": -9.128165
     },
     "speed": 605.78072182431,
     "bearing": -150.48169437461
  }

I am able to read all the data in, and display it on screen (which is only there for verification purposes at the moment) The trouble i am having, is getting that data to be the Lat and Lon of each marker.

Edit: I am able to stop it from causing errors, but it will no longer print the markers. (my guess is that contactList.size is 0 when it attempts to make markers, causing it to never run through the for loop, if i change it to say i<10 it crashes, i guess because when it tries to get data from contactList, its empty). i don't know how to make it run after contactList has been filled. i may be wrong, and it could be a completely different problem.

        mMap = ((MapFragment)   getFragmentManager().findFragmentById(R.id.map)).getMap();
        List<Marker> markers = new ArrayList<Marker>();
        for (int i = 0; i < contactList.size() ; i++)
        {
            if (i == 30) i=0;

            String lat = contactList.get(i).get(TAG_ARR_LAT);
            String lng =  contactList.get(i).get(TAG_ARR_LON);

            // Now parse it in double

            double latitude = Double.parseDouble(lat);
            double longitude = Double.parseDouble(lng);

                Marker marker =  mMap.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                //.position(new LatLng(latitude, longitude))
                .title("Hello world")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.planemarker)));
                markers.add(marker);            

            }  

in there i tried to get the latt cord from my list turning it into an integer, doesn't want to play ball.

Any help on this would be much appreciated.

Cheers

Upvotes: 0

Views: 2436

Answers (2)

Piyush
Piyush

Reputation: 18923

You should put this in your HashMap string list

 String alat = arr.getString(TAG_ARR_LAT);
 String alon = arr.getString(TAG_ARR_LON);

 contact.put(TAG_ARR_LAT, atime);
 contact.put(TAG_ARR_LON, atime);

After that while retrieving latitude and longitude use this...

   for (int i = 0; i < contactList.size ; i++)
   {
        String lat = contactList.get(i).get(TAG_ARR_LAT);
        String lng =  contactList.get(i).get(TAG_ARR_LON);

        // Now parse it in double

        double latitude = Double.parseDouble(lat);
        double longitude = Double.parseDouble(lng);

        Marker marker =  mMap.addMarker(new MarkerOptions()
        .position(new LatLng(latitude, longitude))
        .title("Hello world")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.planemarker)));
         markers.add(marker);

    }

Upvotes: 2

cheeseOverflow
cheeseOverflow

Reputation: 1

The constructor for the LatLng class takes 2 doubles as parameters. You should use

latt = Double.parseDouble(..);
lng = Double.parseDouble(..);

You're currently assigning the value of i (0 - 4) to lng. Make sure you correctly assign the lat and lng values you retrieved from the json object.

Upvotes: 0

Related Questions