Drag polyline along with marker in openstreetmap? - android

I'm currently developing an android application that would allow users to draw Polylines with Markers or point in the polyline when user long press on points how to dragline with points move also line would be move on the map. how do I achieve this I drag marker but cant move marker
public class MainMapActivity extends AppCompatActivity {
GeoPoint startPoint;
MapView map;
Road road;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_map);
map = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
GpsTracking gps=new GpsTracking(MainMapActivity.this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
startPoint = new GeoPoint(latitude, longitude);
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
} else {
gps.showSettingsAlert();
}
// GeoPoint startPoint = new GeoPoint(48.13, -1.63);
IMapController mapController = map.getController();
mapController.setZoom(17);
mapController.setCenter(startPoint);
Marker startMarker = new Marker(map);
startMarker.setPosition(startPoint);
startMarker.setDraggable(true);
startMarker.setOnMarkerDragListener(new OnMarkerDragListenerDrawer());
startMarker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
map.getOverlays().add(startMarker);
//Set-up your start and end points:
RoadManager roadManager = new OSRMRoadManager(this);
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
waypoints.add(startPoint);
GeoPoint endPoint = new GeoPoint(31.382108, 74.260107);
waypoints.add(endPoint);
// retreive the road between those points:
Road road = roadManager.getRoad(waypoints);
// build a Polyline with the route shape:
Polyline polyline=new Polyline();
polyline.setOnClickListener(new Polyline.OnClickListener() {
#Override
public boolean onClick(Polyline polyline, MapView mapView, GeoPoint eventPos) {
return false;
}
});
Polyline roadOverlay = RoadManager.buildRoadOverlay(road);
//Polyline to the overlays of your map:
map.getOverlays().add(roadOverlay);
//Refresh the map!
map.invalidate();
//3. Showing the Route steps on the map
FolderOverlay roadMarkers = new FolderOverlay();
map.getOverlays().add(roadMarkers);
Drawable nodeIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.marker_node, null);
for (int i = 0; i < road.mNodes.size(); i++) {
RoadNode node = road.mNodes.get(i);
Marker nodeMarker = new Marker(map);
nodeMarker.setDraggable(true);
nodeMarker.setOnMarkerDragListener(new OnMarkerDragListenerDrawer());
nodeMarker.setPosition(node.mLocation);
nodeMarker.setIcon(nodeIcon);
//4. Filling the bubbles
nodeMarker.setTitle("Step " + i);
nodeMarker.setSnippet(node.mInstructions);
nodeMarker.setSubDescription(Road.getLengthDurationText(this, node.mLength, node.mDuration));
Drawable iconContinue = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_continue, null);
nodeMarker.setImage(iconContinue);
//4. end
roadMarkers.add(nodeMarker);
}
}
class OnMarkerDragListenerDrawer implements Marker.OnMarkerDragListener {
ArrayList<GeoPoint> mTrace;
Polyline mPolyline;
OnMarkerDragListenerDrawer() {
mTrace = new ArrayList<GeoPoint>(100);
mPolyline = new Polyline();
mPolyline.setColor(0xAA0000FF);
mPolyline.setWidth(2.0f);
mPolyline.setGeodesic(true);
map.getOverlays().add(mPolyline);
}
#Override public void onMarkerDrag(Marker marker) {
//mTrace.add(marker.getPosition());
}
#Override public void onMarkerDragEnd(Marker marker) {
mTrace.add(marker.getPosition());
mPolyline.setPoints(mTrace);
map.invalidate();
}
#Override public void onMarkerDragStart(Marker marker) {
//mTrace.add(marker.getPosition());
}
}
}
Does anyone know how I can achieve this? above is a snippet of my codes. Thanks!

Related

Custom MyPositionIcon On Tap Creates A Copy Of Custom MyPositionMarker

