How to remove a specific ItemizedOverlay from a MapView? - android

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

Related

How to make the onLocationResult function work?I

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

Android Google map shows black screen before loading

I have an application with an initial window with three buttons. When I click on one of them, I start a progress dialog while I am loading a Google Map V2 and drawing some markers on it.
In the onMapReady callback I dismiss the progress dialog:
#Override
public void onMapReady(final GoogleMap map) {
Log.i(MyMoneyBackActivity.TAG, "ShopsMapActivity onMapReady");
GMap = map;
if (needsInit) {
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(CAMERA_LAT,
CAMERA_LNG));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(12f);
map.moveCamera(center);
map.animateCamera(zoom);
}
// Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
// Clears all the existing coordinates
map.clear();
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
provider = mLocationManager.getBestProvider(criteria, true);
// Get best last location measurement
mBestReading = bestLastKnownLocation(MIN_LAST_READ_ACCURACY, FIVE_MIN);
mLocationManager.requestLocationUpdates(provider, 20000, 0, this);
Log.i(MyMoneyBackActivity.TAG, "Map");
Geocoder geoCoder = new Geocoder(ShopsMapActivity.this, Locale.getDefault());
if ( geoCoder.isPresent() )
Log.i(MyMoneyBackActivity.TAG, "Geocoder available");
else
Log.i(MyMoneyBackActivity.TAG, "Geocoder NOT available");
// Add a marker for every shop
for (ShopElement rec : MyMoneyBackActivity.shopElementsList) {
//String addressStr = "Aquileia 39,Udine,Italy";
String addressStr = rec.getaddress() + "," + rec.getcity() +",Italy";
Log.i(MyMoneyBackActivity.TAG, "addressStr -" + addressStr + "-");
try {
List<Address> addresses = geoCoder.getFromLocationName(addressStr, 1);
if (addresses.size() > 0) {
latitude = addresses.get(0).getLatitude();
longitude = addresses.get(0).getLongitude();
}
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(MyMoneyBackActivity.TAG, "Position : " + latitude + " " + longitude);
point = new LatLng(latitude, longitude);
// Add a new marker for this shop
drawMarker(map, point, rec, "");
}
map.setInfoWindowAdapter(new PopupAdapter(this,
getLayoutInflater(),
images));
//point = new LatLng(CAMERA_LAT, CAMERA_LNG);
//drawMarker(map, point, null, "Centro");
// Display last reading information
if(mBestReading!=null){
onLocationChanged(mBestReading);
}
if (MyMoneyBackActivity.progressDialog.isShowing()) {
MyMoneyBackActivity.progressDialog.dismiss();
MyMoneyBackActivity.progressDialog = null;
}
}
But what I got for some tens of seconds is a completely black screen before the map is actually drawn.
Hardware accelartion and largeheap was the issue in my case. I removed them from the app level and used them in the activity they used.
Issue was in Manifest.
<application
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:hardwareAccelerated="false"
android:largeHeap="true">
Remove from Manifest and Use in the Activity
<activity
android:name="com.mycompayname.activities.SignUpActivity"
android:hardwareAccelerated="false"
android:largeHeap="true"/>
Check if it works in Google Play Services 6.7.76 - see here https://code.google.com/p/gmaps-api-issues/issues/detail?id=7679.

Direction Route From User Location to Marker Using String Builder on MarkerClick

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.

Update position of a marker without adding a new one

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

googleMap.getMyLocation(); cannot get current location

i want to make a program to calculate the distance between some places to my current location, but my googleMap.getMyLocation(); doesnt work properly.
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setCompassEnabled(false);
mylocation = googleMap.getMyLocation();
direction = new GMapV2Direction();
LatLng from, to;
from = new LatLng(-7.26071409, 112.80674726);
for(int i=0; i<lat.length; i++){
to = new LatLng(lat[i], lon[i]);
doc = direksi.getDocument(from, to, GMapV2Direction.MODE_DRIVING);
distance[i] = (double)direction.getDistanceValue(doc) / 1000;
}
i saved the latitude and longitude of some places in lat[] and lon[].
LatLng 'from' is mylocation and 'to' is my destination places.
the problem appear when i change
from = new LatLng(-7.26071409, 112.80674726);
to
from = new LatLng(mylocation.getLatitude(), mylocation.getLongitude());
i want to do the calculation without opening the googlemaps. the google maps will appear when i touch the map button as pop up window. so the calculation will happen without opening googlemap
please help me
Try this...I hope this will be help to you
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
double latitude = location.getLatitude();
double longitude = location.getLongitude();
This is my code for you, I hope this help you... edit it if you think, it isn't with correct sintaxis...
This work for android 4.x and 5.x and 6.x, I not test this in android 7
//I use this like global var to edit or get informacion about google map
GoogleMap gMap;
#Override
public void onMapReady(GoogleMap googleMap) {
gMap = googleMap;
if (ActivityCompat.checkSelfPermission(Activity_Map.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Activity_Map.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Activity_Map.this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}else{
if(!gMap.isMyLocationEnabled())
gMap.setMyLocationEnabled(true);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
myLocation = lm.getLastKnownLocation(provider);
}
if(myLocation!=null){
LatLng userLocation = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
gMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 14), 1500, null);
}
}
}
getMyLocation() => this method is deprecated. You need to use LocationClient instead.
You can find informations about LocationClient and how to get current location here

Categories

Resources