0

Ich habe einige Marker auf der Karte platziert. Wenn sich die Position des Markers ändert, wird ein anderer Marker auf der Karte platziert, aber der letzte Marker bleibt unverändert, wodurch mehrere Marker derselben ID auf der Karte erstellt werden.Entfernen Sie die vorherigen Marker als Standort-Updates

Ich habe eine Möglichkeit, den vorherigen Marker als Speicherort zu löschen.

Ich erhalte Standortänderungen von der Firebase-Datenbank in einem beliebigen Array.

Hier ist mein Code:

import android.content.Intent; 
import android.media.MediaPlayer; 
import android.net.Uri; 
import android.os.Bundle; 
import android.os.Handler; 
import android.support.design.widget.NavigationView; 
import android.support.design.widget.Snackbar; 
import android.support.v4.view.GravityCompat; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.ActionBarDrawerToggle; 
import android.support.v7.widget.Toolbar; 
import android.telephony.SmsManager; 
import android.util.Log; 
import android.view.MenuItem; 
import android.view.View; 

import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.OnMapReadyCallback; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.Marker; 
import com.google.android.gms.maps.model.MarkerOptions; 
import com.google.firebase.database.DataSnapshot; 
import com.google.firebase.database.DatabaseError; 
import com.google.firebase.database.DatabaseReference; 
import com.google.firebase.database.FirebaseDatabase; 
import com.google.firebase.database.ValueEventListener; 

import java.util.ArrayList; 
import java.util.Map; 

public class MapsActivity extends MainActivity implements OnMapReadyCallback { 
// flag for Internet connection status 
Boolean isInternetPresent = false; 

// Connection detector class 
ConnectionDetector cd; 

// Alert Dialog Manager 
AlertDialogManager alert = new AlertDialogManager(); 

// GPS Location 
GPSTracker gps; 

Handler handler = new Handler(); 
Runnable refresh; 


final int[] count = {0}; 

final ArrayList<String> locationData = new ArrayList<>(); 
final ArrayList<String> DriverInfo = new ArrayList<>(); 

public GoogleMap mMap; 
public Marker marker; 

MediaPlayer mediaPlayer; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maps); 

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
      this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
    drawer.setDrawerListener(toggle); 
    toggle.syncState(); 

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { 
     @Override 
     public boolean onNavigationItemSelected(MenuItem item) { 
      int id = item.getItemId(); 

      if (id == R.id.profile) { 
       finish(); 
       startActivity(new Intent(MapsActivity.this, ProfileActivity.class)); 
      } else if (id == R.id.nearby) { 
       finish(); 
       startActivity(new Intent(MapsActivity.this, NearbyActivity.class)); 
      } else if (id == R.id.notification) { 
       finish(); 
       startActivity(new Intent(MapsActivity.this, NotificationActivity.class)); 
      } else if (id == R.id.setting) { 
       finish(); 
       startActivity(new Intent(MapsActivity.this, SettingsActivity.class)); 
      } else if (id == R.id.faq) { 
       finish(); 
       startActivity(new Intent(MapsActivity.this, FaqActivity.class)); 
      } else if (id == R.id.emergecy_contact) { 
       finish(); 
       startActivity(new Intent(MapsActivity.this, EmergencyContactActivity.class)); 
      } else if (id == R.id.support) { 
       finish(); 
       startActivity(new Intent(MapsActivity.this, SupportActivity.class)); 
      } else if (id == R.id.help) { 
       finish(); 
       startActivity(new Intent(MapsActivity.this, HelpActivity.class)); 
      } else if (id == R.id.about_us) { 
       finish(); 
       startActivity(new Intent(MapsActivity.this, AboutUsActivity.class)); 
      } else if (id == R.id.rate) { 
       finish(); 
       startActivity(new Intent(MapsActivity.this, RateUsActivity.class)); 
      } else if (id == R.id.share) { 
       finish(); 
       startActivity(new Intent(MapsActivity.this, ShareActivity.class)); 
      } 

      DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
      drawer.closeDrawer(GravityCompat.START); 
      return true; 
     } 
    }); 

    mediaPlayer = MediaPlayer.create(this, R.raw.demonstrative); 

    cd = new ConnectionDetector(getApplicationContext()); 

    // Check if Internet present 
    isInternetPresent = cd.isConnectingToInternet(); 
    if (!isInternetPresent) { 
     // Internet Connection is not present 
     alert.showAlertDialog(MapsActivity.this, "Internet Connection Error", 
       "Please connect to working Internet connection", false); 
     // stop executing code by return 
     return; 
    } 

    // creating GPS Class object 
    gps = new GPSTracker(this); 

    // check if GPS location can get 
    if (gps.canGetLocation()) { 
     Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude()); 
    } else { 
     // Can't get user's current location 
     alert.showAlertDialog(MapsActivity.this, "GPS Status", 
       "Couldn't get location information. Please enable GPS", 
       false); 
     // stop executing code by return 
     return; 
    } 
    // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 


    //Retrive data from firebase 

    final FirebaseDatabase database = FirebaseDatabase.getInstance(); 
    final DatabaseReference myRef = database.getReference().child("users"); 


    myRef.addValueEventListener(new ValueEventListener() { 
     @Override 
     public void onDataChange(DataSnapshot dataSnapshot) { 
      collectLocation((Map<String, Object>) dataSnapshot.getValue()); 
      collectdriverInfo((Map<String, Object>) dataSnapshot.getValue()); 
     } 

     @Override 
     public void onCancelled(DatabaseError databaseError) { 

     } 

    }); 
} 