I am trying to replace mMpap.SetMyPosition(true); function with my own. I had some success on it and when my custom image for "My Position Icon" is tapped, it moves camera to current location with my custom marker.
Everything works fine on it except whenever "My Position Icon" is tapped, it leaves a copy of marker to that position and moves to current location with a new marker.
I am fairly new to Android Development and looking for some help.
My code inside onCreate(Bundle savedInstanceState) is:
ImageView img = (ImageView) findViewById(R.id.myPostionButton);
img.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getTheLocation();
}
});
And getTheLocation() is:
if (location != null) {
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
final Marker marker = mMap.addMarker(
new MarkerOptions()
.position(new LatLng(latitude, longitude))
.draggable(true)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker)));
mMap.setTrafficEnabled(true);
mMap.setMinZoomPreference(10.0f);
mMap.setMaxZoomPreference(20.0f);
//mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16.0f),4000 , null);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16.0f));
mMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
LatLng centerOfMap = mMap.getCameraPosition().target;
marker.setPosition(centerOfMap);
}
});
mMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
LatLng centerOfMap = mMap.getCameraPosition().target;
marker.setPosition(centerOfMap);
double latitude = centerOfMap.latitude;
double longitude = centerOfMap.longitude;
Geocoder geocoder = new Geocoder(getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
String str = addressList.get(0).getAddressLine(0) + ", ";
str += addressList.get(0).getSubLocality() + ", ";
str += addressList.get(0).getLocality() + ", ";
str += addressList.get(0).getCountryCode();
mFromAddress.setText(str);
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
And onMapReady(GoogleMap googleMap) is:
mMap = googleMap;
getTheLocation();
Please Help.
You can try any one of the following based on your situation:
1. If you have only one marker in map, before adding the new marker, clear the map using mMap.clear();
2. If you have multiple markers then you have to keep your current marker object as member variable mMarker. Then just before adding the new marker you can use mMarker.remove();.

I am having trouble making this work

First of all my marker won't show up. But if it did then how would I keep it moving? I'm tracking a satellite. Iv'e done research but all i've found were folks using JSON arrays on their maps. However I have an object that needs to update across the map
I'm using a json OBJECT. Please don't give me links unless you are absolutely sure you know it can apply to my situation. Can anyone help?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private LocationManager locationManager;
private GoogleMap mMap;
JSONParser jsonparser = new JSONParser();
private CameraPosition cameraPosition;
private GoogleMap googleMap;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(map);
List<MarkerOptions> markerOptions = new ArrayList<>();
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(200, 50, conf);
Canvas canvas = new Canvas(bmp);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
public void animateMarker(final Marker marker, final LatLng toPosition,
final boolean hideMarker) {
MapFragment mapFragment = new MapFragment();
mapFragment.getMapAsync(this);
jobj = jsonparser.makeHttpRequest("http://api.wheretheiss.at/v1/satellites/25544");
try {
String lati = "latitude : " + jobj.getDouble("latitude");
} catch (JSONException e) {
e.printStackTrace();
}
try {
String longit = "longitude : " + jobj.getDouble("longitude");
} catch (JSONException e) {
e.printStackTrace();
}
final Handler handler = new Handler() {
};
final long start = SystemClock.uptimeMillis();
Projection proj = mMap.getProjection();
Point startPoint = proj.toScreenLocation(marker.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 500;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
jobj = jsonparser.makeHttpRequest("http://api.wheretheiss.at/v1/satellites/25544");
try {
Double longit = jobj.getDouble("longitude");
Double lat = jobj.getDouble("latitude");
marker.setTitle("ISS");
marker.showInfoWindow();
marker.setPosition(new LatLng(lat, longit));
CameraUpdate center= CameraUpdateFactory.newLatLng(new LatLng(lat, longit));
CameraUpdate zoom = CameraUpdateFactory.newLatLngZoom(new LatLng(lat, longit),3);
googleMap.animateCamera(center);
googleMap.animateCamera(zoom);
} catch (JSONException e) {
e.printStackTrace();
}
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarker) {
marker.setVisible(false);
} else {
marker.setVisible(true);
}
}
}
});
}
public void onLocationChanged(Location location) {
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 17));
}
}
First of all, it seems like you forgot add your marker to map. I didn't see this code in your activity.
Secondly, there is an example of working method to move markers on the google map, developed by guys from google.
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
static void animateMarkerToICS(Marker marker, LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
TypeEvaluator<LatLng> typeEvaluator = new TypeEvaluator<LatLng>() {
#Override
public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
return latLngInterpolator.interpolate(fraction, startValue, endValue);
}
};
Property<Marker, LatLng> property = Property.of(Marker.class, LatLng.class, "position");
ObjectAnimator animator = ObjectAnimator.ofObject(marker, property, typeEvaluator, finalPosition);
animator.setDuration(3000);
animator.start();
}
And interpolator:
public interface LatLngInterpolator {
public LatLng interpolate(float fraction, LatLng a, LatLng b);
public class Linear implements LatLngInterpolator {
#Override
public LatLng interpolate(float fraction, LatLng a, LatLng b) {
double lat = (b.latitude - a.latitude) * fraction + a.latitude;
double lng = (b.longitude - a.longitude) * fraction + a.longitude;
return new LatLng(lat, lng);
}
}
}
More information you can find there

