How to clear previously drawn circle in Google map Android? - android

I want the previously drawn circle to be removed. When I am searching for a new place, the first circle remains there and the new circle is also drawn. Basically every time when the location gets changed, circle keeps getting drawn(overlapping each other) without deleting the previous circle.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_geocoding_maps);
toolbar=(Toolbar)findViewById(R.id.mapToolbar);if (!checkPlayServices()) {
Toast.makeText(this, "Device not compatible", Toast.LENGTH_SHORT).show();
finish();
}
Bundle extras=getIntent().getExtras();
if(extras==null)
{
itemAction=-1;
Log.w(TAG, "Extras are null");
finish();
}
else
{
try{
item=extras.getParcelable(GeofenceUtils.P_KEY);
}catch (Exception e)
{
Log.w(GeofenceUtils.getTag(), e.getMessage());
}
if (item != null) {
if(item.getLatitude()==0.0&&item.getLongitude()==0.0) {
//New item
itemAction=0;
}
else {
//Update item
Log.w(TAG, "Title : "+item.getTitle());
itemAction=1;
}
Log.w(TAG, "Item Action: "+itemAction);
}
else {
Log.w(TAG, "Item null: ");
}
}
dbHelper=GeofenceDBHelper.getInstance(this);
assert toolbar != null;
toolbar.setTitle("Pick a location");
toolbar.setTitleTextColor(Color.WHITE);
setSupportActionBar(toolbar);
address="";
addressText = (EditText) findViewById(R.id.addressText);
if(itemAction==1) {
address=item.getAddress();
if (addressText != null) {
addressText.setText(address);
}
}
addressText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
Log.w(TAG, "onEditorAction");
address = addressText.getText().toString();
LatLng latLng = getLocationFromAddress(GeocodingMapsActivity.this, address);
if (latLng != null) {
mlatitude = latLng.latitude;
mlongitude = latLng.longitude;
marker.setPosition(latLng);//match this behavior to your 'Send' (or Confirm) button
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 18);
mMap.animateCamera(cameraUpdate);
circle = drawCircle(new LatLng(mlatitude, mlongitude));
} else {
Log.w(TAG, "onEditorAction: address null");
}
}
return false;
}
});
if(savedInstanceState!=null)
{
//For handling screen rotations
mlatitude=savedInstanceState.getDouble("Latitude");
mlongitude=savedInstanceState.getDouble("Longitude");
Log.w(TAG, "itemAction savedInstanceState: "+itemAction);
}
else
{
mlatitude=item.getLatitude();
mlongitude=item.getLongitude();
}
clearButton=(ImageButton)findViewById(R.id.clear_text);
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addressText.setText("");
}
});
MyLocationButton=(FloatingActionButton)findViewById(R.id.fab);
MyLocationButton.setBackgroundTintList(ColorStateList.valueOf(Color.WHITE));
MyLocationButton.setRippleColor(Color.parseColor("#f5f5f5"));
MyLocationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mGoogleApiClient.isConnected()) {
LatLng latLng = getCurrentLocation();
if (latLng != null) {
setAddress();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 18);
mMap.animateCamera(cameraUpdate);
// circle = drawCircle(new LatLng(mlatitude, mlongitude));
}
}
}
});
MyLocationButton.setVisibility(View.GONE);
mGeofenceList=new ArrayList<>();
buildGoogleApiClient();
createLocationRequest();
buildLocationSettingsRequest();
checkLocationSettings();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Log.w(TAG, "onCreate");
}
private void removeEverything(){
marker.remove();
marker = null;
circle.remove();
circle = null;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
Circle circle;
#Override
public void onMapReady(GoogleMap googleMap) {
Log.w(TAG, "onMapReady1");
mMap = googleMap;
// mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
enableMyLocation();
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
marker.setPosition(latLng);
mlatitude=latLng.latitude;
mlongitude=latLng.longitude;
setAddress();
}
});
Log.w(TAG, "onMapReady2");
LatLng mLocation=null;
if(mGoogleApiClient.isConnected()&&itemAction==0)
mLocation = getCurrentLocation();
Log.w(TAG, "onMapReady3");
if (itemAction==0&&mLocation != null) {
mlatitude = mLocation.latitude;
mlongitude = mLocation.longitude;
}
else if(itemAction==1) {
mLocation=new LatLng(mlatitude, mlongitude);
}
else
mLocation = new LatLng(0.0, 0.0);
Log.w(TAG, "onMapReady3");
if(mGoogleApiClient.isConnected())
setAddress();
Log.w(TAG, "onMapReady4");
marker = mMap.addMarker(new MarkerOptions().position(mLocation).draggable(true));
Log.w(GeofenceUtils.getTag(), item.getMarkerColor()+"");
marker.setIcon(BitmapDescriptorFactory.fromResource(GeofenceUtils.getMarker(item.getMarkerColor())));
mMap.setOnMarkerDragListener(this);
if(itemAction==1)
{
CameraUpdate cameraUpdate=CameraUpdateFactory.newLatLngZoom(new LatLng(item.getLatitude(), item.getLongitude()), 18);
CameraUpdateFactory.newLatLngZoom(mLocation, 18);
mMap.animateCamera(cameraUpdate);
// circle = drawCircle(new LatLng(mlatitude, mlongitude));
}
Log.w(TAG, "onMapReady5");
}
private Circle drawCircle(LatLng latLng) {
CircleOptions options = new CircleOptions()
.center(latLng)
.radius(50)
.strokeColor(Color.BLACK)
.fillColor(Color.rgb( 229, 204, 229))
.strokeWidth(3);
return mMap.addCircle(options);
}
There are two circles drawn, i want first circle to be removed as soon as the second circle is drawn.

