Marker.remove()无法在谷歌地图中工作,我想删除半径外的标记?

时间:2015-10-12 09:24:22

标签: java android google-maps

在我的应用程序中我正在使用标记列表但是当我尝试删除标记时它没有删除标记。

Marker.remove()无法在谷歌地图中使用,我想删除半径范围外的标记。

请帮忙

我的源代码如下:

public class MapFragment extends Fragment implements LocationListener
{ 
    private static final String LOG_TAG = "ExampleApp"; 

    private MapView mMapView; 
    private GoogleMap mMap; 
    private Bundle mBundle; 
    private static final String SERVICE_URL = "http://203.187.247.199/primevts/vtsservice.svc/data"; 
    JSONObject json = null; 
    JSONObject jsonobject = null; 
    JSONObject jsonobject1 =null;
    JSONObject jsonobject2 =null;
    JSONObject ja = null; 
    JSONArray jsonarray = null; 
    JSONArray jsonarray1 = null;
    JSONArray jsonarray2 = null;
    ProgressDialog mProgressDialog; 
    ArrayList<HashMap<String, String>> arraylist1; 
    ArrayList<HashMap<String, String>> arraylist11; 
    ArrayList<HashMap<String, String>> arraylist12; 
    ArrayList<HashMap<String, String>> arraylist; 
    List<Marker> markerList = new ArrayList<Marker>();
    private Timer timer;
    static String LONG = "Long"; 
    static String LAT = "Lat"; 
    ArrayList<String> ct; 
    public double latt = 0; 
    public double lng = 0; 
    public ArrayList<Integer> dLat; 
    private AlarmManager alarmMgr;
    private PendingIntent alarmIntent;
    private Handler handler;
    public Marker marker;
    Marker stop = null;
    String RegistrationNo="";
    LatLng destination,source,destination2,center;
    Polyline polylin;
    String ime1,destname,routeid;
    GMapV2GetRouteDirection md;
    private HashMap<String, Marker> mMarkers = new HashMap<>();
    int value=1;
    // LatLngBounds values ; 
    double latitude, longitude,destlat,destlong,sourcelat,sourcelong,destlat2,destlong2; 
    String ime,reg,regi; 
    Geocoder geocoder;
    List<Address> addresses;
    CircleOptions circleOptions;
    Circle circle;
    // LatLng val; 
    float[] distance = new float[2];
    static HashMap<String, String> datas; 

    static HashMap<String, String> map; 
    String[] latlngvalues;
    //  LocationManager locman;
    Context context;
    View rootView;
    ImageView imageView1;
    TextView Address;
    public MapFragment() { 
    } 