How to join multiple markers on the map with arrow headed poly-line to show directions of travelling?

I am a newbie to the android and currently working on the Google-map API.
I am able to plot multiple markers on the map but want to join multiple markers with poly line.I have referred this for the directions concern but it is for two points only.
Below is the code for the Activity:
public class MainActivity extends AppCompatActivity {
// Google Map
private GoogleMap googleMap;
// latitude and longitude
double latitude;
double longitude;
String newtime;
ArrayList<LatLng> points;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
points = new ArrayList<LatLng>();
points.add(new LatLng(21.114369, 79.049423));
points.add(new LatLng(21.113913, 79.049203));
points.add(new LatLng(21.113478, 79.048736));
points.add(new LatLng(21.113002, 79.048592));
points.add(new LatLng(21.112857, 79.047315));
points.add(new LatLng(21.112997, 79.046741));
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.setMyLocationEnabled(true);
SimpleDateFormat sdfDateTime = new SimpleDateFormat("dd-MM-yy HH:mm:ss", Locale.US);
newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));
// googleMap.addMarker(marker);
drawMarker(points);
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
}
private void drawMarker(ArrayList<LatLng> l) {
// Creating an instance of MarkerOptions
for (int i = 0; i < l.size(); i++) {
latitude = l.get(i).latitude;
longitude = l.get(i).longitude;
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Bus")
.snippet(newtime);
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// Adding marker on the Google Map
googleMap.addMarker(marker);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(l.get(0).latitude, l.get(0).longitude)).zoom(18).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Please help/guide me to achieve the task.
~Thanks.
Modify your drawMarker() to the following:-
private void drawMarker(ArrayList<LatLng> l) {
// Creating an instance of MarkerOptions
PolylineOptions options = new PolylineOptions();
options.color(Color.RED);
for (int i = 0; i < l.size(); i++) {
options.add(l.get(i));
MarkerOptions marker = new MarkerOptions().position(l.get(i)).title("Bus")
.snippet(newtime);
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// Adding marker on the Google Map
googleMap.addMarker(marker);
}
googleMap.addPolyline(options);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(l.get(0).latitude, l.get(0).longitude)).zoom(18).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
Here it will add lines with red color, to change colors as your wish just modify the options.color().

Route directions for driving mode

I'm trying to implement a route direction for the points I have on my map, for doing that I'm using Polyline, the problem is, I managed to connect 2 points of the map, but I have an array of LatLng with 8 points, how would I connect all the points?:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
ArrayList<LatLng> coordList = new ArrayList<LatLng>();
ArrayList<String> nomes = new ArrayList<String>();
try {
Bundle parametros = getIntent().getExtras();
rm_IdViagem = parametros.getString("id_viagem");
Repositorio ca = new Repositorio(this);
mViagemModel = ca.getViagemPorId(Integer.valueOf(rm_IdViagem));
Repositorio cl = new Repositorio(this);
mClienteModel = cl.getClientesViagem(Integer.valueOf(rm_IdViagem));
if(mClienteModel != null) {
for (int i = 0; i < mClienteModel.size(); i++) {
Repositorio mRepositorio = new Repositorio(this);
mEnderecoModel = mRepositorio.getListaEnderecosDoCliente(Integer.valueOf(mClienteModel.get(i).getClientes_id()));
for (int j = 0; j < mEnderecoModel.size(); j++) {
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
final float latitude = Float.parseFloat(mEnderecoModel.get(j).getLatitude());
final float longitude = Float.parseFloat(mEnderecoModel.get(j).getLongitude());
nomes.add(mClienteModel.get(i).getNome());
coordList.add(new LatLng(latitude, longitude));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 5));
mClusterManager = new ClusterManager<MyItem>(MapaViagem.this, googleMap);
mClusterManager.setRenderer(new MyClusterRenderer(MapaViagem.this, googleMap, mClusterManager));
googleMap.setOnCameraChangeListener(mClusterManager);
googleMap.setOnMarkerClickListener(mClusterManager);
//mClusterManager.setAlgorithm(new GridBasedAlgorithm<MyItem>());
addItems(coordList, nomes);
mClusterManager.cluster();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyClusterRenderer extends DefaultClusterRenderer<MyItem> {
public MyClusterRenderer(Context context, GoogleMap map,
ClusterManager<MyItem> clusterManager) {
super(context, map, clusterManager);
}
#Override
protected void onBeforeClusterItemRendered(MyItem item, MarkerOptions markerOptions) {
super.onBeforeClusterItemRendered(item, markerOptions);
markerOptions.title(String.valueOf(item.getName()));
}
#Override
protected void onClusterItemRendered(MyItem clusterItem, Marker marker) {
super.onClusterItemRendered(clusterItem, marker);
//here you have access to the marker itself
}
#Override
protected boolean shouldRenderAsCluster(Cluster<MyItem> cluster) {
return cluster.getSize() > 1;
}
}
Use this example. This will help you to find solution.
http://wptrafficanalyzer.in/blog/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/

Android map with different location with different marker image

I'm doing map application in android.For that,i need to show current location with one marker image.And when i type any address on top editText box,i need to show tht location with different marker image + i can change that second marker into tapped locations.For me,initially it shows current location with one marker well.But when i type.,while second marker has come.,that first marker(current location) will disapper.I want to have both two markers on view.How could i do that?
My code:
Handler h = new Handler() {
// Invoked by the method onTap()
// in the class CurrentLocationOverlay
#Override
public void handleMessage(Message msg) {
Bundle data = msg.getData();
// Getting the Latitude of the location
int latitude = data.getInt("latitude");
// Getting the Longitude of the location
int longitude = data.getInt("longitude");
// Show the location in the Google Map
showLocation(latitude, longitude);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting reference to map_view available in activity_main.xml
mapView = (MapView) findViewById(R.id.map_view);
// Getting reference to tv_location available in activity_main.xml
tvLocation = (TextView) findViewById(R.id.tv_location);
initLocationManager();
// Default Latitude
int latitude = 28426365;
// Default Longitude
int longitude = 77320393;
// Show the location in the Google Map
showLocation(latitude, longitude);
}
private void initLocationManager() {
mapView.setBuiltInZoomControls(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:" + longitude);
// Creating an instance of GeoPoint corresponding to latitude and
// longitude
GeoPoint point = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Getting MapController
MapController mapController = mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(point);
// Applying a zoom
mapController.setZoom(15);
// Redraw the map
mapView.invalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
// Creating a drawable object to represent the image of mark in the map
Drawable drawable = this.getResources().getDrawable(
R.drawable.ic_launcher);
// Creating an instance of ItemizedOverlay to mark the current location
// in the map
CurrentLocationOverlay currentLocationOverlay = new CurrentLocationOverlay(
drawable);
// Creating an item to represent a mark in the overlay
OverlayItem currentLocation = new OverlayItem(point,
"Current Location", "Latitude : " + latitude + ", Longitude:"
+ longitude);
// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
private void showLocation(int latitude, int longitude) {
// Setting Latitude and Longitude in TextView
tvLocation.setText("Latitude:" + latitude / 1e6 + "," + "Longitude:"
+ longitude / 1e6);
// Setting Zoom Controls
mapView.setBuiltInZoomControls(true);
// Getting the MapController
MapController mapController = mapView.getController();
// Getting Overlays of the map
List<Overlay> overlays = mapView.getOverlays();
// Getting Drawable object corresponding to a resource image
Drawable drawable = getResources().getDrawable(R.drawable.marker);
// Creating an ItemizedOverlay
TouchedLocationOverlay locationOverlay = new TouchedLocationOverlay(
drawable, h);
// Getting the MapController
MapController mc = mapView.getController();
// Creating an instance of GeoPoint, to display in Google Map
GeoPoint p = new GeoPoint(latitude, longitude);
// Locating the point in the Google Map
mc.animateTo(p);
// Creating an OverlayItem to mark the point
OverlayItem overlayItem = new OverlayItem(p, "Item", "Item");
// Adding the OverlayItem in the LocationOverlay
locationOverlay.addOverlay(overlayItem);
// Clearing the overlays
overlays.clear();
// Adding locationOverlay to the overlay
overlays.add(locationOverlay);
// Redraws the map
mapView.invalidate();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return false;
}
private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}
private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
public SitesOverlay(Drawable marker, double lat, double lang) {
super(marker);
boundCenterBottom(marker);
items.add(new OverlayItem(getPoint(lat, lang), "", ""));
populate();
}
public SitesOverlay(Drawable marker, double[] latitude,
double[] longitude) {
super(marker);
// boundCenterBottom(marker);
for (int i = 0; i < latitude.length; i++) {
items.add(new OverlayItem(getPoint(latitude[i], longitude[i]),
"", ""));
}
populate();
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
protected boolean onTap(int i) {
/*
* Toast.makeText(LocationBasedServicesV2.this,
* items.get(i).getSnippet(), Toast.LENGTH_SHORT).show();
*/
return (true);
}
#Override
public int size() {
return (items.size());
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
TochedLocation:
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Handler handler;
public TouchedLocationOverlay(Drawable defaultMarker,Handler h) {
super(boundCenterBottom(defaultMarker));
// Handler object instantiated in the class MainActivity
this.handler = h;
}
// Executed, when populate() method is called
#Override
protected OverlayItem createItem(int arg0) {
return mOverlays.get(arg0);
}
#Override
public int size() {
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay){
mOverlays.add(overlay);
populate(); // Invokes the method createItem()
}
// This method is invoked, when user tap on the map
#Override
public boolean onTap(GeoPoint p, MapView map) {
List<Overlay> overlays = map.getOverlays();
// Creating a Message object to send to Handler
Message message = new Message();
// Creating a Bundle object ot set in Message object
Bundle data = new Bundle();
// Setting latitude in Bundle object
data.putInt("latitude", p.getLatitudeE6());
// Setting longitude in the Bundle object
data.putInt("longitude", p.getLongitudeE6());
// Setting the Bundle object in the Message object
message.setData(data);
// Sending Message object to handler
handler.sendMessage(message);
return super.onTap(p, map);
}
Thanks.
If you want the first overlay to be fixed which is your current location overlay, try with the below code and let me know.
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.remove(1); // Here instead of clearing all overlays, just clear the last added overlay.
listOfOverlays.add(mapOverlay); // Then you can add a new overlay.
mapView.invalidate();
or
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
if(listOfOverlays.size() > 1)
listOfOverlays.remove(listOfOverlays.size()-1); // Here instead of clearing all overlays, just clear the last added overlay.
listOfOverlays.add(mapOverlay); // Then you can add a new overlay.
mapView.invalidate();

Categories

Resources