I am newbie in android development and working on android application in which i am using google maps along with wikimapia request api. I am showing some buttons on the screen lets say Police, Hospital, Metro. When i click on the button let say "Police" it sends wikimapia request and the markers are displayed on the map,but when i click on "Hospital" it also shows me Hospital markers but along with Police markers. I have also used clear()
of the map, but it clear the whole map. I need to show the markers on the screen on which i click and removes the other markers. My code is given below, please help me out here.
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
}
}
You should call mMap.clear(); in this method, so when you call this it will clear the map and then reassigned the markers.
In your click listener you should make your mMap equals to null, so it can make your above condition true in the method and will help you to clear the map and reassigning of the markers.