Search code examples
androidsqlitegoogle-mapsmarker

Markers disappear


I trying to set marker visible on the map when I am in range and set invisible when i am not in range. When am moving and enter area marker appear - but when I get out of range marker is still visible. Here is my code onLocationUpdate. I iterate over my database and adding markers. getDeviceLocation return Ltglng with my current location. I implement this also for GPS provider. Any ideas will be helpfull ty!

 locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Cursor res = activityA.myDB.getAllData();
                while (res.moveToNext()) {

                    double ltd = Double.valueOf(res.getString(3));
                    double lng = Double.valueOf(res.getString(4));
                    LatLng hole = new LatLng(ltd, lng);
                    Marker marker = mMap.addMarker(new MarkerOptions().position(hole)
                            .title(res.getString(1)).visible(false));

                 if (SphericalUtil.computeDistanceBetween(getDeviceLocation(), marker.getPosition()) <3 ) {
                        marker.setVisible(true);
                    } 
                }
            }

Solution

  • From what you have provided this is what I can gather.

    You are adding the marker (originally set to invisible), and then if it meets your if statement, you make them invisible. The problem is, I don't see any place, where you would make them invisible again, or remove them.

    Do you save these markers in your activity? For example in an ArrayList?

    I have two suggestions:

    1)Either call mMap.clear() before before your while statement. This will clear the map of any markers, and then adds the new ones as they are created.

    2)Save all your markers in an ArrayList and then in your onLocationChanged, use a for loop to go through all your markers and make the ones out of range invisible. Here is an example:

    for (Marker marker: mMarkerArrayList) {
        if (outOfRange()) {
            marker.visible(false);
        }
    }
    

    Here mMarkerArrayList is the ArrayList containing all your markers. outOfRange() is a helper function that returns a boolean if the marker is outOfRange.