private Circle circle;
Before drawing a circle to the map. Check first if circle is drawn. Just remove the circle then draw new circle to the map.
if(circle!=null){
circle.remove();
}
circle = drawCircle(new LatLng(mlatitude, mlongitude));

Related

Click on google maps marker in android?

I have an an activity where the main view is Google maps. And I set up a marker when the map is initially loaded, but when I click on it I am not able to get the locality or anything. The maps appears, but I can't click on the marker, or tap or tap on the screen and hold to create a new marker. basically it cannot do anything...And i can't figure out why! Hope you guys can see something that I am not seeing.
Here is my main activity.
public class MapsActivity extends FragmentActivity {
//Maps
private GoogleMap mMap;
//Marker
private Marker marker;
//Location
private LocationListener locationListener = null;
private LocationManager locationManager = null;
private static final float DEFAULTZOOM = 15;
private double longitude_mapsActivity;
private double latitude_from_mapsActivity;
private String cityName_mapsActivity;
private String countryName_mapsActivity;
//ProgressBar
private ProgressBar myPB_MAPS;
//Buttons
private ImageButton fab_doneButton;
//SearchEditText
private EditText editText_Search;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
}
});
//Get user current location.
//myPB_MAPS = (ProgressBar) findViewById(R.id.myPB_MAPS);
//initialize your map
initMap();
//FAB button
fab_doneButton = (ImageButton) findViewById(R.id.activity_maps_FAB_done);
fab_doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (countryName_mapsActivity == null) {
Toast.makeText(MapsActivity.this, "Location is null", Toast.LENGTH_SHORT).show();
} else {
Global_Class.getInstance().getValue().countryName_GLOBAL = countryName_mapsActivity;
Global_Class.getInstance().getValue().cityName_GLOBAL = cityName_mapsActivity;
Global_Class.getInstance().getValue().longitude_user_GLOBAL = longitude_mapsActivity;
Global_Class.getInstance().getValue().latitude_user_GLOBAL = latitude_from_mapsActivity;
//Go to make sure we're sending all the GPS info, so we set geoLocationFromMapsIsPresent to true.
FinishCard.geoLocationFromMapsIsPresent();
FinishCard.setComingBackFromMaps();
Intent FinishCardIntent = new Intent(MapsActivity.this, FinishCard.class);
startActivity(FinishCardIntent);
}
}
});
//EditText
editText_Search = (EditText) findViewById(R.id.maps_EditText);
editText_Search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
}
});
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
}
private void performSearch()
{
String location = editText_Search.getText().toString();
if(location.length() == 0)
{
Toast.makeText(this,"Please enter a location",Toast.LENGTH_SHORT).show();
return;
}
//1-first step
Geocoder gc = new Geocoder(this);
List<Address> list = null;//For this function I only want a single address.
try
{
//3-Third step
list = gc.getFromLocationName(location,10);
}
catch (IOException e)
{
e.printStackTrace();
}
//4-Fourth step
Address add = list.get(0);//Give me the first and only item of the list.
//5-fifth step
String locality = add.getLocality();//So if you enter Taj mahal you get Agra, the place where its at, thats what Address locality does.
double lat = add.getLatitude();
double lng = add.getLongitude();
//GoToLocation() method
gotoLocation(lat, lng, DEFAULTZOOM);
//For Removing existing markers.
if(marker != null)
{
marker.remove();
}
MarkerOptions options = new MarkerOptions()
.title(locality)
.position(new LatLng(lat, lng))
.draggable(true);
marker = mMap.addMarker(options);
}
private void gotoLocation(double lat, double lng, float zoom)
{
LatLng ll = new LatLng(lat,lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mMap.moveCamera(update);
}
private void setMarker(String locality, String country, double lat, double lng)
{
if(marker != null)
{
marker.remove();
}
MarkerOptions options = new MarkerOptions()
.title(locality)
.position(new LatLng(lat, lng))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
.draggable(true);
if(country.length() > 0)
{
options.snippet(country);//Background highlight TEXT SUPER IMPORTANT
}
//.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
marker = mMap.addMarker(options);//So here we connect our marker to our map, which is used in initMap.
}
private void initMap()
{
if(mMap == null)
{
if(mMap != null)
{
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener()
{
#Override
public void onMapLongClick(LatLng ll) {
Geocoder gc = new Geocoder(MapsActivity.this);
List<Address> list = null;
try {
list = gc.getFromLocation(ll.latitude, ll.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address add = list.get(0);
MapsActivity.this.setMarker(add.getLocality(), add.getCountryName(), ll.latitude, ll.longitude);//this is where we set the orange marker.
latitude_from_mapsActivity= ll.latitude;
longitude_mapsActivity= ll.longitude;
countryName_mapsActivity = add.getCountryName();
cityName_mapsActivity = add.getLocality();
}
});
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker)
{
LatLng ll = marker.getPosition();
latitude_from_mapsActivity= ll.latitude;
longitude_mapsActivity = ll.longitude;
Geocoder gc = new Geocoder(MapsActivity.this);
//Global_Class.getInstance().getValue().cardLocality = "Paris";
List<Address> list = null;
try
{
list = gc.getFromLocation(ll.latitude, ll.longitude,1);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
Address add = list.get(0);
countryName_mapsActivity = add.getCountryName();
cityName_mapsActivity = add.getLocality();
return false;
}
catch (IndexOutOfBoundsException e)
{
return false;
}
}
});
mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() //If you want to drag the original google maps marker you use this method, if you comment this out it will use the orange one.
{
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
Geocoder gc = new Geocoder(MapsActivity.this);
List<Address> list = null;
LatLng ll = marker.getPosition();
try {
list = gc.getFromLocation(ll.latitude, ll.longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address add = list.get(0);
marker.setTitle(add.getLocality());
marker.setSnippet(add.getCountryName());
//marker.showInfoWindow();
}
});
}
}
}
}
Here is my xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.daprlabs.swipedeck.GeoLocation.MapsActivity">
<RelativeLayout
android:layout_width="340dp"
android:layout_height="50dp"
android:background="#FFFFFF"
android:elevation="10sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp">
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/maps_EditText"
android:imeOptions="actionSearch"
android:inputType="text"/>
</RelativeLayout>
<ProgressBar
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/myPB_MAPS"
android:layout_marginLeft="150dp"
android:layout_marginTop="55dp"/>
<ImageButton
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/circle_fab"
android:id="#+id/activity_maps_FAB_done"
android:layout_gravity="right|bottom"
android:src="#drawable/white_plus" />
</fragment>
You are contradicting yourself in your initMap().
Remove the following if statement:
if (mMap == null)
Also only call initMap() after mapFragment.getMapAsync returns. At this point, you know your map is ready to go.
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
initMap();
}
});
You are supposed to implement
OnMapReadyCallback
And in turn override
onMapReady
Now you can manipulate the Map within onMapReady. Before that, it is not certain that your Map has actually set properly.
Anything that manipulates the Map like loading markers over it and setting marker click listeners has to happen in onMapReady.
As an example of Map's manipulation at appropriate time, you can take hint from the following code where Map's camera is only set when it has properly set.
public class YourMapFragment extends Fragment implements OnMapReadyCallback {
...
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition,16));
mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + lat + "Lng:" + log));
}
...
}