    @Override 
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, 
            Bundle savedInstanceState) { 
        rootView = inflater.inflate(R.layout.fragment_layout_one, container, false); 


        MapsInitializer.initialize(getActivity()); 

        mMapView = (MapView)rootView.findViewById(R.id.mapView); 
        Address=(TextView)rootView.findViewById(R.id.adressText);
        //imageView1=(ImageView) rootView.findViewById(R.id.imageView1);

        mMapView.onCreate(mBundle); 


        MapsInitializer.initialize(getActivity()); 

        if (android.os.Build.VERSION.SDK_INT > 9) { 
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
            .permitAll().build(); 
            StrictMode.setThreadPolicy(policy); 
        } 
        new DownloadJSON().execute(); 
        setUpMapIfNeeded(rootView);
        new DestinationJSON().execute();
        mMap.setInfoWindowAdapter(new InfoWindowAdapter() {

            @Override
            public View getInfoContents(Marker marker) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public View getInfoWindow(Marker marker) {
                // TODO Auto-generated method stub
                View v  = getActivity().getLayoutInflater().inflate(R.layout.info_window_layout, null);



                TextView markerLabel = (TextView)v.findViewById(R.id.ime);
                TextView destiname=(TextView)v.findViewById(R.id.destname);
                TextView route=(TextView)v.findViewById(R.id.routeid);


                markerLabel.setText(regi);
                destiname.setText(destname);
                route.setText(routeid);
                Log.e("imeid", ""+ime1);
                return v;
            }

        });

        /* handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                 new DownloadJSON().execute(); 
                    setUpMapIfNeeded(rootView); 

                 Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
                 Log.e("Data in Log", "");
            }
        }, 1000);
         */
        final Handler handler = new Handler();
        timer = new Timer();
        TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        //mMap.clear();
                        //Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
                        new DownloadJSON().execute(); 
                        setUpMapIfNeeded(rootView); 
                    }
                });
            }
        };
        timer.schedule(doAsynchronousTask, 20000, 20000);




        /*LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
        //locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
        locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);*/
        return rootView; 
    } 

    private void setUpMapIfNeeded(View inflatedView) { 

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

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

                mMap.setOnCameraChangeListener(new OnCameraChangeListener() {

                    @Override
                    public void onCameraChange(final CameraPosition arg0) {
                        mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
                            @Override
                            public void onMapLoaded() {
                                LatLng latLng= mMap.getCameraPosition().target;
                                double lat = latLng.latitude;
                                double lng = latLng.longitude;
                                Log.e("lati",""+lat);
                                Log.e("longi",""+lng);
                                Log.d("TAG", latLng.toString());
                                //mMap.clear();
                                if(circle!=null){
                                    circle.remove();
                                    //mMap.clear();
                                }



                                circleOptions = new CircleOptions();
                                circleOptions.center(latLng);
                                //circleOptions.fillColor(Color.TRANSPARENT);
                                circleOptions.radius(10000);
                                circleOptions.strokeColor(Color.TRANSPARENT);
                                circle = mMap.addCircle(circleOptions);
                                Log.e("",""+circle);
                                center = mMap.getCameraPosition().target;

                                new GetLocationAsync(center.latitude, center.longitude).execute();

                                /* geocoder = new Geocoder(getActivity(), Locale.getDefault());

                                try {
                                    addresses = geocoder.getFromLocation(lat, lng, 1);
                                     String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                                      Log.e("address",""+address);
                                        String city = addresses.get(0).getLocality();
                                        Log.e("city",""+city);
                                        String state = addresses.get(0).getAdminArea();
                                        Log.e("state",""+state);
                                        String country = addresses.get(0).getCountryName();
                                        Log.e("contry",""+country);
                                        String postalCode = addresses.get(0).getPostalCode();
                                        Log.e("postalcode",""+postalCode);
                                        String knownName = addresses.get(0).getFeatureName();
                                        Log.e("knownName",""+knownName);
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } // Here 1 represent max location result to returned, by documents it recommended 1 to 5


                                //Toast.makeText(this, latLng.toString(), Toast.LENGTH_LONG).show();
                            }*/



                            }
                        });
                    }
                });
                mMap.setOnMarkerClickListener(new OnMarkerClickListener() {

                    @Override
                    public boolean onMarkerClick(Marker arg0) {
                        // TODO Auto-generated method stub
                        if(stop!=null){
                            mMap.clear();
                        }




                        regi=arg0.getTitle().toString();
                        Log.e("aaa", ""+regi);
                        JSONPost jsonpost= new JSONPost();

                        ja=jsonpost.datewise(regi);
                        Log.e("Home_details..", "" + ja);
                        //  new DownloadJSON2().execute();



                        try
                        {

                            arraylist11 = new ArrayList<HashMap<String, String>>();
                            arraylist12 = new ArrayList<HashMap<String, String>>();

                            jsonarray = ja.getJSONArray("Routeinbus");

                            for (int i = 0; i <jsonarray.length(); i++) {

                                HashMap<String, String> map = new HashMap<String, String>();
                                json = jsonarray.getJSONObject(i);
                                Log.e("G>>>>>>>>>>>", "" + json);
                                // Retrive JSON Objects
                                // map.put("flatID", jsonobject.getString("flatID"));
                                map.put("FromLat", json.getString("FromLat"));

                                map.put("FromLong", json.getString("FromLong"));
                                sourcelat = json.getDouble("FromLat"); 
                                sourcelong=json.getDouble("FromLong");
                                source=new LatLng(sourcelat, sourcelong);
                                map.put("Fromaddress", json.getString("Fromaddress"));
                                map.put("ToLat", json.getString("ToLat"));
                                map.put("ToLong", json.getString("ToLong"));
                                routeid=json.getString("RouteID");
                                destname=json.getString("Toaddress");
                                destlat2=json.getDouble("ToLat");
                                destlong2=json.getDouble("ToLong");
                                destination2=new LatLng(destlat2, destlong2);
                                jsonarray1 = json.getJSONArray("Routes");
                                Log.d("Hbbbbbbbbbbbbbbb", "" + jsonarray1);

                                for (int j = 0; j <jsonarray1.length(); j++) {


                                    jsonobject1 = jsonarray1.getJSONObject(j);
                                    jsonarray2=jsonobject1.getJSONArray("stages");
                                    Log.d("jsonarray2", "" + jsonarray2);

                                    for(int k=0;k<jsonarray2.length();k++)
                                    {
                                        jsonobject2 =jsonarray2.getJSONObject(k);
                                        HashMap<String, String> map1 = new HashMap<String, String>();
                                        map1.put("Lat",jsonobject2.getString("Lat"));

                                        Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject2.getString("Lat"));
                                        map1.put("Long",jsonobject2.getString("Long"));
                                        map1.put("StopName", jsonobject2.getString("StopName"));
                                        Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject2.getString("Long"));
                                        //      map1.put("LiveLongitude",jsonobject1.getString("LiveLongitude"));

                                        //       Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject1.getString("LiveLongitude"));


                                        arraylist12.add(map1);

                                        Log.e("arraylist12", ""+arraylist12);

                                        /*if(polylin!=null){
                            polylin.remove();
                        }
                        if(marker!=null){
                            marker.remove();
                        }

                        md = new GMapV2GetRouteDirection();
                        Document doc = md.getDocument(source, destination2,
                                GMapV2GetRouteDirection.MODE_DRIVING);
                        ArrayList<LatLng> directionPoint = md.getDirection(doc);
                        PolylineOptions rectLine = new PolylineOptions().width(10).color(
                                Color.CYAN);

                        for (int a = 0; a < directionPoint.size(); a++) {
                            rectLine.add(directionPoint.get(a));
                        }

                        polylin = mMap.addPolyline(rectLine);*/
                                        //marker=mMap.addMarker(new MarkerOptions().position(destination2).icon(BitmapDescriptorFactory .fromResource(R.drawable.bustour)));


                                        for (int m = 0; m < arraylist12.size(); m++)
                                        { 

                                            final LatLng stopposition = new LatLng(Double .parseDouble(arraylist12.get(m).get("Lat")),Double.parseDouble(arraylist12.get(m).get("Long"))); 
                                            Log.e("position", ""+stopposition);                             
                                            String stopname = arraylist12.get(m).get("StopName");
                                            Log.e("markcheck",""+stopname);


                                                 final MarkerOptions options = new MarkerOptions().position(stopposition).icon(BitmapDescriptorFactory .fromResource(R.drawable.greenbus)).title(stopname); 
                                                    //mMap.addMarker(options); 
                                                 stop=mMap.addMarker(options);
                                        }



                                    }
                                }
                                arraylist11.add(map);
                                Log.e("arraylist11",""+arraylist11);

                            } 

                        }catch (Exception e) {
                            String result = "Error";
                        }

                        return false;
                    }


                });
                // 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"))); 
                            Double lati=Double.parseDouble(arraylist1.get(i).get("Latitude"));
                            Double longi=Double.parseDouble(arraylist1.get(i).get("Longitude"));
                            //  Log.e("doublelati",""+lati);
                            //  Log.e("doublelongi",""+longi);
                            ime1 = arraylist1.get(i).get("RegistrationNo");
                            final MarkerOptions options = new MarkerOptions() 
                            .position(position); 
                            //mMap.addMarker(options); 

                            //marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)));
                            // mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
                            //marker.showInfoWindow();
                            try 
                            {
                                Location.distanceBetween(lati,longi,circle.getCenter().latitude, circle.getCenter().longitude, distance);

                                if ( distance[0] <= circle.getRadius())
                                {

                                    marker=mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.whitebus)).anchor(0.0f, 1.0f).title(ime1));
                                    // Inside The Circle
                                }
                                else 
                                {
                                    //Toast.makeText(getActivity(), "currently no buses available at this location", Toast.LENGTH_SHORT).show();

                                    /*  if(marker!=null)
                                    {
                                            marker.remove();
                                    }*/
                                    // Outside The Circle
                                    marker.remove();
                                }
                            }catch (Exception e){

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

                        } if(value==1){
                            LatLng latLng = new LatLng(arg0.getLatitude(), arg0 
                                    .getLongitude()); 

                            //mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                            mMap.setMyLocationEnabled(true); 

                            //mMap.moveCamera(CameraUpdateFactory.newLatLng(newLatLnglatLng)); 
                            // mMap.setOnMapClickListener(null); 

                            //mMap.animateCamera(CameraUpdateFactory.zoomTo(9)); 
                            CameraPosition cameraPosition = new CameraPosition.Builder()
                            .target(latLng)      // Sets the center of the map to Mountain View
                            .zoom(10)                   // Sets the zoom
                            .build();                   // Creates a CameraPosition from the builder
                            mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                            value++;
                        }
                    }
                }); 
            } 
        }
    }



    private class DestinationJSON 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("http://beta.json-generator.com/api/json/get/NJMZPNSi"); 

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

                        destlat = json.getDouble("Latitude"); 
                        destlong = json.getDouble("Longitude"); 
                        ime = json.getString("IME");
                        //reg=json.getString("RegistrationNo");
                        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("RegistrationNo", json.getString("RegistrationNo"));
                        map.put("IME", json.getString("IME"));
                        destination=new LatLng(destlat, destlong);                  } 

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

        } 
    }
    private class GetLocationAsync extends AsyncTask<String, Void, String> {
        // boolean duplicateResponse;
        double x, y;
        StringBuilder str;

        public GetLocationAsync(double latitude, double longitude) {
            // TODO Auto-generated constructor stub

            x = latitude;
            y = longitude;
        }

        @Override
        protected void onPreExecute() {
            Address.setText(" Getting location ");
        }
        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            try { geocoder = new Geocoder(getActivity(), Locale.ENGLISH);
            addresses = geocoder.getFromLocation(x, y, 1);
            str = new StringBuilder();
            if (geocoder.isPresent()) {
                Address returnAddress = addresses.get(0);

                String localityString = returnAddress.getLocality();
                String city = returnAddress.getCountryName();
                String region_code = returnAddress.getCountryCode();
                String zipcode = returnAddress.getPostalCode();

                str.append(localityString + "");
                str.append(city + "" + region_code + "");
                str.append(zipcode + "");

            } else {
            }
            } catch (Exception e) {
                // TODO: handle exception
                Log.e("tag", e.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                Address.setText(addresses.get(0).getAddressLine(0)
                        + addresses.get(0).getAddressLine(1) + " ");
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    }
    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); 

                        latitude = json.getDouble("Latitude"); 
                        longitude = json.getDouble("Longitude"); 
                        ime = json.getString("IME");
                        reg=json.getString("RegistrationNo");
                        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("RegistrationNo", json.getString("RegistrationNo"));
                        map.put("IME", json.getString("IME"));
                        arraylist1.add(map); 
                        //Log.e("arraylist1", ""+arraylist1);
                    } 

                } 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 onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }

    @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

    } {




    }



    }

0 个答案:

没有答案