I know there are similar questions around, but I was not able to find a solid answer, here is my question: Is there any way I can make Markers without a Google Map reference to be stored in an ArrayList (or any other storage), and then just simply add them to my map?
Background:
I have an app, that at the moment has around 3,500 markers. Each marker also has a data associated with it (boolean array storing data for each marker which is used to make them visible/invisible based on users interactions). At the moment, I get these marker's location and data using a class that extends AsyncTask. After the loading is finished, then I create my markers using this data on the main Thread. However, this takes some time, and it freezes the UI while the markers are being created and added to the map. I want to do this somehow in the background.
What I have tried so far:
I created another class that extends AsyncTask passing in my LocationData and my Google Map object. But I get an error when I try to make the markers in my Async class. I get a Runtime error saying I need to do this on the UI thread.
java.lang.RuntimeException: An error occurred while executing
doInBackground()
Caused by: com.google.maps.api.android.lib6.common.apiexception.c: Not
on the main thread
I have also thought about just making MarkerOptions object in the background and then use that to create markers in the main thread; however, I cannot add a tag to the MarkerOption, it needs to be added to the marker. In that case, I need to go through all of them again in the main thread just to add the tag, which I feel like is not saving me too much time/resources.
Any suggestion/help would be appreciated on how to create these markers and attach their tags without blocking the UI?
Thanks in advance.
Here are some of my code:
LocationLoader class
(BinLocation is my Location class, each object has boolean variables (marker tags) and LatLng)
public class LocationLoader extends AsyncTaskLoader> {
private String TAG = LocationLoader.class.getName();
String[] fileNameArray;
//ArrayLists
private ArrayList<BinLocation> mBinLocationArrayList = new ArrayList<>();
public LocationLoader(Context context, String... fileNames){
super(context);
//get the file names that was passed in
fileNameArray = fileNames;
}//LocationLoader
#Override
protected void onStartLoading() {
Log.v(TAG, "onStartLoading called");
forceLoad();
}//onStartLoading
#Override
public ArrayList<BinLocation> loadInBackground() {
Log.v(TAG, "loadInBackground called");
String path = "/storage/emulated/0/";
File file;
String output = "";
//Read data from file
for (int i = 0; i < fileNameArray.length; i++) {
file = new File(path + fileNameArray[i]);
try (Scanner scanner = new Scanner(file)) {
//first line of the text, containing the location and version
output = scanner.nextLine();
String prefix = (output.split(":"))[0];
String line;
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String inputArray[] = line.split(",");
BinLocation binLocation = new BinLocation(
prefix + "-" + inputArray[0],
Double.parseDouble(inputArray[1]),
Double.parseDouble(inputArray[2]),
Integer.parseInt(inputArray[3].trim()),
Integer.parseInt(inputArray[4].trim()),
Integer.parseInt(inputArray[5].trim()),
Integer.parseInt(inputArray[6].trim()));
mBinLocationArrayList.add(binLocation);
}//while
} catch (Exception e) {
Log.e(TAG, "File read error: ", e);
}
}//for
Log.v(TAG, "readLocation finished");
Log.v(TAG, "ArrayList size: " + mBinLocationArrayList.size());
return mBinLocationArrayList;
}//loadInBackground
}//LocationLoader class
Here is my MarkerLoader class (I have tried this and got the doInBackground() error). Also there is no code right now here for adding the data to the marker but it foes in the loop right after it has been added to the map.
public class MarkerLoader extends AsyncTaskLoader<ArrayList<Marker>> {
private GoogleMap map;
private ArrayList<Marker> mMarkerArrayList = new ArrayList<>();
private ArrayList<MyLocation> mBinLocationArrayList = new ArrayList<>();
public MarkerLoader (Context context, GoogleMap map, ArrayList<BinLocation> binLocationArrayList) {
super(context);
this.map = map;
this.mBinLocationArrayList = binLocationArrayList;
}//MarkerLoader
#Override
protected void onStartLoading() {
Log.v(TAG, "onStartLoading called");
forceLoad();
}//onStartLoading
#Override
public ArrayList<Marker> loadInBackground() {
Log.v(TAG, "loadInBackground called");
Marker marker;
for (BinLocation binLocation : mMyLocationArrayList) {
marker = map.addMarker(new MarkerOptions()
.position(binLocation.getPosition()));
mMarkerArrayList.add(marker);
}
Log.v(TAG, "loadInBackground finished, with: " + mMarkerArrayList.size());
return mMarkerArrayList;
}
}
This is the helper function(populateMap()) in the main Activity that makes the markers and save them in an ArrayList
private void populateMap() {
if (!checkMapReady() || !mMapIsEmpty) {
return;
}//if Map Not ready
//Initialize ArrayList
mMarkerArrayList = new ArrayList<>();
/**
* This part uses the loop to go through each MyLocation object in the ArrayList, extract
* all the data, and set the markers
*/
//Check to make sure the BinLocation ArrayList is not empty otherwise we will crash
if (mBinLocationArrayList.isEmpty()) {
Log.w(TAG, "populateMap() terminated, mBinLocationArrayList empty");
return;
}//if BinLocation empty
//Safety check to clear the map before populating it
mMap.clear();
//create a markerMyLocation object
Marker mMaker;
//This goes through the ArrayList for every MyLocation object and sets up the markerMyLocation
for (BinLocation binLocation : mBinLocationArrayList) {
//get boolean values
boolean[] booleanValues = {binLocation.getGarbage(), binLocation.getContainer(),
binLocation.getPaper(), binLocation.getCompost()};
//Set different icon
switch (markerIconPreference) {
case "customIcon":
//custom icon
//Decide what icon to use
if (booleanValues[0] && !booleanValues[1] && !booleanValues[2] && !booleanValues[3]) {
//Make a new MarkerOptions object to add the data
//garbage markers
mMaker = mMap.addMarker(new MarkerOptions()
.title(binLocation.getId())
.position(binLocation.getPosition())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_garbage))
.visible(garbageVisible));
} else {
//Make a new MarkerOptions object to add the data
//recycling markers
mMaker = mMap.addMarker(new MarkerOptions()
.title(binLocation.getId())
.position(binLocation.getPosition())
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_recycling))
.visible(recyclingVisible));
}
//Add our boolean array as an object to our markerMyLocation
mMaker.setTag(booleanValues);
//Add the markerMyLocation to the ArrayList
mMarkerArrayList.add(mMaker);
break;
case "coloredTeardrop":
//teardrop icon
//Decide what icon to use
if (booleanValues[0] && !booleanValues[1] && !booleanValues[2] && !booleanValues[3]) {
//Make a new MarkerOptions object to add the data
//garbage markers
mMaker = mMap.addMarker(new MarkerOptions()
.title(binLocation.getId())
.position(binLocation.getPosition())
.visible(garbageVisible));
} else {
//Make a new MarkerOptions object to add the data
//recycling markers
mMaker = mMap.addMarker(new MarkerOptions()
.title(binLocation.getId())
.position(binLocation.getPosition())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
.visible(recyclingVisible));
}
//Add our boolean array as an object to our markerMyLocation
mMaker.setTag(booleanValues);
//Add the markerMyLocation to the ArrayList
mMarkerArrayList.add(mMaker);
break;
}//switch
}//for
//disable the progress bar
mProgressBar.setVisibility(View.GONE);
//De-activate the CountDown timer since the map is ready
mCountDownTimer.cancel();
//set the boolean to false
mMapIsEmpty = false;
Log.v(TAG, "populateMap finished. Markers: " + mMarkerArrayList.size());
}//populateMap
Here is the onMapReady function
public void onMapReady(GoogleMap map) {
Log.v(TAG, "onMapReady called");
mMap = map;
//Setup on map loaded
mMap.setOnMapLoadedCallback(this);
//Check to see if the map is empty and the location array list is not empty and then call populateMap
if (mMapIsEmpty && !mBinLocationArrayList.isEmpty()) {
populateMap();
}//if map empty
//set bounds
mMap.setLatLngBoundsForCameraTarget(GREATER_VANCOUVER_BOUND);
//Set min zoom level to match the bound
mMap.setMinZoomPreference(10.0f);
//disable map toolbar
UiSettings mUiSettings = mMap.getUiSettings();
mUiSettings.setMapToolbarEnabled(false);
//Set listeners
mMap.setOnMarkerClickListener(this);
mMap.setOnInfoWindowCloseListener(this);
mMap.setOnInfoWindowClickListener(this);
// Setting our custom info window, passing out helper method
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
//Here we check for permission and setup the map accordingly
if (!checkLocationPermission()) {
//Permission is not granted, log, and use the default location
Log.v(TAG, "No location permission");
//setup default map
defaultMapSetup();
} else {
Log.v(TAG, "Location permission granted");
//Enable my location and initialize the map there
mMap.setMyLocationEnabled(true);
//Setup the map
locationMapSetup();
}//if -permission
}//onMapReady
try to Create your markers in another thread like this
YourActivity.this.runOnUiThread(new Runnable(){
public void run(){
//paste your code here.
});
Related
I have tried many of the solutions that abound here in the forum of the operation of onmarkerclick () but none have worked.
I am working with an app that uses the google maps api and we want to program a route tracer.
The operation that I am trying to achieve now is that by clicking on a marker you can trace the path to it, the problem is that the onmarkerclick method is not working or returning anything.
I will add the 2 parts of the code that I consider important to be able to find the solution to the problem:
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapClickListener(this);
mMap.setOnMarkerClickListener(this);
mMap.setOnInfoWindowClickListener(this);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
// Add layer
try {
layer = new KmlLayer(mMap, R.raw.kmltest, getApplicationContext());
layer.addLayerToMap();
// Set a listener for geometry clicked events.
layer.setOnFeatureClickListener(new KmlLayer.OnFeatureClickListener() {
#Override
public void onFeatureClick(Feature feature) {
Log.i("KML", "Feature clicked: " + feature.getProperty("CUA_DESCRI"));
}
});
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// end of layer add
}
public boolean onMarkerClick(Marker marker) {
Log.d("Comprobar markerclick", "onMarkerClick !!!!!!!!!!!!!!!!!! ");
btnTrazarRuta.hide();
//El destino que buscaremos al dar click
destinoRutaUnica = marker.getPosition().latitude + "," + marker.getPosition().longitude;
return false;
}
The onmarkerclick method should hide a button and get the position of the marker, but before that I put a logd to be able to see if it was at least entering the method, but no. It shows absolutely nothing.
Fron anyone who got the same problem.
in my case it was the line:
layer = new KmlLayer(mMap, R.raw.kmltest, getApplicationContext());
apparently, onmarkerclick() and at the same time oninfowindowsclick() stop working when working with a KML layer.
I don't know exactly why.
Once you add a KML layer, it will handle the clicks. You need to instruct the KML layer to delegate the clicks to e.g. your markers or polylines.
here's how to do it with markers (same principle for polylines etc):
MarkerManager markerManager = new MarkerManager(map);
MarkerManager.Collection markerCollection = markerManager.newCollection();
... where map is GoogleMap.
Now when adding a marker to the map
instead of doing:
map.addMarker(markerOptions);
map.setOnMarkerClickListener(listener);
do:
markerCollection.addMarker(markerOptions)
markerCollection.setOnMarkerClickListener(listener);
And now the final hint:
When adding a KML object to the map, pass in the markerManager (and polylineManager etc):
KmlLayer kmlLayer = new KmlLayer(map, R.raw.kmltest, ctxt, markerManager, polygonManager, polylineManager, groundOverlayManager, (cache));
In case you only use markers, it would simply be:
KmlLayer kmlLayer = new KmlLayer(map, R.raw.kmltest, ctxt, markerManager, null, null, null, null);
... and watch ALL your click listeners work
I am using the HERE Maps Lite SDK for Android as a library in my project.
I want to show MapView, and add overlays of all shelters I have in my database, in their specific coordinates.
The map works well, but the shown coordinates are not accurate. I tried to geocode the coordinates in lat-long website, and they are correct, but in the map they are shown right to their real location.
My code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shelters_map);
mapView = findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
ActivityCompat.requestPermissions(SheltersMapActivity.this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION}, 123);
if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
Toast.makeText(getApplicationContext(), "אנא אפשר גישה לשירותי מיקום", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this,
new String[]{ACCESS_FINE_LOCATION},
1);
} else // premission is granted
{
GPStracker g = new GPStracker(getApplicationContext());
userLocation = g.getLocation();
}
loadMapScene();
addSheltersOverlay();
// loadMapScene();
}
private void loadMapScene() {
// Load a scene from the SDK to render the map with a map style.
mapView.getMapScene().loadScene(MapStyle.NORMAL_DAY, new MapScene.LoadSceneCallback() {
#Override
public void onLoadScene(#Nullable MapScene.ErrorCode errorCode) {
if (errorCode == null) {
mapView.getCamera().setTarget(new GeoCoordinates(userLocation.getLatitude(),
userLocation.getLongitude()));
mapView.getCamera().setZoomLevel(15);
} else {
Log.d("data1", "onLoadScene failed: " + errorCode.toString());
}
}
});
}
private void addSheltersOverlay() {
db = new DatabaseHandler(this);
ArrayList<Shelter> places = this.db.getAllPlaces();
Shelter userLocationPlace = new Shelter("המיקום שלך", "", userLocation, null, 0, "");
places.add(userLocationPlace);
int size = places.size();
for(int i = 0; i < size; i++) {
TextView textView = new TextView(this);
textView.setTextColor(Color.parseColor("#FFFFFF"));
textView.setText(places.get(i).getName());
LinearLayout linearLayout = new LinearLayout(this);
if (places.get(i) instanceof Basement)
linearLayout.setBackgroundColor(Color.BLACK);
else if (places.get(i) instanceof Stairs)
linearLayout.setBackgroundColor(Color.GREEN);
else
linearLayout.setBackgroundColor(Color.BLUE);
linearLayout.setPadding(10, 10, 10, 10);
linearLayout.addView(textView);
GeoCoordinates geoCoordinates = new GeoCoordinates(places.get(i).getLocation().getLatitude(),
places.get(i).getLocation().getLongitude());
MapOverlay<LinearLayout> mapOverlay = new MapOverlay<>(linearLayout, geoCoordinates);
mapView.addMapOverlay(mapOverlay);
}
}
The shown map:
.
I can see the streets names in the shown map itself, and I see that it is not the accurate point.
Anybody help?
From the code it looks correct, but I cannot see the location vs. the expected location. By default, MapOverlays are drawn centered on the coordinates. You can set an anchor point to move the overlay in relation to the coordinates. This could help if there is always an offset between the coordinates in your database and the location on the map.
Maybe, can you try to render a small MapCircle item onto the map at the expected location? Then you can more easily see where that location lies on the map. You can compare the results with https://www.latlong.net/.
Hello everyone I am new dealing with google map API , and I have a list of LatLng object that added marker on map .
for (LatLng location : camerasLocations) {
googleMap.addMarker(new MarkerOptions()
.position(location).icon(icon)
.title(cameraList.get(j).getName()));
}
I want to know the position of the marker on that array when I click on the marker with :
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
showDialog(getActivity(), "");
return false;
}
});
any help please ...
First you need to set position as tag on marker while adding marker in google map
for(int i = 0, i < camerasLocations.size(), i++){
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(location).icon(icon)
.title(cameraList.get(j).getName()))
.setTag(i);
}
And then you can obtain this marker position in the onclick method using getTag() method :
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(this, "Marker position >> " + marker.getTag(), Toast.LENGTH_SHORT).show();
return false;
}
});
As far as I know, they are not positioned in that way. You would have to handle it yourself. If you are sure you just want to get the index based on the order of creation, you can do sth like that:
Create private field with Map, for storing that information
//class field
private Map<Marker, Integer> markersOrderNumbers = new HashMap<>();
Afterward, populate it
//Your method
int markerIndex = 0;
for (LatLng location : camerasLocations) {
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(location).icon(icon)
.title(cameraList.get(j).getName()));
markersOrderNumbers.put(marker,markerIndex);
markerIndex++;
}
And then you can obtain this index number in the onclick method
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Integer index = markersOrderNumbers.get(marker);
//Do whatever you want to
showDialog(getActivity(), "");
return false;
}
});
I might add that if you are not certainly focused on the index itself but rather on some information that you get using that Id, you can use provided method to map marker with needed information at the first place like:
Map<Marker, Whatever> ...
This application purposed to get the distance from 2 points of coordinate. The ways is just to click in the map of the position place that you want to count the distance. But there's problem in the point's start, where the application cannot changes the position place.
this is my code:
public class MapsActivity extends FragmentActivity {
// the Google Map object
private GoogleMap mMap;
//ArrayList markerPoints;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// we set the layout for the Activity
setContentView(R.layout.activity_maps);
// the geocoder is instantiated for the first time
geocoder=new Geocoder(this);
// if there isn't a map, it will be created
setUpMapIfNeeded();
}
// LatLng objects store a pair of terrestrial coordinates (latitude and longitude)
private static LatLng STARTING_MARKER_POSITION =new LatLng(3.099465, 101.717111);
/* distanceFrom indicates the starting point to calculate the distance from.
It's initialized with STARTING_MARKER_POSITION
*/
private LatLng distanceFrom= STARTING_MARKER_POSITION;
// line will be drawn at the click event
private Polyline line=null;
// A Geocoder can transform a pair of latitude/longitude into a street address and viceversa.
// We'll use it in the listener
private static Geocoder geocoder=null;
private GoogleMap.OnMapClickListener clickListener=new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(final LatLng pos) {
// this method is called when the user taps the map
// if a line already appears, it's removed
if (line!=null)
line.remove();
// a new line is created
line = mMap.addPolyline(new PolylineOptions()
.add(distanceFrom, pos)
.width(9) // width of the line
.color(Color.BLUE)); // line color
// call the converter object for geocoding invocation and distance calculation
new AddressConverter().execute(distanceFrom, pos);
}
};
#Override
protected void onResume() {
super.onResume();
// the availability of the GoogleMap will be checked before the Activity starts interacting with the user
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// the map is created only it has not been initialized
if (mMap == null) {
// the map is located in the layout
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// if a map exists, we proceed with initialization
if (mMap != null) {
setUpMap();
}
}
}
// Now it's time to configure the map. We can add markers, shapes, event handlers and so on
private void setUpMap() {
// the camera will be positioned according to the new coordinates
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(STARTING_MARKER_POSITION, 14));
// we choose the type of the map: Satellite in this case
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// markerOptions describes the marker we want to place
MarkerOptions markerOptions=new MarkerOptions()
.position(STARTING_MARKER_POSITION)
.draggable(true);
// the marker has to be draggable as we'll move it
// the marker is rendered on the map
mMap.addMarker(markerOptions);
// we define the object to invoke when the marker is dragged
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener()
{
#Override
public void onMarkerDragStart(Marker arg0)
{
// this method is called when the drag starts
// the operation we need is the cancellation of a preexisting line
if (line!=null)
line.remove();
}
#Override
public void onMarkerDragEnd(final Marker pos)
{
// we get the final position of the marker
distanceFrom=pos.getPosition();
}
#Override
public void onMarkerDrag(Marker arg0)
{
// operations performed during the movement. Nothing to do
}
});
// the callback to invoke is set
mMap.setOnMapClickListener(clickListener);
}
// we want to know which address corresponds to this location
// we use AsyncTask to perform slower operations on a separate thread
private class AddressConverter extends AsyncTask<LatLng,Void,String>
{
// The ProgressDialog window we'll show during the calculation
private ProgressDialog progress=null;
// this method is called before the background job starts. It works on the main thread
#Override
protected void onPreExecute() {
// ProgressDialog is shown
progress= ProgressDialog.show(MapsActivity.this,"Distance calculator","We are calcultating the distance...", true,false);
}
// this method works on a separate thread
// it performs geocoding operations to retrieve the address of the points and calculates the distance in meters between them
#Override
protected String doInBackground(LatLng... params) {
float[] distance=new float[1];
try {
// the Location class contains what we need to calculate distances
Location.distanceBetween(params[0].latitude,params[0].longitude,params[1].latitude,params[1].longitude,distance);
// geocoding operations
List<Address> fromResult=geocoder.getFromLocation(params[0].latitude,params[0].longitude,1);
List<Address> toResult=geocoder.getFromLocation(params[1].latitude,params[1].longitude,1);
// the message informs the user about the distance from the marker to the point selected with the click
// if we have got both the addresses, we use them to compose the message, otherwise we show only the distance
if (fromResult.size()>0 && toResult.size()>0)
{
// ((TextView) findViewById(R.id.tvDuration)).setText(route.duration.text);
return "The distance between " + getAddressDescription(fromResult.get(0)) + " and " + getAddressDescription(toResult.get(0)) + " is " + Math.round(distance[0]) + " meters";
}
else
return "The distance is " + Math.round(distance[0]) + " meters";
}
catch (IOException e) {
return "The distance is " + Math.round(distance[0]) + " meters";
}
}
#Override
protected void onPostExecute(String message)
{
if (progress!=null)
progress.dismiss();
// The builder of the window is instantiated
AlertDialog.Builder builder=new AlertDialog.Builder(MapsActivity.this);
builder.setTitle("Distance");
builder.setMessage(message);
// the Alert dialog appears
builder.show();
}
}
// this method only formats the message with addresses
private String getAddressDescription(Address a)
{
String city=a.getLocality();
String address=a.getAddressLine(0);
return "'"+address+"' ("+city+")";
}}
Use distanceBetween() method, It will give you exact distance in meters.
Location.distanceBetween(double startLatitude, double startLongitude,
double endLatitude, double endLongitude, float[] results);
What I need to do, is when the "user" marker gets into (let's say 50 meters radius) the radius of one of the place of interest marker popus an dialog ( showplaceDialog() ).
How can I do it? I have simply no clue of how to do it...
This is how I put the "user" marker, which moves as location changes.
#Override
public void onLocationChanged(Location location) {
Log.d("Location", "onLocationChanged with location " + location.toString());
if(overlayMarkerYou == null) {
overlayMarkerYou = new MyOverlay(getResources().getDrawable(R.drawable.marker_you),mapView);
mapView.getOverlays().add(overlayMarkerYou);
}else{
mapView.getOverlays().remove(overlayMarkerYou);
mapView.invalidate();
overlayMarkerYou = new MyOverlay(getResources().getDrawable(R.drawable.marker_you),mapView);
mapView.getOverlays().add(overlayMarkerYou);
}
if (location != null) {
mapView.invalidate();
GeoPoint gpt = new GeoPoint(microdegrees(location.getLatitude()),microdegrees(location.getLongitude()));
mapController.setCenter(gpt);
overlayMarkerYou.addPoint(gpt, getString(R.string.markerYou), getString(R.string.markerYouDescription));
}
}
And this is how I put multiple markers for places of interest
public void putPlacesOfInterest(){
this.dh = new DataHelper(ShowMap.this);
List<Pontos> list = this.dh.selectAll();
for(Pontos p : list){
markerPlaces.add(new OverlayItem(p.getName().toString(), Long.toString(p.getId()), new GeoPoint(p.getLat(), p.getLng())));
}
mMyLocationOverlay = new ItemizedIconOverlay<OverlayItem>(markerPlaces, new OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemLongPress(int index, OverlayItem item) {
Toast.makeText(ShowMap.this, "" + item.mTitle, Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onItemSingleTapUp(int index, OverlayItem item) {
showplaceDialog(Integer.parseInt(item.mDescription),item.mTitle);
return true;
}
}, mResourceProxy);
mapView.getOverlays().add(mMyLocationOverlay);
mapView.invalidate();
}
I would recommend looking into the addProximityAlert() function available in the LocationManager class. I am not sure how many listeners you are able to register though.
Your other choice is to do a check on every location update. When your app gets a onLocationChanged() callback you can loop through your places of interest, and check to see if they are within 50 meters of the current location. To make this even easier, you can use the distanceTo() method in the Location class.