I have a circle on my map. Now I want to detect if the user (or me) is inside the circle.
Circle circle = map.addCircle(new CircleOptions()
.center(new LatLng(14.635594, 121.032962))
.radius(55)
.strokeColor(Color.RED)
);
I have this code:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,ll);
Location.distanceBetween( pLat,pLong,
circle.getCenter().latitude, circle.getCenter().longitude, distance);
if( distance[0] > circle.getRadius() ){
Toast.makeText(getBaseContext(), "Outside", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside", Toast.LENGTH_LONG).show();
}
And on myLocationListener I have this:
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
pLong = location.getLongitude();
pLat = location.getLatitude();
}
It works correctly if I parameter inside distanceBetween is the coordinates of marker, however, the toast displays Outside even though my location is inside the radius.
Any ideas how to do this correctly? Please help. Thanks!
EDIT
I discovered something odd.
On the picture, you can see I have a textView above which has 5 numbers (circle Latitude, circle longitude, distance at index 0 , distance at index 1 , distance2). distance is a float array to store the distance between the center of the circle and the user location. I set the radius to 100, and I think the unit is meters, however, as you can see, the values at the distance array are : 1.334880E7 , -81.25308990478516 , -10696092987060547 . What is the formula for the computation of the distance? And also, 1.something times 10 raise to 7 is about 13 million which is really greater than 100. Please help its really confusing right now. According to documentation of Circle (The radius of the circle, specified in meters. It should be zero or greater.) and distanceBetween (Computes the approximate distance in meters between two locations) so I don't know why is this the result.
tl;dr? jsFiddle here - look at your console output.
Basically there're two ways to do this:
Check if the (marker of) the user is inside the Circle Bounds
Compute the distance between the user and the center of the Circle. Then check if it is equal or smaller than the Circle Radius. This solution needs the spherical library to work.
Circle Bounds
Just add a circle:
circle = new google.maps.Circle( {
map : map,
center : new google.maps.LatLng( 100, 20 ),
radius : 2000,
strokeColor : '#FF0099',
strokeOpacity : 1,
strokeWeight : 2,
fillColor : '#009ee0',
fillOpacity : 0.2
} )
and then check if the marker is inside:
circle.getBounds().contains( new google.maps.LatLng( 101, 21 ) );
At a first glance you might think this works. But it doesn't. In the background google (still) uses a rectangle, so everything inside the rectangular bounding box, but outside the circle will be recognized as inside the latLng bounds. It's wrong and a known problem, but it seems Google doesn't care.
If you now think that it would work with rectangular bounds, then you're wrong. Those don't work either.
Spherical Distance
The easiest and best way is to measure the distance. Include the spherical library by appending &library=spherical to your google maps script call. Then go with
google.maps.geometry.spherical.computeDistanceBetween(
new google.maps.LatLng( 100, 20 ),
new google.maps.LatLng( 101, 21 )
) <= 2000;
I know this question had been asked more than a year ago but I have
the same problem and fixed it using the distanceBetween static function of Location.
float[] distance = new float[2];
Location.distanceBetween(latLng.latitude, latLng.longitude, circle.getCenter().latitude,circle.getCenter().longitude,distance);
if ( distance[0] <= circle.getRadius())
{
// Inside The Circle
}
else
{
// Outside The Circle
}
Use GoogleMap.setOnMyLocationChange(OnMyLocationChangeListener) instead of LocationManager. This way you will get Locations that are the same as blue dot locations.
Related
I have the coordinates stored in the Firebase database, from there I get all these coordinates, and I want to make it so that I can find out how many coordinates are included in the area bounded by my circle.Question: How do I implement the boundaries of this blue circle? (The circle is in the image).
Here is the image: [Google Maps][1]
Here is the code where I get all the coordinates from Firebase:
if (model.getPostId() != null) {
if(model.getLat() != 0 && model.getLon() != 0){
Toast.makeText(getActivity(), "Lat = " + model.getLat() + "Lon = " + model.getLon(),Toast.LENGTH_SHORT).show();
}
}
Please help me! I have been looking for 5 days for information on how to do this, but I have not found it: (thank you in advance!
[1]: https://i.stack.imgur.com/LeY8a.jpg![enter image description here]
Here is another example:(https://i.stack.imgur.com/zyoan.jpg)![enter image description here]
Here is another example:
(https://i.stack.imgur.com/RHw7L.jpg)
Figure out the centre coordinates(𝑥𝑐,𝑦𝑐) of the circle and the radius (𝑟). Then get the distance of your firebase coordinates (𝑥𝑝,𝑦𝑝) from the centre of the circle. 𝑑=√((𝑥𝑝−𝑥𝑐)2+(𝑦𝑝−𝑦𝑐)2). The point (𝑥𝑝,𝑦𝑝) is inside the circle if 𝑑<𝑟, on the circle if 𝑑=𝑟, and outside the circle if 𝑑>𝑟.
So if you added the circle like this:
Circle circle = map.addCircle(new CircleOptions()
.center(new LatLng(xc, yc))
.radius(r)
.strokeColor(Color.RED)
.fillColor(Color.BLUE));
Then you should have the centre coordinates and the radius to use this formula.
double d = Math.sqrt(Math.pow((xp-xc),2)+Math.pow((yp-yc),2));
if(d<r || d==r){
//your logic in here
}
I'm drawing many circles on Google Maps API with the following code:
Circle circle = map.addCircle(new CircleOptions()
.center(lastKnownLatLng)
.radius(4)
.strokeColor(Color.RED)
.fillColor(Color.RED));
And store them into List<Circle> circleList = new ArrayList<>() by adding them one by one with circleList.add(circle).
I want to make the radius of these circles resizing automatically when the user zoom "in" and "out" (like Polyline Class do). This is my solution but I have no idea how to calculate new radius.
public GoogleMap.OnCameraChangeListener getCameraChangeListener() {
return new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition position) {
Log.d("Zoom", "Zoom: " + position.zoom);
zoomLevel = position.zoom;
if(!circleList.isEmpty()){
resizeCircles();
}
}
};
}
public void resizeCircles() {
if (???) { // if zoom in, it mean zoomLevel increase and I need to decrease radius
double newRadius = ???
for (int i = 0; i < circleList.size(); i++)
circleList.get(i).setRadius(newRadius);
}
if (???) { // if zoom out, it mean zoomLevel decrease and I need to increase radius
double newRadius = ???
for (int i = 0; i < circleList.size(); i++)
circleList.get(i).setRadius(newRadius);
}
}
Original Answer
Figure out the default radius when not zoomed. Then use the zoom level as a multiplier to your initial radius.
You might also want to change your circle's initial radius to a constant so it can be used elsewhere. Adjust this value as needed for your app.
private static final double INITIAL_RADIUS = 4.0;
Instead of depending on the previous zoom level, find the current zoom level so you can then determine an appropriate multiplier. When increasing the zoom level by 1, it doubles the width of the view, so we'd want to have similar behavior for the circle radius.
// Something like this, perhaps.
double newRadius = INITIAL_RADIUS * Math.pow(2.0, currentZoomLevel);
Zoom level 0 is also a possibility, so this may be a special case to deal with.
More about the zoom levels can be found here: https://developers.google.com/maps/documentation/android-sdk/views#zoom
Extended Answer
Decreasing the circle size when zooming in is just the inverse. An adjustment to the initial radius may be necessary. Again, be aware of the 0 zoom level possibility.
// Something like this, perhaps.
double newRadius = INITIAL_RADIUS / Math.pow(2.0, currentZoomLevel);
In my Android application I have to use my current heading (using accelerometer and magnetometer) and current bearing to targetLocation (location.bearingTo(targetLocation)).
I already know that using accelerometer and magnetometer to figure out current heading starts at 0° on magnetic North and current Bearing starts on geographical North. So i figured out, that i have to add to headingValue, depending on my current location, a value called declination.
For example, I pick up a certain GPS point from google-maps, adding this point as locationpoint in the application. Starting application, moving before measuring the device like a infinity-sign in the air and holding the device in front of me focused in target direction. So i notice that heading != bearing. Can anyone explain to me the error? Assume that i tried different distances between 50 and 3 meters and that my device is calibrated correctly. Below are important methods of source code:
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values.clone();
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values.clone();
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
double tempAzimuth = Math.toDegrees(orientation[0]); // orientation contains: azimut, pitch and roll
if(tempAzimuth < 0){
currentHeading = tempAzimuth + 360;
} else {
currentHeading = tempAzimuth;
}
TVheadingMag.setText(""+String.format( "%.2f",currentHeading)+"°");
}
}
}
#Override
public void onLocationChanged(Location location) {
//Declination http://stackoverflow.com/questions/4308262/calculate-compass-bearing-heading-to-location-in-android
geoField = new GeomagneticField(
Double.valueOf(location.getLatitude()).floatValue(),
Double.valueOf(location.getLongitude()).floatValue(),
Double.valueOf(location.getAltitude()).floatValue(),
System.currentTimeMillis());
if(location.bearingTo(this.target)<0){
currentBearing = location.bearingTo(this.target)+360;
} else {
currentBearing = location.bearingTo(this.target);
}
headingWithDeclination = currentHeading;
headingWithDeclination += geoField.getDeclination();
currentDistance = location.distanceTo(this.target);
TVheading.setText(""+String.format( "%.2f", headingWithDeclination)+"°");
TVheadingMag.setText(""+String.format( "%.2f",currentHeading)+"°");
TVbearing.setText(""+String.format( "%.2f",currentBearing)+"°");
TVgps.setText(""+ String.format( "%.6f",location.getLatitude()) + " " + String.format( "%.6f",location.getLongitude()));
}
UPDATE
Picture: https://pl.vc/1r6ap
The orange marked position is targetLocation.
Both position are heading to targetLocation.
Can you agree that these results are quiet correctly displayed?
During creation of this pic, i've noticed that both white marks are not equal to positions i was standing at. It seems like bad gps data is the reason because of the problem, isnt it?
Heading is the direction where you look, e.g a tank in which direction it would shoot, while bearing is the direction this vehicle moves. So that should answer why bearing is not heading.
They have different names, and meanings, they are different caluclated, they could not be expected to deliver the same value.
More details
You can move North (bearing = North) , but look at NE. (heading)
Gps delivers bearing (or course (over ground)), the direction the vehicle moves (altough some Api wrongly call it heading)
Compass (=magnetometer) delivers the direction in which you hold the device = (heading)
When you calculate the bearing between the two locations defined as coordinates in lat,lon , as you do in targetLocation (location.bearingTo(targetLocation)). then this is bearing! It is not heading!
And neither the compass not the accelrometer will deliver a decent heading value.
Some android device are very wrong in their magnetomter ( I saw +-20 degrees compared to +/- 2 degrees of my iPhone., Always use a traditional high quality compass as reference)
The ios devices shows the heading well within +/- 2 degress when well calibrated, (you have to calibrate each time before looking at the decice value, not only when you are asked by the operating system to calibrate).
GPS when moving > 10 km(h delives goot bearing results, but not heading.
Magnetometer can be off by some degree even when calibrated.
And usually the declination is smaller than the error.
Declination is nearly nothing in europe, 3 degress very north (europe), only a few places have a high declination >6-7°(north alaska)
Update to your further explantion in your graphic:
You have placed two points with a distance of only 15m, while GPS will not be much more acurate than 3-6m.
So imagine 6m offset of start or destination: such a triangle where a = 6m, b = 15, has an angle of atan2(6 / 15.0) = 21°. So you have an offset of 21° only by inacuracy of location. However still think at the differnce of heading by compass and bearing by line of sight between two locations.
I'm using onLocationChanged to:
//set the location of a point
point1 = (new LatLng(location.getLatitude() , location.getLongitude()));
I'm trying to construct a polyline that points in the direction of the heading as I'm moving. Ive used the computeHeading method to calculate the heading and then I put that in computeOffset to generate another point x feet away as the far point to generate a polyline. This is done like this:
#Override
public void onLocationChanged(Location location) {
point1 = (new LatLng(location.getLatitude() , location.getLongitude()));
point2 = (new LatLng(location.getLatitude() , location.getLongitude()));
heading = SphericalUtil.computeHeading(point1, point2);
navOrigin = (new LatLng(location.getLatitude() , location.getLongitude()));
navSecPoint = SphericalUtil.computeOffset(point2, 500, heading);
PolylineOptions navigation = new PolylineOptions()
.add(navOrigin)
.add(navSecPoint)
.color(Color.MAGENTA);
if(navigationalLine !=null) { navigationalLine.remove(); }
else { navigationalLine = getMap().addPolyline(navigation); }
navigationalLine = getMap().addPolyline(navigation);
Only problem is to determine an instantaneous heading I need a distinct location for point1 and for point2. Currently as they are both in my onLocationChanged they both fill with the same location data. You can't compute a heading if both points are in the same spot.
How do I create some sort of timer or location based firing mechanism that gives some millisecond time delay between when point1 is filled with location data and a couple feet later to fill point2 with location data.
You can see the problem illustrated here
Using a timer to offset the location of two points is not necessary. Although a heading could be calculated with the spherical util tools the android.location series has a getBearing() method that continually updates with the heading of the device.
The
navSecPoint = SphericalUtil.computeOffset(point2, 500, heading);
could be substituted with:
navSecPoint = SphericalUtil.computeOffset(point2, 500, bearing);
the getBearing() method is a float and the computeOffset requires a double. This can be done:
float floatbearing = location.getBearing();
double bearing = floatbearing;
If you did decide to use a timer. Use the java.util.TimerTask.
Follow this tutorial:
run() with Timer
I've added several or more pegs to my google maps in various places and similarly added radius circles using the code below. But I'd like to remove all added circles, but keep all pegs on the map. Does anyone know how to do this?
The difference between this and most other questions on this subject is,
I want to remove all circles simultaneously
Whilst keeping all pegs on the map
Code:
public static void GoogleSetup (double MapSize, double lat, double lon){
CircleOptions circleOptions = new CircleOptions()
.center(new LatLng(lat, lon)) //set center
.radius(MapSize) //set radius in meters
.fillColor(Color.argb(30, 20, 20, 140)) //default
.strokeWidth(2)
.strokeColor(Color.RED);
Circle myCircle = mGoogleMap.addCircle(circleOptions);
}
When adding Circles store all of them into a List:
Circle myCircle = mGoogleMap.addCircle(circleOptions);
myList.add(myCircle);
At some point, iterate over this list and remove all of them:
for (Circle myCircle : myList) {
myCircle.remove();
}
myList.clear();
The API provides no other way of removing visual objects except for GoogleMap.clear() as of version 4.2.