如何通过android中的json将唯一图像添加到谷歌地图上各种数量的自定义标记

Posted

技术标签:

【中文标题】如何通过android中的json将唯一图像添加到谷歌地图上各种数量的自定义标记【英文标题】:How to add unique images to various number of custom markers on google map via json in android 【发布时间】:2014-10-18 09:23:39 【问题描述】:

我是 android 初学者。

我的应用程序中有一个谷歌地图。 我需要在上面显示一些标记,并且标记的数据来自 JSON。我想在标记中使用的图像不是静态的,存储在服务器中,我的 JSON 还包含图像 URL。

执行此任务的最合适方法是什么。

我使用 asynctask 类来下载图像,如果我在那个 JSON 中只有一个可以正常工作的标记,但是如果 JSON 包含多个元素,循环会尝试调用多个 asynctask .即使我最终没有看到任何异常,我也看不到地图上的任何标记。

这是我的处理程序:

        private final Handler handler = new Handler() 

            public void handleMessage(Message msg) 
                String response = msg.getData().getString("message");
                try 

                    JSONArray jArr = new JSONArray(response);
                    unitObjectArray = new Unit[jArr.length()];

                    for (int i = 0; i < jArr.length(); i++) 
                        Unit units = new Unit();
                        JSONObject jsnparse = jArr.getJSONObject(i);
                        units.setdLatitude(jsnparse.getString("lat"));
                        units.setdLongitude(jsnparse.getString("lon"));     
                        units.setId(jsnparse.getInt("id"));
                        units.setUrl("http://.../layout/img/avatar/"+jsnparse.getInt("id")+".png");
                        dlati = Double.parseDouble(units.getdLatitude());
                        dlongi = Double.parseDouble(units.getdLongitude());
                        units.setDlati(dlati);
                        units.setDlongi(dlongi);
                        unitObjectArray[i] = units;

                    

                 catch (JSONException e) 
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                


                if ((null != response)) 
                    for (int i = 0; i < unitObjectArray.length; i++) 
 //************************if unitObjectArray.length equals to one that works*************
                        Toast.makeText(
                                getBaseContext(),
                                "Server Response: "
                                        + unitObjectArray[i].getDlati()
                                        + unitObjectArray[i].getDlongi(),
                                Toast.LENGTH_SHORT).show();
                        markerLatLng = new LatLng(unitObjectArray[i]
                                .getDlati(), unitObjectArray[i].getDlongi());
                        setUpMap(i);
                    

                 else 
                    // ALERT MESSAGE
                    Toast.makeText(getBaseContext(),
                            "Not Got Response From Server.",
                            Toast.LENGTH_SHORT).show();
                
            
        ;

这是setUpMap方法:

private void setUpMap(int i) 
   mMap = ((SupportMapFragment)     getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

         marker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE))
            .inflate(R.layout.custom_marker_layout, null);

            imageFromUrl= (ImageView)marker.findViewById(R.id.imageFromUrl);

            new DownloadImageFromUrl().execute(unitObjectArray[i].getUrl());

            customMarker = mMap.addMarker(new MarkerOptions()
                .position(markerLatLng)
                .title("Latitude :" + markerLatLng.latitude + " and Longitude:"+ markerLatLng.longitude)
                // .snippet("Description")
                .icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(this, marker))));

        final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerLatLng, 10));
    

这是我的 asyntask 类:

private class DownloadImageFromUrl extends AsyncTask<String, Void, Bitmap> 

            @Override
            protected void onPreExecute() 
                super.onPreExecute();
                // Create a progressdialog
                mProgressDialog = new ProgressDialog(Map.this);
                // Set progressdialog title
                mProgressDialog.setTitle("Download Image Tutorial");
                // Set progressdialog message
                mProgressDialog.setMessage("Loading...");
                mProgressDialog.setIndeterminate(false);
                // Show progressdialog
                mProgressDialog.show();
            

            @Override
            protected Bitmap doInBackground(String... URL) 

                String imageURL = URL[0];

                Bitmap bitmap = null;
                try 
                    // Download Image from URL
                    InputStream input = new java.net.URL(imageURL).openStream();
                    // Decode Bitmap
                    bitmap = BitmapFactory.decodeStream(input);
                 catch (Exception e) 
                    e.printStackTrace();
                
                return bitmap;
            

            @Override
            protected void onPostExecute(Bitmap result) 
                // Set the bitmap into ImageView
                imageFromUrl.setImageBitmap(result);
                // Close progressdialog
                mProgressDialog.dismiss();
            
        

任何帮助将不胜感激。

【问题讨论】:

【参考方案1】:

也许您应该下载所有数据,然后再尝试显示地图? 不错的自定义图标工厂存在于Android Maps Utils

【讨论】:

【参考方案2】:

试试这个方法,希望能帮助你解决问题。

1.从[这里][1]下载最新的AndroidQuery jar:

2.把这个jar放到你的libs文件夹里,右键jar,Build Path -> Add to bulid path。

3.如何使用看这个例子:

AQuery androidQuery = new AQuery(this);

androidQuery.ajax(url, Bitmap.class, 0, new AjaxCallback<Bitmap>() 
   @Override
   public void callback(String url, Bitmap object, AjaxStatus status) 
       super.callback(url, object, status);
       googleMap.addMarker(new MarkerOptions().title("yourtitle").icon(BitmapDescriptorFactory.fromBitmap(object)).position(new LatLng(yourlatitude), Double.parseDouble(yourlongitude))));
   
);

【讨论】:

以上是关于如何通过android中的json将唯一图像添加到谷歌地图上各种数量的自定义标记的主要内容,如果未能解决你的问题,请参考以下文章

如何使用java将相机拍摄的图像添加到Android中的imageviewer?我试过下面的代码

如何在 Android 中的图像上添加文本并使用 JavaMail API 通过电子邮件发送

如何将字节数组中的图像发送到从android到具有Flask的python的url [重复]

如何通过反应 redux 中的唯一字符串切换状态?

如何通过 iOS 中的 JSON webservices post 方法将一组图像发送到服务器?

将json对象发送到android中的webservice