how can we reuse the google map object and not create in everytime the activity is called

I want that the map object once created should be reused and not created again and again because when ever the onCreate() of support manager gets called I feel its a new instance, that I need to avoid so can anyone please help me on this ?
Sharing the code I am using:
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
int checkGooglePlayServices = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
if (checkGooglePlayServices != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(checkGooglePlayServices)) {
GooglePlayServicesUtil.getErrorDialog(checkGooglePlayServices,
this,
0).show();
} else
Toast.makeText(this,
"Please check your Google Play Services in order to run this app",
Toast.LENGTH_LONG).show();
finish();
}
} catch (Exception e) {
e.printStackTrace();
}
setContentView(R.layout.activity_gmap);
setUpMapIfNeeded();
}
#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 (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).setRetainInstance(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View customMarkerView = null;
try {
customMarkerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.view_custom_marker, null);
TextView titleView = (TextView) customMarkerView.findViewById(R.id.title);
customMarkerView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
customMarkerView.buildDrawingCache();
} catch (Exception e) {
e.printStackTrace();
}
return customMarkerView;
}
});
setUpMap();
}
}
}
private void setUpMap() {
try {
int ZoomLevel = 9;
int animateZoomLevel = 7;
double lat = Double.parseDouble(myvehicleInfo.getLatitude());
double log = Double.parseDouble(myvehicleInfo.getLongitude());
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, log)));
String type = Utility.getDefaultMap(GMapActivity.this);
switch (type) {
case "Normal":
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case "Hybrid":
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
case "Satellite":
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case "Terrain":
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
}
LatLng longlat = new LatLng(lat, log);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(longlat);
final CameraPosition cameraPosition1 = new CameraPosition.Builder()
.target(longlat)
.zoom(ZoomLevel + animateZoomLevel)
.tilt(45)
.build();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(longlat, ZoomLevel));
try {
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition1)
, 2500,
new GoogleMap.CancelableCallback() {
#Override
public void onFinish() {
double lat = Double.parseDouble(myvehicleInfo.getLatitude());
double log = Double.parseDouble(myvehicleInfo.getLongitude());
LatLng ll = new LatLng(lat, log);
MarkerOptions axesTrackMarker = null;
if (myvehicleInfo.getLocation().isEmpty()) {
axesTrackMarker = new MarkerOptions()
.position(ll)
.title(myvehicleInfo.getVehicleName());
} else {
axesTrackMarker = new MarkerOptions()
.position(ll)/*
.icon(BitmapDescriptorFactory
.fromBitmap(
getMarkerBitmapFromView(
myvehicleInfo.getVehicleName(),
myvehicleInfo.getLocation())
))*/;
}
mMap.addMarker(axesTrackMarker).showInfoWindow();
}
#Override
public void onCancel() {
// do something
}
}
);
} catch (Exception ex) {
ex.printStackTrace();
}
// }
//});
} catch (Exception e) {
}
}

