Google map location updates and marker positioning

I am able to add multiple markers in my map, but every time I open the application again, added markers are cleared and only one marker at current location is shown. My present code is given below, what changes should I make to get constant location coordinate updates and to save markers so they are present every time I open my map.

public class MainActivity extends FragmentActivity implements View.OnClickListener {

public static final String mapLongitude="longitude";
public static final String mapLatitude="latitude";
FragmentManager fm = getSupportFragmentManager();
Button displayareas;



private GoogleMap newmap; // Might be null if Google Play services APK is not available.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    displayareas = (Button) findViewById(R.id.display);
    displayareas.setOnClickListener(this);
    Log.d("Map","MapCreated");
    setUpMapIfNeeded();

}
@Override
public void onClick(View v) {
    if(v.getId()==R.id.display){
        Intent intent = new Intent(this, AllAreas.class);

        startActivity(intent);
    }

}

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


private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (newmap == null) {
        // Try to obtain the map from the SupportMapFragment.
        newmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (newmap != null) {
            setUpMap();
            Log.d("MAPS","Map working");


        }
        else Log.d("MAPS","not working");

    }
}


private void setUpMap() {

    newmap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));

    // Enable MyLocation Layer of Google Map
    newmap.setMyLocationEnabled(true);

    // Get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    // Get the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);

    // Get Current Location
    Location myLocation = locationManager.getLastKnownLocation(provider);

    // set map type
    newmap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    // Get latitude of the current location
    double latitude = myLocation.getLatitude();

    // Get longitude of the current location
    double longitude = myLocation.getLongitude();

    // Create a LatLng object for the current location
    LatLng latLng = new LatLng(latitude, longitude);

    // Show the current location in Google Map
    newmap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    // Zoom in the Google Map
    newmap.animateCamera(CameraUpdateFactory.zoomTo(20));
    newmap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My location"));

    Log.d("LATITUDE",String.valueOf(latitude));
    Log.d("LONGITUDE",String.valueOf(longitude));
    GoogleMap.OnMarkerClickListener listener = new GoogleMap.OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(final Marker marker) {

            AddGeofenceFragment dFragment = new AddGeofenceFragment();
            // Show DialogFragment
            dFragment.show(fm, "Dialog Fragment");
            return true;
        }

    };

    newmap.setOnMarkerClickListener(listener);

    newmap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

        @Override
        public void onMapClick(LatLng latLng) {

            // Creating a marker
            MarkerOptions markerOptions = new MarkerOptions();

            // Setting the position for the marker
            markerOptions.position(latLng);

            // Setting the title for the marker.
            // This will be displayed on taping the marker
            markerOptions.title(latLng.latitude + " : " + latLng.longitude);


            // Animating to the touched position
            newmap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

            // Placing a marker on the touched position
            newmap.addMarker(markerOptions);
            Log.d("ADDED LATITUDE",String.valueOf(latLng.latitude));
            Log.d("ADDED LONGITUDE",String.valueOf(latLng.longitude));

            Toast.makeText(getApplicationContext(),"Block area updated",Toast.LENGTH_LONG).show();



        }
    });

}

}

Answers


  1. On constant location update, I recommend using FusedLocationAPI here is the link.
  2. On why the markers were removed. Can you try to remove setUpMapIfNeeded() method in your onResume() ?

My thought is that re-opening the app re initializes the map and all points aren't re-initialized. Honestly I wouldn't think they would stay. It's not the behavior I would expect. If I wanted them to stay I might try to save the points using SQLite. That would save them for sure, but then you need to think about your marker removal user experience.


If you want to show markers when open app in next time.. Please save each lat and long of markers to somewhere (SharedPreference or SQLite ..) and in onCreate() call this data to render in map ..

newmap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

    @Override
    public void onMapClick(LatLng latLng) {

        // Creating a marker
        MarkerOptions markerOptions = new MarkerOptions();

        // Setting the position for the marker
        markerOptions.position(latLng);

        // Setting the title for the marker.
        // This will be displayed on taping the marker
        markerOptions.title(latLng.latitude + " : " + latLng.longitude);


        // Animating to the touched position
        newmap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

        // Placing a marker on the touched position
        newmap.addMarker(markerOptions);
        Log.d("ADDED LATITUDE",String.valueOf(latLng.latitude));
        Log.d("ADDED LONGITUDE",String.valueOf(latLng.longitude));

        //Save it to SharedPreference or SQLite .
        Toast.makeText(getApplicationContext(),"Block area updated",Toast.LENGTH_LONG).show();



    }
});

Need Your Help

Instantiate Apigee.Client With JavaScript

javascript json apigee

I just learned about Apigee yesterday and decided to tinker with it a bit. I am working through the installation article to implement it into JavaScript and am supposed to, "...pass a JSON object w...