标记未使用JSON显示在Google地图中

时间:2014-08-15 11:31:37

标签: java android json google-maps

我正在尝试从JSON Parsing添加标记。但标记没有显示在地图中。谁能帮帮我吗?这是我的代码:

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

出租车。 java(模型类)

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;

    }

}

2 个答案:

答案 0 :(得分:0)

array of MarkerOptions传递给在UI线程上运行的onPostExecute方法。您可以在那里将标记添加到地图中。例如:

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

答案 1 :(得分:0)

您正在尝试从非UI线程更新UI。这是不允许的,应该正常地抛出异常。您最好使用自定义侦听器将出租车列表从onPostExecute方法传递到UI线程。 制作自定义听众:

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

在asyncTask中添加一个构造函数,如下所示:

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

在onPostExecute中返回列表:

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

并重写你的onCreate方法:

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