Current Location updation on movement using google maps android

I am using below code to show current location on google maps. But the problem is that if i am moving my location is updating again and again. For the first time loading i want to fix my current location on the map, after that if i am moving then i don't want to update it. I am selecting a point on the map, and if i am moving or after few seconds it again moves to my current location and don't allow user to select desired point. My code is given below, please help me out here.
MarkerOptions markerOptions = new MarkerOptions();
private GoogleMap mMap;
private Location lastLocation = null;
private LocationClient mLocationClient;
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
float diff = 0;
if (lastLocation != null) {
diff = location.distanceTo(lastLocation);
}
if ((lastLocation == null) || (diff > 5)) {
LatLng latLng = new LatLng(location.getLatitude(),
location.getLongitude());
CameraPosition cameraPosition = new CameraPosition(latLng, 20,
45, 0);
CameraUpdate cameraUpdate = CameraUpdateFactory
.newCameraPosition(cameraPosition);
mMap.animateCamera(cameraUpdate, 2000, null);
lastLocation = location;
}
}
};
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapVirard)).getMap();
mMap.setOnMapClickListener(Virtuvity.this);
if (mMap != null) {
mMap.setOnMapClickListener(Virtuvity.this);
mMap.setMyLocationEnabled(true);
mMap.setBuildingsEnabled(true);
mMap.setIndoorEnabled(true);
mMap.getUiSettings().setCompassEnabled(false);
mMap.setMapType(mMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(true);
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
LatLng latLng = arg0.target;
latitude = latLng.latitude;
longitude = latLng.longitude;
}
});
}
}
}
ConnectionCallbacks connectionCallbacks = new ConnectionCallbacks() {
#Override
public void onDisconnected() {
}
#Override
public void onConnected(Bundle connectionHint) {
mLocationClient.requestLocationUpdates(REQUEST, locationListener);
}
};
private void setUpLocationClientIfNeeded() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(getApplicationContext(),
connectionCallbacks, onConnectionFailedListener);
}
}
OnConnectionFailedListener onConnectionFailedListener = new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
}
};
#Override
public void onMapClick(LatLng arg0) {
// TODO Auto-generated method stub
}
Inside onLocationChanged if location != null
call mLocationClient.removeUpdates(this);

