How to update a position of my marker in Google Maps v2 in android without adding a new one?
Every time my location changes i have to update the position of the user in a Google Map, but it always creating a new point e the map, how to avoid this behaviour?
Here is how im updating
public void onLocationChanged(Location location) {
this.localizacao = location;
loc = location;
if (mAdapter.getCount() == 0){
getAdvsFromServer();
}
LatLng me = new LatLng(location.getLatitude(), location.getLongitude());
if (eu != null){
Log.d("marker_eu", "removed");
eu.remove();
}
eu = map.addMarker(new MarkerOptions().position(me).title("Eu"));
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_maps_indicator_current_position);
eu.setIcon(BitmapDescriptorFactory.fromBitmap(bm));
map.moveCamera(CameraUpdateFactory.newLatLng(me));
//map.moveCamera(CameraUpdateFactory.newLatLngZoom(me, 13));
}
UPDATE:
This way it always creating a new point too:
public void onLocationChanged(Location location) {
this.localizacao = location;
loc = location;
if (mAdapter.getCount() == 0){
getAdvsFromServer();
}
if (ac != null){
ac.setLayoutLocalizacaoVisible(View.GONE, View.VISIBLE);
}
LatLng me = new LatLng(location.getLatitude(), location.getLongitude());
// if (eu != null){
// Log.d("marker_eu", "removed");
// eu.remove();
// }
if (eu == null){
eu = map.addMarker(new MarkerOptions().position(me).title("Eu"));
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_maps_indicator_current_position);
eu.setIcon(BitmapDescriptorFactory.fromBitmap(bm));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(me, 13));
}else {
eu.setPosition(me);
map.moveCamera(CameraUpdateFactory.newLatLng(me));
}
You should not add new marker every time location change, instead you can directly set the new position into your existing marker.
For example:
marker.setPosition(new LatLng(lat, lng));
If your activity is creating a new Marker while running this method, than eu is somehow cleared or null going into the if statement. eu.setPosition(me);would not create another Marker but simply change the location of the marker without altering any other attributes.
If you are certain that the new marker is not created somewhere else in your code then check the state of eu before going into your if statement and find out why it is null at that point by backtracking. Check the position of the Marker to verify the location after the execution. Use the following and watch the logcat.
System.out.println(eu);
Related
I am trying to show my current location and store the location to Firebase and to place a marker on my current location.
i searched in google and even stack overflow t couldn't find anything related to my problem.
Also i read googles documentation on its maps sdk but didn't understand it.
LocationCallback mLocationCallback = new LocationCallback() { //NEW onLocation changed
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
mLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));//1-21
}
}
};
I expect to see a blue dot in my app but instead only see the map without any markers or even without my current location
public fun placeMarkerOnMap(location: LatLng, drawableResInt: Int? = null): Marker? {
val markerOptions = MarkerOptions().position(location)
val marker = googleMap?.addMarker(markerOptions)
if (drawableResInt != null) {
marker?.setIcon(BitmapDescriptorFactory.fromResource(drawableResInt))
}
return marker
}
Your code miss the part of adding marker.You can add marker to particular LatLng with/without custom image.Then only, move the camera.
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng))
Add Marker By doing following
double latitude = location.getLatitude();
double longitude = location.getLongitude());
LatLng latlng= new LatLng(latitude, longitude); ////your lat lng
mMap.addMarker(new MarkerOptions().position(latlng));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(posisiabsen, 65);
mMap.animateCamera(cameraUpdate);
I want to draw a path between two locations using on android google map.I have tired this code
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
if (cursor.moveToFirst()) {
do {
// latitude and longitude
double latitude = 0.00;
double longitude = 0.00;
Log.i("lat", cursor.getString(10));
Log.i("lat", cursor.getString(11));
try {
latitude = Double.parseDouble(cursor.getString(10));
} catch (Exception e) {
}
try {
longitude = Double.parseDouble(cursor.getString(11));
} catch (Exception e) {
}
if (latitude == 0.00 || longitude == 0.00) {
} else {
i++;
LatLng point = new LatLng(latitude,longitude);
options.add(point);
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title(cursor.getString(1));
}
}
while (cursor.moveToNext());
}
cursor.close();
googleMap.addPolyline(options);
but i got straight line.like this
I want to get paths on actual roads.
Thanks..!!
If you want to draw a polyline between 2 points and following road, you can try with the library Google-Directions-Android
You can add the library on gradle with compile 'com.github.jd-alexander:library:1.0.7'
You can use all your point (Latlng) and use them into the waypoint method.
Routing routing = new Routing.Builder()
.travelMode(/* Travel Mode */)
.withListener(/* Listener that delivers routing results.*/)
.waypoints(/*waypoints*/)
.build();
routing.execute();
What I want to do is just show driving routes to my Fragment Map when the Marker is Clicked.
This Tutorial is my source.
Right now the route only shows on OTHER app not in the myactivity layout. What I want to do is show the driving direction route in my fragment
Here is my MainActivity.Class
public class MainActivity extends ActionBarActivity implements GoogleMap.OnMarkerClickListener {
private LatLng Mark_Kantor_Gubernur = new LatLng(-0.9376155, 100.3600001);
private LatLng Mark_Bappeda_prov_Sumbar = new LatLng(-0.913884, 100.359176);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting Map From Google
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.setTrafficEnabled(true);
//Getting Location Based on Fused Location(GPS & Network)
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
//Handle map when opened on first time
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(13));
//Setting UP Marker
googleMap.addMarker(new MarkerOptions().position(Mark_Kantor_Gubernur)
.title("Kantor Gubernur")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_cp)));
googleMap.addMarker(new MarkerOptions().position(Mark_Bappeda_prov_Sumbar)
.title("Kantor Bappeda SUMBAR")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker_cp)));
TextView locationTV = (TextView) findViewById(R.id.tvLatLongLocation);
locationTV.setText("Latitude:" + latitude + ",Longitude:" + longitude);
//Setting onclick marker & Direction to Marker
googleMap.setOnMarkerClickListener(this);
}
#Override
public boolean onMarkerClick(Marker marker) {
//you can handle marker click from here
try {
StringBuilder stringBuilder = new StringBuilder();
String daddr = (String.valueOf(marker.getPosition().latitude)+","+String.valueOf(marker.getPosition().longitude));
stringBuilder.append("http://maps.google.com/maps?f=d&hl=en");
stringBuilder.append("&saddr="+String.valueOf(googleMap.getMyLocation().getLatitude())+","
+String.valueOf(googleMap.getMyLocation().getLongitude()));
stringBuilder.append("&daddr="+daddr);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(stringBuilder.toString()));
startActivity(intent);
}catch (Exception ee)
{
Toast.makeText(getApplicationContext(), "Lokasi Saat Ini Belum Didapatkan, Coba Nyalakan GPS, Keluar Ruangan dan Tunggu Beberapa Saat", Toast.LENGTH_LONG).show();
}
return false;
}
I have looked at J2ME/Android/BlackBerry - Driving directions, Route Between Two Locations, Draw Route On Google Map but this is showing just straight lines between the users location and destination, what I want is driving route.
If I add this polyline code:
Polyline polyline = googleMap.addPolyline(new PolylineOptions().add(new LatLng(googleMap.getMyLocation().getLatitude(), googleMap.getMyLocation().getLongitude()),new LatLng(marker.getPosition().latitude, marker.getPosition().longitude)).width(2).color(Color.RED).geodesic(true));
It just shows straight lines in a Google map fragment
Note: Please include comments and an explanation on answer code, I'm very new in android and still learning.
Selector elements should be placed in res\drawable. Right click on 'drawable', select 'new' then select 'Drawable resource file'. Name the file and you should be good to go.
I wanted to draw the path on Google Maps V2 when driving or walking, I couldn't find any online resource to help me with this problem.
I'm using the onLocationChanged listener method.
Thanks.
extend OnMyLocationChangeListener.
use this in the map-setup:
mMap.setOnMyLocationChangeListener(this);
override this:
#Override
public void onMyLocationChange(Location location) {
/* your code here */
}
for example the code could be something like this (NOT TESTED):
Location lastLocationloc=null;
#Override
public void onMyLocationChange(Location location) {
if(lastLocationloc == null)
lastLocationloc = location;
LatLng lastLatLng= locationToLatLng(lastLocationloc);
LatLng thisLatLng= locationToLatLng(location);
mMap.addPolyline(new PolylineOptions().add(lastLatLng).add(thisLatLng).width(3).color(Color.RED));
lastLocationloc = location;
}
the locationToLatLng could look something like this:
public static LatLng locationToLatLng(Location loc) {
if(loc != null)
return new LatLng(loc.getLatitude(), loc.getLongitude());
return null;
}
As been said here you need to use the Polyline object, you can collect all your path points (LatLng locations) and add all the road on the map using a loop:
Polyline newPolyline;
GoogleMap mMap = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
for(int i = 0 ; i < directionPoints.size() ; i++)
{
rectLine.add(directionPoints.get(i));
}
newPolyline = mMap.addPolyline(rectLine);
Or add a single line on each location update so place this code in the onLocationChanged
Polyline newPolyline;
PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
rectLine.add(point); //your received location.
newPolyline = mMap.addPolyline(rectLine);
To update the marker's location, just remove the old one and create a new marker (with the new coordinates) instead.
You can use Polyline from Google Maps. It takes locations and draws them on the map.
I have 2 instances of ItemizedOverlay in my application, one for CurrentLocation and another for something else. I have added these 2 overlays to a MapView.
I want to update the CurrentLocation overlay when the refresh button of the map is tipped. If I did, it means it shows the previous current location also, and the new one also. How do I remove the previous one?
But I need to show another overlay also.
I have subclassed the ItemizedOverlay:
MyItemizedOverlay currentOverlay = new MyItemizedOverlay(pushPinDrawable);
MyItemizedOverlay anotherOverlay = new MyItemizedOverlay(drawable);
The code for the refresh button:
if (currentGeo != null) {
mapView.getOverlays().remove(currentOverlay);
mapVite();
mapOverlays = mapView.getOverlays();
myLocationOverlay = new OverlayItem(currentGeo, "My Location", mapTime.format(new Date(myLocationTime)));
// (currentGeo is the updated current geo point.)
currentOverlay.addOverlay(myLocationOverlay);
mapOverlays.add(currentOverlay);
mapController.animateTo(currentGeo);
} else {
Toast.makeText(this, "Your Current Location is temporarily unavailable", Toast.LENGTH_LONG).show();
}
Any idea?
You should have some like this
public void onLocationChanged(Location location) {
if (mMyOverlay == null) {
mMyOverlay = new myOverlay(getResources().getDrawable(R.drawable.arrow), MyMap);
MyMap.getOverlays().add(mMyOverlay);
} else {
MyMap.getOverlays().remove(mMyOverlay);
MyMap.invalidate();
mMyOverlay = new myOverlay(getResources().getDrawable(R.drawable.arrow), MyMap);
MyMap.getOverlays().add(mMyOverlay);
}
if (location != null) {
MyMap.invalidate();
GeoPoint MyPos = new GeoPoint(microdegrees(location.getLatitude()), microdegrees(location.getLongitude()));
MyController.animateTo(MyPos);
mMyOverlay.addPoint(MyPos, "My position", "My position");
}
Berfore adding the CurrentOverlay in mapOverlays array, you can surely do something like this,
if(mapOverlays.contains(itemizedOverlay))
{
mapOverlays.remove(itemizedOverlay);
}
mapOverlays.add(itemizedOverlay);