根据新的 wikimapia 地点请求更新 google 地图上的标记

Update markers on google maps on new wikimapia place request

我是 android 开发和 android 应用程序的新手,我在其中使用 google 地图和 wikimapi 一个请求 api .我在屏幕上显示了一些按钮,比如警察、医院、地铁。当我点击按钮时,假设 "Police" 它向 wikimapi 发送一个请求并且标记显示在地图上,但是当我点击 "Hospital" 它也向我显示医院标记但是与警察标记。我也用过clear()的地图,但它清除了整个地图。我需要在我点击并删除其他标记的屏幕上显示标记。我的代码如下,请帮帮我。

public class MyLocationActivity extends BaseActivity implements
OnMapClickListener, OnMapLongClickListener, NetworkStateReceiverListener{

    private GoogleMap mMap;
    private Location lastLocation = null;
    private LocationClient mLocationClient;
    public AlertDialog alert;
    DocumentBuilder documentBuilder;
    Document document;
    private NetworkStateReceiver networkStateReceiver;
    boolean connectionStatus = false;
    final MarkerOptions markerOptions = new MarkerOptions();

    private static final LocationRequest REQUEST = LocationRequest.create()
            .setInterval(8000) // 5 seconds
            .setFastestInterval(16) // 16ms = 60fps
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


    @Override
    protected void onStart() {
        sActivityMyLocation = this;
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        sActivityMyLocation = null;

        mMap.clear();
        //unregisterReceiver(networkStateReceiver);
        super.onDestroy();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_location_hospitals);

        networkStateReceiver = new NetworkStateReceiver();
        networkStateReceiver.addListener(this);
        this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));

        ImageView imgHospital = (ImageView) findViewById(R.id.imgHospital);

        imgHospital.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new PlacesAPICall().execute();
            }
        });

        ImageView imgPolice = (ImageView) findViewById(R.id.imgPolice);

        imgPolice.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                new PlacesAPICall().execute();



            }
        });

        ImageView imgMetro = (ImageView) findViewById(R.id.imgMetro);

        imgMetro.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {


                new PlacesAPICall().execute();

            }
        });



        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    }

    @Override
    protected void onResume() {
        super.onResume();

        setUpMapIfNeeded();
        setUpLocationClientIfNeeded();
        mLocationClient.connect();


    }

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

        if (mLocationClient != null) {
            mLocationClient.disconnect();
        }
    }

    private void setUpMapIfNeeded() {
        if (mMap == null) {
            mMap = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            mMap.setOnMapClickListener(MyLocationActivity.this);

            if (mMap != null) {
                mMap.setOnMapClickListener(MyLocationActivity.this);
                mMap.setMyLocationEnabled(true);
                mMap.setBuildingsEnabled(true);
                mMap.setIndoorEnabled(true);
                mMap.setMapType(mMap.MAP_TYPE_NORMAL);
                mMap.setTrafficEnabled(true);
            }
        }
    }

    private void setUpLocationClientIfNeeded() {
        if (mLocationClient == null) {
            mLocationClient = new LocationClient(getApplicationContext(),
                    connectionCallbacks, onConnectionFailedListener);
        }
    }

    ConnectionCallbacks connectionCallbacks = new ConnectionCallbacks() {

        @Override
        public void onDisconnected() {

        }

        @Override
        public void onConnected(Bundle connectionHint) {
            mLocationClient.requestLocationUpdates(REQUEST, locationListener);
        }
    };

    OnConnectionFailedListener onConnectionFailedListener = new OnConnectionFailedListener() {

        @Override
        public void onConnectionFailed(ConnectionResult result) {

        }
    };

    OnMyLocationChangeListener onMyLocationChangeListener = new OnMyLocationChangeListener() {

        @Override
        public void onMyLocationChange(Location location) {

        }
    };

    LocationListener locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {

            float diff = 0;

            if (lastLocation != null) {
                diff = location.distanceTo(lastLocation);
            }

            if ((lastLocation == null) || (diff > 5)) {

                LatLng latLng = new LatLng(location.getLatitude(),
                        location.getLongitude());

                CameraPosition cameraPosition = new CameraPosition(latLng, 14,
                        45, 0);

                CameraUpdate cameraUpdate = CameraUpdateFactory
                        .newCameraPosition(cameraPosition);

                mMap.animateCamera(cameraUpdate, 25, null);

                mMap.getUiSettings().setZoomControlsEnabled(true);
                mMap.getUiSettings().setZoomGesturesEnabled(true);
                //new PlacesAPICall().execute();

                lastLocation = location;
            }

        }
    };


    String urlString;

    class PlacesAPICall extends AsyncTask<Void, Void, Void> {

        JSONObject jObject;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            showLoadingDialog();
        }

        @Override
        protected Void doInBackground(Void... params) {

            BufferedReader reader = null;
            String key = "D###0545-58###39-6#####D-41####77-4#####8-###1C28-D524###7-#####4F5";
            String category = "287";// For the nearest medical related facilities. It could be a pharmacy,clinic hospital etc.
            if(isHospital == true){
//              urlString = "http://api.wikimapia.org/?key="+key+"&function=place.getnearest&q=&lat="+lastLocation.getLatitude()+"&lon="+lastLocation.getLongitude()+"&format=json&pack=&language=en&page=1&count=100&category="+category+"&categories_or=&categories_and=&distance=";//Hospital
                urlString = "http://api.wikimapia.org/?key="+key+"&function=place.search&q=&lat="+lastLocation.getLatitude()+"&lon="+lastLocation.getLongitude()+"&format=json&pack=&language=en&page=1&count=50&category=287&categories_or=&categories_and=&distance=";
            }else if(isMetro == true){
                urlString = "http://api.wikimapia.org/?key="+key+"&function=place.search&lat="+lastLocation.getLatitude()+"&lon="+lastLocation.getLongitude()+"&format=json&pack=&language=en&count=100&category="+44758;//Metro
            }else if(isPolice == true){
                urlString = "http://api.wikimapia.org/?key="+key+"&function=place.search&lat="+lastLocation.getLatitude()+"&lon="+lastLocation.getLongitude()+"&format=json&pack=&language=en&count=100&category="+670;// Police
            }


            if(connectionStatus){

            try {

                URL url = new URL(urlString);

                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(
                        conn.getOutputStream());
                wr.flush();

                reader = new BufferedReader(new InputStreamReader(
                        conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;

                while ((line = reader.readLine()) != null) {
                    // Append server response in string
                    sb.append(line + "");
                }

                String content = sb.toString();

                Logs.v(getLocalClassName(),
                        "Places API InBackgroung, Contect = " + content);

                try {
                    jObject = new JSONObject(content);

                } catch (Exception e) {
                    Logs.e("Exception", e.toString());
                }

            } catch (Exception ex) {
                Logs.v(getLocalClassName(), "Places API InBackgroung, Error = "
                        + ex.toString());
            }  finally {
                try {
                    reader.close();
                } catch (Exception ex) {
                }
            }
        }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            Bitmap bitmap = null;

            String icon = "", latitude = "", longitude = "",distance = "",place = "";

            if(connectionStatus==true){
                try {
                    //  JSONArray arrayOfPlaces = jObject.getJSONArray("results");
                        JSONArray arrayOfPlaces = jObject.getJSONArray("places");

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

                            JSONObject jPlace = arrayOfPlaces.getJSONObject(i);

                            if (!jPlace.isNull("title")) {
                                place = jPlace.getString("title");
                            }
                            if (!jPlace.isNull("urlhtml")) {
                                icon = jPlace.getString("urlhtml");
                            }
                            if (!jPlace.isNull("id")) {
                                distance = jPlace.getString("id");
                            }
                            if (!jPlace.isNull("distance")) {
                                distance = jPlace.getString("distance");
                            }

                            longitude = jPlace.getJSONObject("location").getString("lon");
                            latitude = jPlace.getJSONObject("location").getString("lat");

                            double lat = Double.parseDouble(latitude);
                            double lng = Double.parseDouble(longitude);
                            LatLng latLng = new LatLng(lat, lng);

                            //mMap.clear();
                            // It clears the whole map
                            markerOptions.position(latLng);
                            markerOptions.title(place);

                            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_x));
                            mMap.getUiSettings().setZoomControlsEnabled(true);
                            mMap.addMarker(markerOptions).setSnippet("Distance "+distance);
                            mMap.addMarker(markerOptions).showInfoWindow();

                        }

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


            dismissLoadingDialog();
        }
    }

    }

    @Override
    public void onMapLongClick(LatLng arg0) {
        // TODO Auto-generated method stub

    }

}

您应该在执行 mMap.addMarker(markerOptions) 时保存标记的引用,然后在您的标记上执行 .remove() 操作。

所以,它应该看起来像...

private GoogleMap gMap;
private Marker myMarker;
....
....//where you add the marker
    myMarker = gMap.addMarker(marker);
    myMarker.showInfoWindow();
....
....//where you remove the marker
    myMarker.remove();

你应该调用 mMap.clear();在此方法中,因此当您调用此方法时,它将清除地图,然后重新分配标记。

 private void setUpMapIfNeeded() {
            if (mMap == null) {

                mMap = ((SupportMapFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.map)).getMap();
                mMap.clear();
                mMap.setOnMapClickListener(MyLocationActivity.this);

                if (mMap != null) {
                    mMap.setOnMapClickListener(MyLocationActivity.this);
                    mMap.setMyLocationEnabled(true);
                    mMap.setBuildingsEnabled(true);
                    mMap.setIndoorEnabled(true);
                    mMap.setMapType(mMap.MAP_TYPE_NORMAL);
                    mMap.setTrafficEnabled(true);
                }
            }
        }

在你的点击监听器中,你应该让你的 mMap 等于 null,这样它可以在方法中使你的上述条件为真,并帮助你清除地图和重新分配标记。

 ImageView imgPublicToilet = (ImageView) findViewById(R.id.imgPublicToilet);

        imgPublicToilet.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mMap = null;
                setUpMapIfNeeded();
            }
        });