Polyline draws a line from wrong location

I developing an app that draws a polyline on users movement.
For now i got a GoogleMap, and when I launch this app I got a polyline that draws from unknown location to my location. I Just want to start drawing this polyline when user start to move.
Anyone can tell me whats wrong with my code?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("MYTAG","onCreate()");
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
if (mGoogleApiClient != null)
Log.d("MYTAG","Google api created!");
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000) // 1 second, in milliseconds
.setSmallestDisplacement(10);
}
#Override
public void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
#Override
public void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mFusedLocationCallback);
mGoogleApiClient.disconnect();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.run_fragment, container, false);
} catch (InflateException e) {
// Map already created
}
if (mMap == null) {
// Get the map fragment
mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.myMapid)).getMap();
// If get map successfully set "Go to my location" button enabled
if (mMap != null)
mMap.setMyLocationEnabled(true);
}
// Timer widgets
tv_timer = (TextView)view.findViewById(R.id.timer);
b_start_activity = (Button)view.findViewById(R.id.b_start_activity);
b_start_activity.setOnClickListener(this);
// CountDown widgets
tv_CountDown = (TextView)view.findViewById(R.id.tv_countdown);
iv_CountDownBack = (ImageView)view.findViewById(R.id.iv_countdown);
// CountDown object
countDownTimer = new CounterClass(5000,1000);
return view;
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (mMap != null) {
getChildFragmentManager().beginTransaction()
.remove(getChildFragmentManager().findFragmentById(R.id.myMapid)).commitAllowingStateLoss();
mMap = null;
}
}
#Override
public void onConnected(Bundle bundle) {
location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
Log.d("MYTAG","Requesting location updates!");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mFusedLocationCallback);
} else
updateUI(location);
Log.d("MYTAG", "GoogleApi is connected! And location time is: " + location.getTime());
}
#Override
public void onConnectionSuspended(int i) {
Log.d("MYTAG", "GoogleApi connection suspended!");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i("MYTAG", "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
private void updatePolyline(LatLng tempLatlng, LatLng currentLatlng) {
Log.d("MYTAG","Polyline updated!");
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(tempLatlng, currentLatlng)
.width(10)
.color(Color.BLUE));
line.setVisible(true);
}
private void updateUI(Location location) {
Log.d("MYTAG", "Updating your location!");
LatLng temp = new LatLng(latitude, longitude);
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
// move camera to current location and zoom in
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
updatePolyline(temp,latLng);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.b_start_activity){
iv_CountDownBack.setVisibility(View.VISIBLE);
tv_CountDown.setVisibility(View.VISIBLE);
b_start_activity.setVisibility(View.GONE);
countDownTimer.start();
}
}
private class LocationCallback implements LocationListener{
public LocationCallback(){
}
#Override
public void onLocationChanged(Location location) {
Log.d("MYTAG", "Location changed");
LatLng temp = new LatLng(latitude, longitude); // Store previouse points
// Get new points
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
// Call to updateUI to update the UI with correct location on map
updateUI(location);
}
}

