【问题标题】:Add marker to android google map with async task使用异步任务将标记添加到 android 谷歌地图
【发布时间】:2013-12-21 15:47:49
【问题描述】:

我有一个异步任务,我正在尝试将地图标记添加到 android 中的谷歌地图。我设置了我的地图并用这个调用异步任务:

public class BreweryMap extends ActionbarMenu {

    BeerData e;
    String beerID;
    GoogleMap map;

    //get beer details from bundle
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_brewerymap);


        //get beer data
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        String breweryID = extras.getString("breweryID");

        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();



        //todo: get brewery latt and long and add marker
        //construct url
        String url = "http://api.brewerydb.com/v2/brewery/"+ breweryID +"?key=myKeyformat=json&withLocations=y";

        Log.d("map", url);
        //async task to get beer taste tag percents
        new AddBreweryMapMarkerJSON(this,map).execute(url);

当调用 asycn 任务时,我解析返回的 json 长和 latt 并尝试将标记添加到我的地图中。我正在从 json 中检索一个 long 和 latt 值,我从我的日志中知道。标记只是没有放置在地图上。

public class AddBreweryMapMarkerJSON extends AsyncTask<String, Void, String> {

    Context c;
    private ProgressDialog Dialog;
    GoogleMap mapIn;

    public AddBreweryMapMarkerJSON(Context context, GoogleMap map)
    {
        c = context;
        mapIn = map;
        Dialog = new ProgressDialog(c);
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return readJSONFeed(arg0[0]);
    }

    protected void onPreExecute() {
        Dialog.setMessage("Getting brewery information");

        Dialog.setTitle("Loading");
        Dialog.setCancelable(false);
        Dialog.show();
    }

    @Override
    protected void onPostExecute(String result){

        try{

            Log.d("map", "in try");
            JSONObject o = new JSONObject(result);

            Log.d("brewery", result);


            String longitude = getLong(o);
            String latt = getLatt(o);



            double longDouble = Double.parseDouble(longitude);
            double lattDouble = Double.parseDouble(latt);

            //add marker
            mapIn.addMarker(new MarkerOptions()
                    .position(new LatLng(longDouble, lattDouble))
                    .title("Hello world"));



        }
        catch(Exception e){

        }

        Dialog.dismiss();

    }

    public String getName(JSONObject json){
        String holder;



        try{
            holder = json.getJSONObject("data").getString("name");

        } catch (JSONException e) {
            holder = "N/A";
        }



        return holder;

    }



    public String getIcon(JSONObject json){
        String holder;



        try{
            holder = json.getJSONObject("data").getJSONObject("images").getString("large");

        } catch (JSONException e) {
            holder = "N/A";
        }



        return holder;

    }

    public String getDescription(JSONObject json){
        String holder;



        try{
            holder = json.getJSONObject("data").getString("description");

        } catch (JSONException e) {
            holder = "N/A";
        }



        return holder;

    }


    public String getYear(JSONObject json){
        String holder;



        try{
            holder = json.getJSONObject("data").getString("established");

        } catch (JSONException e) {
            holder = "N/A";
        }



        return holder;

    }

    public String getLatt(JSONObject json){
        String holder;



        try{
            holder = json.getJSONObject("data").getJSONArray("locations").getJSONObject(0).getString("latitude");

        } catch (JSONException e) {
            holder = "null";
        }



        return holder;

    }

    public String getLong(JSONObject json){
        String holder;



        try{
            holder = json.getJSONObject("data").getJSONArray("locations").getJSONObject(0).getString("longitude");

        } catch (JSONException e) {
            holder = "null";
        }



        return holder;

    }

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

}

【问题讨论】:

    标签: android json google-maps


    【解决方案1】:

    尝试将修改地图的代码放在处理程序中,然后从 AsyncTask 向处理程序发送消息。通常,接口修改必须在主线程中进行,而 AsyncTask 显然是在侧线程中运行的。

    【讨论】:

    • 嗯,在我研究它之前从来没有冒险进入处理程序。
    • 感谢@adamp 提供的信息,不知道!
    【解决方案2】:

    请尝试将您的谷歌地图相机位置动画到特定位置,例如

    CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng) .zoom(12) // 设置缩放 .tilt(30) // 设置相机的倾斜度为 30 度 。建造(); // 从构建器创建一个 CameraPosition // .bearing(90) // 将相机的方向设置为东 gMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    【讨论】:

    • 不确定你的 latLng 是什么格式,我有两个双打,一个用于 latt,一个用于 long。
    【解决方案3】:

    从您的 JSON 字符串中获取 Lat/Lng 点,然后从您的 JSON 数组中创建一个“LatLng 点列表”

    ArrayList<LatLng> points = new ArrayList<LatLng>();
    

    遍历字符串并添加到列表中

    points.add(new LatLng(lat,lng));
    

    在你的doInBackground中返回列表

    return points;
    

    然后在您的onPostExecute 中循环遍历列表并绘制每个列表

    public void onPostExecute(ArrayList points){
        for(LatLng point : points){
            //plot the point to the map
        }
    }
    

    你当然也必须在声明你的类时改变你的返回类型

    AsyncTask<String, Void, ArrayList<LatLng>>
    

    【讨论】:

    • 不知道这和我的有什么不同,然后你使用多个点。我已经在尝试在执行后添加地图点。
    • @Mike 不同,因为您在后台进行所有解析,并且只返回点以循环遍历它们。然后使用列表,您可以循环并绘制每个 latlng。如果列表为空,则意味着某处发生了异常,因为您在解析时没有记录异常,您如何知道是否发生了异常?永远不要不记录异常,您是否尝试过调试以确保没有异常发生?
    【解决方案4】:

    这里的问题似乎是它不喜欢在添加标记的内部创建 LatLng。通过改变这个:

    //add marker
                mapIn.addMarker(new MarkerOptions()
                        .position(new LatLng(longDouble, lattDouble))
                        .title("Hello world"));
    

    对此,修复了未添加的标记:

    double longDouble = Double.parseDouble(longitude);
                double lattDouble = Double.parseDouble(latt);
    
                LatLng positionOne = new LatLng(lattDouble, longDouble);
    
                //add marker
                mapIn.addMarker(new MarkerOptions()
                        .position(positionOne)
                        .title(name));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      相关资源
      最近更新 更多