当纬度经度发生变化时,在Google地图中移动标记

时间:2015-07-27 13:50:47

标签: android google-maps dictionary

在我的应用程序中创建一个包含来自JSON的纬度和经度的数组列表并在地图中添加标记购买起诉数组列表但是当lat long更改时标记从一个位置移动到另一个位置但是它创建了两个标记而不是移动,如果我给map.clear(),整个标记得到禁用和启用但我想删除旧标记如何不使用map.clear(),请帮助

private void setUpMapIfNeeded(查看inflatedView){

        if (mMap == null) { 
            mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap(); 
            mMap.setMyLocationEnabled(true); 

            Location myLocation = mMap.getMyLocation(); 
            if (mMap != null) {  
                //mMap.clear();

                // setUpMap(); 
                mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() { 

                    @Override 
                    public void onMyLocationChange(Location arg0) { 

                        // TODO Auto-generated method stub 
                        final LatLngBounds.Builder builder = new LatLngBounds.Builder(); 
                     mMap.clear();
                        if (marker != null) {
                             marker.remove();
                         }
                        for (int i = 0; i < arraylist1.size(); i++) { 
                            final LatLng position = new LatLng(Double 
                                    .parseDouble(arraylist1.get(i).get("Latitude")), 
                                    Double.parseDouble(arraylist1.get(i).get( 
                                            "Longitude"))); 
                            String ime1 = arraylist1.get(i).get("IME");

                            final MarkerOptions options = new MarkerOptions() 
                            .position(position); 
                            //mMap.addMarker(options); 
                            //mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));

                              marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));

                            //options.title(ime1);
                            builder.include(position); 

                        } 
                        LatLng latLng = new LatLng(arg0.getLatitude(), arg0 
                                .getLongitude()); 
                        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                        mMap.setMyLocationEnabled(true); 

                        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
                        // mMap.setOnMapClickListener(null); 
                        mMap.setOnMarkerClickListener(null); 

                        mMap.animateCamera(CameraUpdateFactory.zoomTo(9)); 
                    } 
                }); 

            } 
        } 
    } 

    /*  protected void retrieveAndAddCities() throws IOException { 
        HttpURLConnection conn = null; 
        final StringBuilder json = new StringBuilder(); 
        try { 

            URL url = new URL(SERVICE_URL); 
            conn = (HttpURLConnection) url.openConnection(); 
            InputStreamReader in = new InputStreamReader(conn.getInputStream()); 

            int read; 
            char[] buff = new char[1024]; 
            while ((read = in.read(buff)) != -1) { 
                json.append(buff, 0, read); 
            } 
        } catch (IOException e) { 
            Log.e(LOG_TAG, "Error connecting to service", e); 
            throw new IOException("Error connecting to service", e); 
        } finally { 
            if (conn != null) { 
                conn.disconnect(); 
            } 
        } 
        new DownloadJSON().execute(); 

    } */

    private class DownloadJSON extends AsyncTask<Void, Void, Void> { 
        String result=""; 
        @Override 
        protected void onPreExecute() { 
            super.onPreExecute(); 
        }

        @Override 
        protected Void doInBackground(Void... params) { 
            try { 
                arraylist1 = new ArrayList<HashMap<String, String>>(); 

                JSONParser jParser = new JSONParser(); 
                String result = ""; 

                json = jParser.getJSONFromUrl(SERVICE_URL); 

                try { 
                    //arraylist1.clear(); 

                    jsonarray = json.getJSONArray("SingleIMEs"); 
                    Log.d("Haaaaaaaaaaaa", "" + json); 

                    for (int i = 0; i < jsonarray.length(); i++) { 
                        Log.d("H11111111111111111111111111", 
                                "" + jsonarray.length()); 
                        map = new HashMap<String, String>(); 
                        json = jsonarray.getJSONObject(i); 

                        // pubname = json.getString("PubName"); 
                        latitude = json.getDouble("Latitude"); 
                        longitude = json.getDouble("Longitude"); 
                        ime = json.getString("IME");
                        //  map.put("PubName", json.getString("PubName")); 
                        //map.put("PubID", json.getString("PubID")); 
                        map.put("Latitude", json.getString("Latitude")); 
                        Log.e("CHECKLAT",""+json.getString("Latitude") );
                        map.put("Longitude", json.getString("Longitude")); 
                        Log.e("CHECKLONG",""+json.getString("Longitude") );

                        map.put("IME", json.getString("IME"));
                        arraylist1.add(map); 
                    } 

                } catch (JSONException e) { 
                    Log.e("log_tag", "Error parsing data " + e.toString()); 
                    result="Error"; 
                    e.printStackTrace(); 
                } 
            }catch(Exception e){ 
                result="Error"; 
            } 

            return null; 
        } 

        protected void onPostExecute(Void args) { 

            // mProgressDialog.dismiss(); 

        } 
    } 

    @Override 
    public void onResume() { 
        super.onResume(); 
        mMapView.onResume(); 
    } 

    @Override 
    public void onPause() { 
        super.onPause(); 
        mMapView.onPause(); 
    } 

    @Override 
    public void onDestroy() { 
        mMapView.onDestroy(); 
    super.onDestroy(); 
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

   /* Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
        Log.d("onLocationUpdated!!!","");
        new DownloadJSON().execute(); 
        setUpMapIfNeeded(rootView);*/

    }


    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {

        // TODO Auto-generated method stub

    } 


}

2 个答案:

答案 0 :(得分:1)

首先,你需要以某种方式识别你的标记,每个标记必须有一个uniq id,让我们说它是String

然后你需要存储你的标记。

private HashMap<String, Marker> mMarkers = new HashMap<>();

然后在使用新数据更新标记之前,您需要复制以前的标记集合,以找出新添加的标记和丢失的标记:

HashMap<String, Marker> oldMarkers = mMarkers;
mMarkers = new HashMap<>();

for (YourMarkerObject m : newMarkers) { // I assume you have collections of your objects here
  String id = m.getId(); // Get an id
  Marker marker = oldMarkers.get(id);
  if (marker == null) { // it means it's the new one
    // Create marker and attach it to the map on the right position
  } else { // it means we already have this marker attached, so just move it
    marker.setPosition(m.getPosition());
    oldMarkers.remove(id); // Remove this one from old markers collection
  }

  mMarkers.put(id, marker);
}

for (Marker oldMarker : oldMarkers.values()) {
  // Detach old markers
}

答案 1 :(得分:0)

您需要保留创建时创建的所有标记,因为绘制后无法从地图中获取特定标记。然后,您所要做的就是从列表中找到标记并进行更新。

我使用HashMap存储标记,以便我可以通过某个键快速引用它们