//Retrieve location from database 
public void collectLocation(Map<String, Object> users) { 
    for (Map.Entry<String, Object> entry : users.entrySet()) { 
     //Get user map 
     Map singleUser = (Map) entry.getValue(); 
     //Get phone field and append to list 
     locationData.add((String) singleUser.get("location")); 

     count[0]++; 

    } 

    System.out.println("Location: " + locationData.toString()); 
    System.out.println("My count is: " + count[0]); 
} 

//Retrive driver info from database 
public void collectdriverInfo(Map<String, Object> users) { 
    final String[] userName = new String[count[0]]; 
    final String[] userContact = new String[count[0]]; 

    final double[] latitude = new double[count[0]]; 
    final double[] longitude = new double[count[0]]; 


    for (Map.Entry<String, Object> entry : users.entrySet()) { 
     //Get user map 
     Map singleUser = (Map) entry.getValue(); 
     //Get phone field and append to list 
     DriverInfo.add((String) singleUser.get("driverInfo")); 
    } 
    System.out.println("Driver Information: " + DriverInfo.toString()); 


    //Convert location string to double 
    int j = 0; 
    for (String loc : locationData) { 
     System.out.println("LocationMMdm" + loc); 
     String[] Location = loc.split(","); 
     latitude[j] = Double.parseDouble(Location[0]); 
     longitude[j] = Double.parseDouble(Location[1]); 
     System.out.println("lat: " + latitude[0] + " " + "log: " + longitude[0]); 

     j++; 
    } 

    //Split driver info and add marker on map 
    int i = 0; 
    for (String data : DriverInfo) { 
     System.out.println("datainfo " + data); 
     String[] singleEntry = data.split(","); 
     userName[i] = singleEntry[0]; 
     userContact[i] = singleEntry[1]; 

     mMap.addMarker(new MarkerOptions().position(new LatLng(latitude[i], longitude[i])). 
        title(userName[i]). 
        snippet(userContact[i]). 
        flat(true). 
        alpha(0.9f). 
        anchor(0.5f, 0.5f). 
        rotation((0.0f)). 
        icon(BitmapDescriptorFactory.fromResource(R.drawable.markeramb))); 
      i++; 
    } 


    mMap.setOnInfoWindowLongClickListener(new GoogleMap.OnInfoWindowLongClickListener() { 
     @Override 
     public void onInfoWindowLongClick(Marker marker) { 
      String phoneno = marker.getSnippet(); 
      double myLat = gps.getLatitude(); 
      double myLog = gps.getLongitude(); 
      String title = marker.getTitle(); 
      String msg = myLat + ", " + myLog; 

      try { 
       SmsManager smsManager = SmsManager.getDefault(); 
       smsManager.sendTextMessage(phoneno, null, msg, null, null); 

       View view = findViewById(android.R.id.content); 
       Snackbar.make(view, "Message Sent", Snackbar.LENGTH_LONG).show(); 

       mediaPlayer.start(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 

    //Call to the ambulance driver 
    mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() { 
     @Override 
     public void onInfoWindowClick(Marker marker) { 
      try { 
       String uri = "tel:" + marker.getSnippet(); 
       if (marker.getSnippet() == null) { 
        alert.showAlertDialog(MapsActivity.this, "Not Present", 
          "Contact no. not available", false); 
       } else { 
        finish(); 
        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri)); 
        startActivity(callIntent); 
       } 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

     } 
    }); 
    System.out.println("Users name are: " + userName.toString()); 
    System.out.println("Users count is: " + userContact.toString()); 
    System.out.println("Count is:" + count[0]); 
} 



@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 
    mMap.setMyLocationEnabled(true); 
    double myLatitude = gps.getLatitude(); 
    double myLongitude = gps.getLongitude(); 
    LatLng latLng = new LatLng(myLatitude, myLongitude); 
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10)); 
} 


@Override 
public void onBackPressed() { 
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    if (drawer.isDrawerOpen(GravityCompat.START)) { 
     drawer.closeDrawer(GravityCompat.START); 
    } else { 
     super.onBackPressed(); 
     finish(); 
     startActivity(new Intent(MapsActivity.this, MainActivity.class)); 
    } 
    } 
} 
+0

Verwenden Sie einfach mMap.clear() als die erste Zeile in OnDataChange Verfahren von ValueEventListener helfen, zu entfernen. –

+0

Danke, Rishabh mMap.clear hat funktioniert, aber anstatt es in OnDataChange-Methode zu verwenden, habe ich es in meiner collectionLocation-Funktion verwendet –

Antwort

0

Die unten können Sie Marker

if (destnationMarker != null) { 

    destnationMarker.remove(); 
    mMap.clear(); 
    destnationMarker = null; 

} 
+0

Danke, aber es löste mein Problem nicht Bitte beziehen Sie sich auf meinen Code und schlagen Sie mir einige Änderungen vor. Ich denke, ich mache etwas falsch –

Verwandte Themen