Android Google Map how to check if the gps location is inside the circle

I'm trying to detect if a user is in the radius of a Marker , using the users gps location. I have the marker's coordinates, but I don't know how to calculate whether the user is in the area. I've tried to use the following, but even when the current location is inside the circle I keep getting the "outside" message.
public class MapaEscola extends FragmentActivity {
private GoogleMap googleMap;
private Serializable escolas;
private ProgressDialog dialog;
private Circle mCircle;
private Marker mMarker;
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setContentView(R.layout.maps);
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// 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);
Bundle extra = getIntent().getBundleExtra("extra");
ArrayList<Escolas> objects = (ArrayList<Escolas>) extra.getSerializable("array");
try {
for(int i = 0; i < objects.size(); i ++) {
System.out.println(" escolas " + objects.get(i).getLatitude() + " " + objects.get(i).getLongitude());
float latitude = objects.get(i).getLatitude();
float longitude = objects.get(i).getLongitude();
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-23.316281, -51.155528), 15));
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(new LatLng(latitude, longitude));
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
LatLng latLng = new LatLng(latitude, longitude);
drawMarkerWithCircle(latLng);
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
float[] distance = new float[2];
Location.distanceBetween( mMarker.getPosition().latitude, mMarker.getPosition().longitude,
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
if( distance[0] > (mCircle.getRadius() / 2) ){
Toast.makeText(getBaseContext(), "Outside", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside", Toast.LENGTH_LONG).show();
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void drawMarkerWithCircle(LatLng position){
double radiusInMeters = 500.0;
int strokeColor = 0xffff0000; //red outline
int shadeColor = 0x44ff0000; //opaque red fill
CircleOptions circleOptions = new CircleOptions().center(position).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
mCircle = googleMap.addCircle(circleOptions);
MarkerOptions markerOptions = new MarkerOptions().position(position);
mMarker = googleMap.addMarker(markerOptions);
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
finish();
return true;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
I just ran the updated code and figured out what the main problem is.
You should be using the Location passed into the onMyLocationChange() callback, so that it uses your current location to tell if the device is within the circle or not:
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
float[] distance = new float[2];
/*
Location.distanceBetween( mMarker.getPosition().latitude, mMarker.getPosition().longitude,
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
*/
Location.distanceBetween( location.getLatitude(), location.getLongitude(),
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
if( distance[0] > mCircle.getRadius() ){
Toast.makeText(getBaseContext(), "Outside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius() , Toast.LENGTH_LONG).show();
}
}
});
Here is the full working example that I ran, it's a pared down version of your original code:
public class MainActivity extends ActionBarActivity {
private GoogleMap googleMap;
private Serializable escolas;
private ProgressDialog dialog;
private Circle mCircle;
private Marker mMarker;
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
setContentView(R.layout.activity_main);
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// 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);
// Bundle extra = getIntent().getBundleExtra("extra");
//ArrayList<Escolas> objects = (ArrayList<Escolas>) extra.getSerializable("array");
try {
//test outside
double mLatitude = 37.77657;
double mLongitude = -122.417506;
//test inside
//double mLatitude = 37.7795516;
//double mLongitude = -122.39292;
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLatitude, mLongitude), 15));
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(new LatLng(mLatitude, mLongitude));
//googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
LatLng latLng = new LatLng(mLatitude, mLongitude);
drawMarkerWithCircle(latLng);
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
float[] distance = new float[2];
/*
Location.distanceBetween( mMarker.getPosition().latitude, mMarker.getPosition().longitude,
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
*/
Location.distanceBetween( location.getLatitude(), location.getLongitude(),
mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
if( distance[0] > mCircle.getRadius() ){
Toast.makeText(getBaseContext(), "Outside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius() , Toast.LENGTH_LONG).show();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void drawMarkerWithCircle(LatLng position){
double radiusInMeters = 500.0;
int strokeColor = 0xffff0000; //red outline
int shadeColor = 0x44ff0000; //opaque red fill
CircleOptions circleOptions = new CircleOptions().center(position).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
mCircle = googleMap.addCircle(circleOptions);
MarkerOptions markerOptions = new MarkerOptions().position(position);
mMarker = googleMap.addMarker(markerOptions);
}
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(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
finish();
return true;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
Results of Inside the circle:
Results of outside the circle:
#Daniel Nugent:
imho getRadius() will return the radius and not the diameter so the "/2" is wrong
#WARpoluido:
I cant see that the mMarker variable is updated when the location changes. Why dont you use the value given to onMyLocationChange()?
Location.distanceBetween( mCircle.getCenter().latitude, mCircle.getCenter().longitude, location.getLatitude(), location.getLongitude(), distance);
if( distance[0] > mCircle.getRadius() ){
...
Hi I have got mine working correctly with this code
//Getting current location
private void getCurrentLocation() {
mMap.clear();
//Creating a location object
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
//moving the map to location
moveMap();
}
Circle circle = mMap.addCircle(new CircleOptions()
.center(new LatLng(54.773097, -6.557841))
.radius(55)
.strokeColor(Color.RED)
);
pLong = location.getLongitude();
pLat = location.getLatitude();
float[] distance = new float[2];
Location.distanceBetween(pLat, pLong,
circle.getCenter().latitude, circle.getCenter().longitude, distance);
if( distance[0] > circle.getRadius() ){
Toast.makeText(getBaseContext(), "You are not in a bunker", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "You are inside a bunker", Toast.LENGTH_LONG).show();
}
}
Inside the circle
Outside the circle
The accepted solution of Daniel Nugent isn't so good anymore because setOnMyLocationChangeListener is deprecated now.
Here is current way how to do it in fragment - change getActivity() with this for Activity:
private boolean mLocationPermissionGranted;
// The geographical location where the device is currently located. That is, the last-known
// location retrieved by the Fused Location Provider.
private Location mLastKnownLocation;
private long UPDATE_INTERVAL = 10 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
private FusedLocationProviderClient mFusedLocationProviderClient;
private void addLocationChangeListener(){
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
// Create the location request to start receiving updates
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
//mLocationRequest.setMaxWaitTime(0);
//mLocationRequest.setSmallestDisplacement(0);
// Create LocationSettingsRequest object using location request
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Check whether location settings are satisfied
// https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
SettingsClient settingsClient = LocationServices.getSettingsClient(getActivity());
settingsClient.checkLocationSettings(locationSettingsRequest);
// new Google API SDK v11 uses getFusedLocationProviderClient(this)
if (mLocationPermissionGranted) {
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest,
new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
// do work here
Location location = locationResult.getLastLocation();
}
},
Looper.myLooper());
} else {
getLocationPermission();
}
}

Categories

Resources