Актуализации на местоположението на картата на Google и позициониране на маркер

Мога да добавя множество маркери в моята карта, но всеки път, когато отворя приложението отново, добавените маркери се изчистват и се показва само един маркер на текущото местоположение. Настоящият ми код е даден по-долу, какви промени трябва да направя, за да получавам постоянни актуализации на координатите на местоположението и да запазвам маркери, така че да присъстват всеки път, когато отворя картата си.

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



        }
    });

}

}


person Noor    schedule 28.07.2015    source източник


Отговори (3)


  1. При постоянна актуализация на местоположението препоръчвам да използвате FusedLocationAPI тук е връзката.
  2. Защо са премахнати маркерите. Можете ли да опитате да премахнете метода setUpMapIfNeeded() във вашия onResume()?
person Melvin Mauricio    schedule 28.07.2015
comment
Опитах това. Но маркерите все още са премахнати. Има ли друг начин? - person Noor; 28.07.2015

Мисълта ми е, че повторното отваряне на приложението инициализира картата и всички точки не се инициализират отново. Честно казано, не бих си помислил, че ще останат. Това не е поведението, което бих очаквал. Ако исках да останат, можех да опитам да запазя точките с помощта на SQLite. Това със сигурност ще ги спести, но тогава трябва да помислите за вашето потребителско изживяване при премахване на маркери.

person DasScooter    schedule 28.07.2015

Ако искате да показвате маркери, когато отворите приложението следващия път.. Моля, запазете всяка широчина и дължина на маркерите някъде (SharedPreference или SQLite..) и в onCreate() извикайте тези данни, за да изобразите в карта..

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



    }
});
person CodeMonster    schedule 28.07.2015