0

我正在开发一个包含谷歌地图的应用程序。我想在地图上添加标记/指针。指针将从接收到的数据中添加。因此,如果数据库中有 3 行,那么它应该向地图添加 3 个标记,其中 LatLng 和行的名称。

我可以手动添加标记,但我希望它循环执行。因此,对于每一行 -> 在地图上添加一个标记。

如何才能做到这一点?

我的活动如下。

public class MapsActivity extends Activity {

     private MainMapFragement mapFragment;
     private HashMap<Marker, EventInfo> eventMarkerMap;
     private LatLng mPosition;
     Geocoder geocoder;
     String bestProvider;
     List<Address> user = null;
     double lat, lng;
     private ProgressDialog pDialog;
     JSONParser jParser = new JSONParser();
     ArrayList<HashMap<String, String>> productsList;
     private static String url_all_products = "http://000100023.host56.com/db_all.php";

     // JSON Node names
     private static final String TAG_SUCCESS = "success";
     private static final String TAG_PRODUCTS = "locations";
     private static final String TAG_PID = "id";
     private static final String TAG_NAME = "name";

     // products JSONArray
     JSONArray products = null;

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

        ActionBar abs = getActionBar();
        abs.setTitle(R.string.activity_title_map);
        abs.setDisplayHomeAsUpEnabled(true);

        mapFragment = new MainMapFragement();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.map, mapFragment);
        ft.commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

     @Override
     protected void onStart() {
         super.onStart();
         new LoadAllLocations().execute();

         setCurrentLocationSpot();
     }

     private void setCurrentLocationSpot() {
         LocationManager lm = (LocationManager) MapsActivity.this.getSystemService(Context.LOCATION_SERVICE);

         Criteria criteria = new Criteria();
         bestProvider = lm.getBestProvider(criteria, false);
         Location location = lm.getLastKnownLocation(bestProvider);

         if (location == null){
             Toast.makeText(MapsActivity.this,"Location Not found",Toast.LENGTH_LONG).show();
          }else{
              geocoder = new Geocoder(MapsActivity.this);
              try {
                  user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                  lat=(double)user.get(0).getLatitude();
                  lng=(double)user.get(0).getLongitude();

                  mPosition = new LatLng(lat, lng);

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

                  mGap.setMyLocationEnabled(true);
                  mGap.animateCamera(CameraUpdateFactory.newLatLngZoom(mPosition, 13));

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

     private void setUpEventSpots() {
          EventInfo firstEventInfo = new EventInfo(new LatLng(60.39341189999999, 5.322973699999999), "Right now - event", new Date(), null);
          EventInfo secondEventInfo = new EventInfo(new LatLng(51.25, 4.15), "Future Event", new Date(1032, 5, 25), null);

          Marker firstMarker = mapFragment.placeMarker(firstEventInfo);
          Marker secondMarker = mapFragment.placeMarker(secondEventInfo);

          eventMarkerMap = new HashMap<Marker, EventInfo>();

          eventMarkerMap.put(firstMarker, firstEventInfo);
          eventMarkerMap.put(secondMarker, secondEventInfo);

          mapFragment.getMap().setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
          @Override
          public void onInfoWindowClick(Marker marker) {
              EventInfo eventInfo = eventMarkerMap.get(marker);
              Toast.makeText(getBaseContext(),
              "The date of " + eventInfo.getName() + " is " + eventInfo.getSomeDate().toLocaleString(),
              Toast.LENGTH_LONG).show();
          }
          });
     }

     class LoadAllLocations extends AsyncTask<String, String, String> {

            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                //pDialog = new ProgressDialog(MapsActivity.this);
                //pDialog.setMessage("Loading locations. Please wait...");
                //pDialog.setIndeterminate(false);
                //pDialog.setCancelable(false);
                //pDialog.show();
            }

            /**
             * getting All products from url
             * */
            protected String doInBackground(String... args) {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                // getting JSON string from URL
                JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

                // Check your log cat for JSON reponse
                Log.d("All Products: ", json.toString());

                try {
                    // Checking for SUCCESS TAG
                    int success = json.getInt(TAG_SUCCESS);

                    if (success == 1) {
                        // products found
                        // Getting Array of Products
                        products = json.getJSONArray(TAG_PRODUCTS);

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

                            // Storing each json item in variable
                            String id = c.getString(TAG_PID);
                            String name = c.getString(TAG_NAME);
                            setUpEventSpots();
                            // creating new HashMap
                            //HashMap<String, String> map = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            //map.put(TAG_PID, id);
                            //map.put(TAG_NAME, name);

                            // adding HashList to ArrayList
                            //productsList.add(map);
                        }
                    } else {
                        // no products found
                        // Launch Add New product Activity
                        //Intent i = new Intent(getApplicationContext(),
                          //      NewProductActivity.class);
                        // Closing all previous activities
                        //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        //startActivity(i);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return null;
            }
     }
}

日志猫:

11-14 21:52:30.391: E/AndroidRuntime(30921): FATAL EXCEPTION: AsyncTask #1
11-14 21:52:30.391: E/AndroidRuntime(30921): Process: com.spxc.nightclubratings, PID: 30921
11-14 21:52:30.391: E/AndroidRuntime(30921): java.lang.RuntimeException: An error occured while executing doInBackground()
11-14 21:52:30.391: E/AndroidRuntime(30921):    at android.os.AsyncTask$3.done(AsyncTask.java:300)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at java.lang.Thread.run(Thread.java:841)
11-14 21:52:30.391: E/AndroidRuntime(30921): Caused by: java.lang.IllegalStateException: Not on the main thread
11-14 21:52:30.391: E/AndroidRuntime(30921):    at maps.aq.o.b(Unknown Source)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at maps.ak.g.b(Unknown Source)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at maps.af.al.a(Unknown Source)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at clz.onTransact(SourceFile:167)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at android.os.Binder.transact(Binder.java:361)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at com.google.android.gms.maps.internal.IGoogleMapDelegate$a$a.addMarker(Unknown Source)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at com.google.android.gms.maps.GoogleMap.addMarker(Unknown Source)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at com.spxc.nightclubratings.adapter.MainMapFragement.placeMarker(MainMapFragement.java:10)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at com.spxc.nightclubratings.MapsActivity.setUpEventSpots(MapsActivity.java:126)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at com.spxc.nightclubratings.MapsActivity.access$1(MapsActivity.java:122)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at com.spxc.nightclubratings.MapsActivity$LoadAllLocations.doInBackground(MapsActivity.java:189)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at com.spxc.nightclubratings.MapsActivity$LoadAllLocations.doInBackground(MapsActivity.java:1)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
11-14 21:52:30.391: E/AndroidRuntime(30921):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
11-14 21:52:30.391: E/AndroidRuntime(30921):    ... 4 more

任何帮助深表感谢!

4

1 回答 1

0

如果您阅读异常,您将看到您无法在 UI 线程之外添加标记。添加任何标记/多边形/折线/圆不能在 UI 线程之外完成

于 2013-11-15T01:48:37.897 回答