简体   繁体   中英

Markers not displayed in the google map using JSON

I am trying to add markers from JSON Parsing. but the markers are not showing in the map. Can anyone please help me? Here is my code:

MainActivity.java

package com.hasibhasan.sampletask;

import java.util.ArrayList;

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

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends ActionBarActivity {
    private GoogleMap googlemap;
    private static String TAG_POSTS = "posts";
    private static String TAG_DRIVER = "driver";
    private static String TAG_ID = "id";
    private static String TAG_LATITUDE = "lat";
    private static String TAG_LONGITUDE = "lon";
    private static String TAG_DATETIME = "recorded_datetime";
    private static String TAG_USERID = "user_id";
    private static String TAG_STATE = "cabby_state";
    private static String TAG_VTYPE = "vehicleType";
    private static String TAG_DRIVERNAME = "driver_name";
    private static String TAG_PICNAME = "pic_name";
    private static String TAG_RATING = "rating";
    private static String TAG_CARMODEL = "car_model";
    private static String TAG_NUMBERSIT = "number_sit";
    private static String TAG_DISTANCE = "distance";
    private static String TAG_OPERATOR = "operator";
    private static String TAG_NEARESTDISTANCE = "nearest_distance";
    private static String TAG_NDISTANCE = "distance";
    private static String TAG_TIME = "time";
    private static String TAG_CARMODELS = "car_models";
    ArrayList<Taxi> taxi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        taxi = new ArrayList<Taxi>();
        new ParseJSONTask().execute();
        googlemap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();
    }

    private class ParseJSONTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            WebServiceHandler webServiceHandler = new WebServiceHandler();
            String jsonstr = webServiceHandler
                    .getJSONData("http://54.186.247.213/unicabi/mobileservice/CurrentLocationService.php");
            try {
                JSONObject jsonObject = new JSONObject(jsonstr);
                JSONArray postJson = jsonObject.getJSONArray(TAG_POSTS);
                for (int i = 0; i < postJson.length(); i++) {
                    Taxi aTaxi = new Taxi();
                    JSONObject postObject = postJson.getJSONObject(i);
                    aTaxi.lat = postObject.getString(TAG_LATITUDE);
                    aTaxi.lon = postObject.getString(TAG_LONGITUDE);
                    aTaxi.driver_name = postObject.getString(TAG_DRIVERNAME);
                    taxi.add(aTaxi);
                    double lati = Double.parseDouble(aTaxi.lat);
                    double lon = Double.parseDouble(aTaxi.lon);
                    googlemap.addMarker(new MarkerOptions().title(
                            aTaxi.driver_name).position(new LatLng(lati, lon)));

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            super.onPostExecute(result);
        }
    }
}

Taxi. java (the model class)

package com.hasibhasan.sampletask;

public class Taxi {
    public String posts = "";
    public String success = "";
    public String driver = "";
    public String id = "";
    public String lat = "";
    public String lon = "";
    public String recorded_datetime = "";
    public String vehicleType = "";
    public String driver_name = "";
    public String pic_name = "";
    public String rating = "";
    public String car_model = "";
    public String number_sit = "";
    public String distance = "";
    public String operator = "";
    public String nearest_distance = "";
    public String car_models = "";

}

Webservicehandler.java

    package com.hasibhasan.sampletask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class WebServiceHandler {
    public WebServiceHandler() {

    }

    public String getJSONData(String url) {
        String response = null;
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpclient.execute(httpGet);
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;

    }

}

Pass the array of MarkerOptions to your onPostExecute method which runs on the UI thread. You can add the markers to your map there. Example:

private class ParseJSONTask extends AsyncTask<Void, Void, List<MarkerOptions>> {
    @Override
    protected void onPreExecute() {

        super.onPreExecute();
    }

    @Override
    protected List<MarkerOptions> doInBackground(Void... params) {
        WebServiceHandler webServiceHandler = new WebServiceHandler();
        String jsonstr = webServiceHandler
                .getJSONData("http://54.186.247.213/unicabi/mobileservice/CurrentLocationService.php");
        try {
            JSONObject jsonObject = new JSONObject(jsonstr);
            JSONArray postJson = jsonObject.getJSONArray(TAG_POSTS);
            List<MarkerOptions> markers = new ArrayList<MarkerOptions>();
            for (int i = 0; i < postJson.length(); i++) {
                Taxi aTaxi = new Taxi();
                JSONObject postObject = postJson.getJSONObject(i);
                aTaxi.lat = postObject.getString(TAG_LATITUDE);
                aTaxi.lon = postObject.getString(TAG_LONGITUDE);
                aTaxi.driver_name = postObject.getString(TAG_DRIVERNAME);
                taxi.add(aTaxi);
                double lati = Double.parseDouble(aTaxi.lat);
                double lon = Double.parseDouble(aTaxi.lon);
                markers.add(new MarkerOptions().title(aTaxi.driver_name).
                        position(new LatLng(lati, lon)));

                return markers;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<MarkerOptions>();
    }

    @Override
    protected void onPostExecute(List<MarkerOptions> markers) {
        super.onPostExecute(markers);
        for (MarkerOptions marker : markers) {
            googlemap.addMarker(marker);
        }
    }
}

You are trying to update the UI from a non-UI thread. This not allowed and should normaly throw an exception. You should better use an custom listener to pass the taxi list to your UI thread from your onPostExecute method. Make a custom Listener:

public interface ParsingFinishedListener{
    public abstract void onParsingFinished(List<MarkerOptions> markers;
}

Add a constructor to your asyncTask like this:

public ParseJsonTask(ParsingFinishedListener l){
    this.mParsingFinisedListener = l;
}

And in onPostExecute return the list:

@Override
protected void onPostExecute(List<MarkerOptions> markers) {
    super.onPostExecute(markers);
    mParsingFinishedListener.onParsingFinished(markers);
}

And rewrite your onCreate method:

@Override
public void onCreate(Bundele savedInstance){
    super.onCreate(savedInstance);
    setContentView(R.layout.activity_main);
    googlemap = ((MapFragment) getFragmentManager().findFragmentById(
    R.id.map)).getMap();
    taxi = new ArrayList<Taxi>();
    new ParseJSONTask().execute(new ParsingFinishedListener(){
        @Override
        public void onParsingFinished(List<MarkerOptions> m){
            for (MarkerOptions marker : markers) {
                googlemap.addMarker(marker);
            }
        }
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM