在新的wikimapia地方请求更新谷歌地图上的标记

时间:2015-06-18 10:45:42

标签: android google-maps google-maps-markers

我是Android开发中的新手,并在Android应用程序上工作,我正在使用谷歌地图以及wikimapia请求api。我在屏幕上显示一些按钮让我们说警察,医院,地铁。当我点击按钮时,请说"警察"它发送wikimapia请求,标记显示在地图上,但当我点击"医院"它还向我展示了医院标记,但还有警察标记。我还使用了地图的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

    }

}

2 个答案:

答案 0 :(得分:1)

你应该调用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();
            }
        });

答案 1 :(得分:0)

执行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();