Alright so after reading Antonio's comment, I am with this in my code. Now regardless of what I submit as my percentage it still thinks my object is outside the bounding box.
My Position is the marker passed in.
LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds;
LatLngBounds newBounds = reduceBy(bounds, 0.05d);
if(newBounds.contains(myPosition.getPosition())) {
//If the item is within the the bounds of the screen
} else{
//If the marker is off screen
zoomLevel -= 1;}
}
return zoomLevel;
}
public LatLngBounds reduceBy(LatLngBounds bounds, double percentage) {
double distance = SphericalUtil.computeDistanceBetween(bounds.northeast, bounds.southwest);
double reduced = distance * percentage;
double headingNESW = SphericalUtil.computeHeading(bounds.northeast, bounds.southwest);
LatLng newNE = SphericalUtil.computeOffset(bounds.northeast, reduced/2d, headingNESW);
double headingSWNE = SphericalUtil.computeHeading(bounds.southwest, bounds.northeast);
LatLng newSW = SphericalUtil.computeOffset(bounds.southwest, reduced/2d, headingSWNE);
return LatLngBounds.builder().include(newNE).include(newSW).build();
}
}
I have all the zoom levels set but sometimes I run into spots such as this where it is still in bounds except the marker is off screen. I want to have a slightly smaller bounding box to detect this and then zoom out one level on only these situations.
You can use SphericalUtil class from the Google Maps API Utility Library to make the calculations:
public LatLngBounds reduceBy(LatLngBounds bounds, double percentage) {
double distance = SphericalUtil.computeDistanceBetween(bounds.northeast, bounds.southwest);
double reduced = distance * percentage;
double headingNESW = SphericalUtil.computeHeading(bounds.northeast, bounds.southwest);
LatLng newNE = SphericalUtil.computeOffset(bounds.northeast, reduced/2d, headingNESW);
double headingSWNE = SphericalUtil.computeHeading(bounds.southwest, bounds.northeast);
LatLng newSW = SphericalUtil.computeOffset(bounds.southwest, reduced/2d, headingSWNE);
return LatLngBounds.builder().include(newNE).include(newSW).build();
}
To reduce your bounds by a 5% (diagonal) you can do:
LatLngBounds newBounds = reduceBy(bounds, 0.05d);
Depending on your requirements for precision, you might want to just use simple interpolation like here:
public LatLngBounds reduceBounds(LatLngBounds bounds, double percentage) {
double north = bounds.northeast.latitude;
double south = bounds.southwest.latitude;
double east = bounds.northeast.longitude;
double west = bounds.southwest.longitude;
double lowerFactor = percentage / 2 / 100;
double upperFactor = (100 - percentage / 2) / 100;
return new LatLngBounds(new LatLng(south + (north - south) * lowerFactor, west + (east - west) * lowerFactor),
new LatLng(south + (north - south) * upperFactor, west + (east - west) * upperFactor));
}
This is very simple Math using +-*/ and doesn't cost a lot of performance.
To reduce your bounds dimensions by 10% you do:
LatLngBounds newBounds = reduceBounds(bounds, 10);
Add error checking and border case handling as needed
Related
I'm writing an Android app and integrating GoogleMapsV2 API. I have a series of markers on the map at various locations around an anchor.
I want those markers to converge on the anchor's position incrementally.
I've got a loop running that will call each marker B and from B's position calculate the bearing to the anchor A. I then calculate the destination coordinate for a fixed distance along that bearing and update.
Here are the two functions (taken from an amalgamation of stack posts and a GeoMapping site, for full disclosure) I'm using:
public double calcBearing(double lat1, double lon1, double lat2, double lon2){
double longitude1 = lon1;
double longitude2 = lon2;
double latitude1 = Math.toRadians(lat1);
double latitude2 = Math.toRadians(lat2);
double longDiff= Math.toRadians(longitude2-longitude1);
double y= Math.sin(longDiff)*Math.cos(latitude2);
double x=Math.cos(latitude1)*Math.sin(latitude2)-Math.sin(latitude1)*Math.cos(latitude2)*Math.cos(longDiff);
double calcBearing = (Math.toDegrees(Math.atan2(y, x))+360)%360;
return calcBearing;
}
public Coordinate calcCoordFromPointBearing(double lat1, double lon1, double bearing, double distance){
double rEarth = 6371.01; // Earth's average radius in km
double epsilon = 0.000001; // threshold for floating-point equality
double rLat1 = deg2rad(lat1);
double rLon1 = deg2rad(lon1);
double rbearing = deg2rad(bearing);
double rdistance = distance / rEarth;
double rlat = Math.asin( Math.sin(rLat1) * Math.cos(rdistance) + Math.cos(rLat1) * Math.sin(rdistance) * Math.cos(rbearing) );
double rlon;
if (Math.cos(rlat) == 0 || Math.abs(Math.cos(rlat)) < epsilon) // Endpoint a pole
rlon=rLon1;
else
rlon = ( (rLon1 - Math.asin( Math.sin(rbearing)* Math.sin(rdistance) / Math.cos(rlat) ) + Math.PI ) % (2*Math.PI) ) - Math.PI;
double lat = rad2deg(rlat);
double lon = rad2deg(rlon);
return new Coordinate(lat,lon);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
In short, I've screwed up the above calculations I believe. The behavior I'm seeing is the markers moving erratically and with a high frequency ending up heading towards two bearings: 90 and 270. As a result, they tend to move away from my anchor instead of towards it.
Can someone help me spot the mistake? I am passing in degrees to both the bearing function and the coordinate calculation function, but I'm converting them immediately to radians for the algorithm and back to degrees for usage elsewhere.
[UPDATE:
Most of the code came from this example:
Calculating coordinates given a bearing and a distance
It looks to me that the output longitude is being normalized to -180 to 180, which I'm plotting on a 360 degree space causing the outputs to head to the bearings 90 and 270. Any suggestions on the trig math change required to fix this?]
probably needs 360.0
double calcBearing = (Math.toDegrees(Math.atan2(y, x))+360.0)%360.0;
This was kindof answered here
You still have another issue. Your not considering any tilt in the map. Why not just animate with the pixels. There won't be too much distortion of curvature. What you have to do is get the pixel position of the marker. You'll have to save the latlon when adding the marker or you have to add the markers with .setAnchor which gives you an offset in pixels. If you have the latlon of the marker placement then you get the point by.
LatLon ll;
Point p = mMap.getProjection().toScreenLocation(ll);
Then you can use code like this to animate the markers. I'm making a marker bounce below by interpolating the y axis. You'll have to interpolate both axi.
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final long duration = 2500;
final Interpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = Math.max(
1 - interpolator.getInterpolation((float) elapsed
/ duration), 0);
marker.setAnchor(0.5f, 1.0f + 6 * t);
if (t > 0.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
The above code is from this question. I apologize for any performance issues you have when you use the above method. But you could still use the pixel positions for a more traditional animation approach.
I've got almost the same formulas as you working in another program where I animate a map to move to the expected location based on a location bearing and speed. The formula is slightly different at the end than yours. I lifted it from here and changed to longer names.
// Define the callback method that receives location updates
#Override
public void onLocationChanged(Location location) {
// Given the bearing, speed, and current location
// calculate what the expected location is traveling for an
// interval that is slightly larger than two times fastest interval of
// the location provider and animate the map movement to the
// expected location over the same slightly larger interval.
// In Theory by using an interval that is slightly larger
// than two times fastest interval of the location provider for the
// animation length a new animation will start before the
// currently running animation finishes. This should ensure a
// smooth animation of the map while traveling under most
// circumstances.
// Negative acceleration (braking)
// should have acceptable map animation because the map
// animation in theory never finishes.
// Note longer intervals, large negative accelerations, just
// braking at the start of an interval may result in the map moving
// backwards. But it will still be animated.
// Some handhelds might not be able to keep up
// TODO CHECK THE age of the location
// location.getSpeed() =meters/second
// interval 1/1000 seconds
// distance in radians km/6371
// changed.
// (location.getSpeed()m/s)(1/1000 interval seconds)( 1/1000 km/m)
// (1/6371 radians/km) = radians/6371000000.0
double expectedDistance = location.getSpeed() * expectedDistMultiplier;
// latitude in Radians
double currentLatitude = Math.toRadians(location.getLatitude());
// longitude in Radians
double longitude1 = Math.toRadians(location.getLongitude());
double bearing;
bearing = (location.hasBearing()) ? Math.toRadians(location
.getBearing()) : 0;
// calculate the expected latitude and longitude based on staring
// location
// , bearing, and distance
double expectedLatitude = Math.asin(Math.sin(currentLatitude)
* Math.cos(expectedDistance) + Math.cos(currentLatitude)
* Math.sin(expectedDistance) * Math.cos(bearing));
double a = Math.atan2(
Math.sin(bearing) * Math.sin(expectedDistance)
* Math.cos(currentLatitude),
Math.cos(expectedDistance) - Math.sin(currentLatitude)
* Math.sin(expectedLatitude));
double expectedLongitude = longitude1 + a;
expectedLongitude = (expectedLongitude + 3 * Math.PI) % (2 * Math.PI)
- Math.PI;
// convert to degrees for the expected destination
double expectedLongitudeDestination = Math.toDegrees(expectedLongitude);
double expectedLatitudeDestination = Math.toDegrees(expectedLatitude);
// log everything for testing.
Log.d("Location", "Bearing in radians" + bearing);
Log.d("Location", "distance in km" + expectedDistance);
Log.d("Location", "Current Latitude = " + location.getLatitude()
+ " Current Longitude = " + location.getLongitude());
Log.d("Location", "New Latitude = " + expectedLatitudeDestination
+ " New Longitude = " + expectedLongitudeDestination);
// build a camera update to animate positioning map to the expected
// destination
LatLng ll = new LatLng(expectedLatitudeDestination,
expectedLongitudeDestination);
CameraPosition.Builder cb = CameraPosition.builder()
.zoom(mMap.getCameraPosition().zoom)
.bearing(mMap.getCameraPosition().bearing)
.tilt(mMap.getCameraPosition().tilt).target(ll);
if (location.hasBearing()) {
cb.bearing(location.getBearing());
}
CameraPosition camera = cb.build();
CameraUpdate update = CameraUpdateFactory.newCameraPosition(camera);
mMap.animateCamera(update, interval, this);
}
I am using com.google.android.gms.maps.GoogleMap in SherlockFragmentActivity.
XML code is this :
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="fill_parent"
android:layout_height="150dip" />
int zoomLevel = ? // How I can calculate the zoom level for two diffrent latlong values
as android map v3 need to tell zoom level as int
map.setZoom(zoomLevel);
I have start and destination values as com.google.android.gms.maps.model.LatLng
LatLng start , end;
I am adding a pligon like GoogleLocation.addPolyLineOnGMap(mMap, startPoint, endPoint, startMarker, endMarker)
My problem is how I can calculate zoom level for Google map so it can show both marker appropriately on map.
Use LatLngBounds.Builder add all the bounds in it and build it, Then create the CameraUpdate object and pass the bounds in it updatefactory with padding. Use this CameraUpdate object to animate the map camera.
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker m : markers) {
builder.include(m.getPosition());
}
LatLngBounds bounds = builder.build();
int padding = ((width * 10) / 100); // offset from edges of the map
// in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
padding);
mMap.animateCamera(cu);
For me, i need to calculate the zoom for initial map setup by GoogleMapOptions, so using LatLngBounds.Builder
would not work and not optimized. This is how I calculate the zoom based on a city's northeast and southwest coordinates
It's referencing here and this answer, you can simply put the code below to your helper class:
final static int GLOBE_WIDTH = 256; // a constant in Google's map projection
final static int ZOOM_MAX = 21;
public static int getBoundsZoomLevel(LatLng northeast,LatLng southwest,
int width, int height) {
double latFraction = (latRad(northeast.latitude) - latRad(southwest.latitude)) / Math.PI;
double lngDiff = northeast.longitude - southwest.longitude;
double lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;
double latZoom = zoom(height, GLOBE_WIDTH, latFraction);
double lngZoom = zoom(width, GLOBE_WIDTH, lngFraction);
double zoom = Math.min(Math.min(latZoom, lngZoom),ZOOM_MAX);
return (int)(zoom);
}
private static double latRad(double lat) {
double sin = Math.sin(lat * Math.PI / 180);
double radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
}
private static double zoom(double mapPx, double worldPx, double fraction) {
final double LN2 = .693147180559945309417;
return (Math.log(mapPx / worldPx / fraction) / LN2);
}
Creating LatLng simply by new LatLng(lat-double, lng-double)
width and height is the map layout size in pixels
in Android:
LatLngBounds group = new LatLngBounds.Builder()
.include(tokio) // LatLgn object1
.include(sydney) // LatLgn object2
.build();
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(group, 100)); // Set Padding and that's all!
Is there a way to get the coordinates of the current area, which is shown at the device?
Background is, we want to show "nearby" places, which are stored in our own database. So let's say, the user looks at following clip of a map:
How do we get the longitude/latitude of the screen (or the point in the middle of the screen and a radius which covers everything?). Please keep in mind, center of the map is not usually the current position, since the user can move the center of the card!
Use map.getProjection().getVisibleRegion(). From VisibleRegion you can get LatLngBounds, which is easy to work with. You may also try directly with the region, which might be trapezoid.
I found the solution for Google Map API v2 from few of responses:
stackoverflow#1 and
stackoverflow#2
So, need implements Activity from GoogleMap.OnCameraChangeListener interface
private static final int REQUEST_CODE_GOOGLE_PLAY_SERVECES_ERROR = -1;
private static final double EARTH_RADIOUS = 3958.75; // Earth radius;
private static final int METER_CONVERSION = 1609;
private GoogleMap mGoogleMap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext);
if (status != ConnectionResult.SUCCESS)
{
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, activity,
REQUEST_CODE_GOOGLE_PLAY_SERVECES_ERROR);
dialog.show();
mGoogleMap = null;
}
else
{
mGoogleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(
R.id.fragment_shops_layout_maps_fragment)).getMap();
mGoogleMap.setOnCameraChangeListener(this);
}
}
The listener, that working when map scaled. Determin as LatLng the positions of bottom left, bottom right, top left and top right sides of map, that showing on screen. By greatest side of screen and two points we can get radius from center of map.
#Override
public void onCameraChange(CameraPosition cameraPosition)
{
// Listener of zooming;
float zoomLevel = cameraPosition.zoom;
VisibleRegion visibleRegion = mGoogleMap.getProjection().getVisibleRegion();
LatLng nearLeft = visibleRegion.nearLeft;
LatLng nearRight = visibleRegion.nearRight;
LatLng farLeft = visibleRegion.farLeft;
LatLng farRight = visibleRegion.farRight;
double dist_w = distanceFrom(nearLeft.latitude, nearLeft.longitude, nearRight.latitude, nearRight.longitude);
double dist_h = distanceFrom(farLeft.latitude, farLeft.longitude, farRight.latitude, farRight.longitude);
Log.d("DISTANCE: ", "DISTANCE WIDTH: " + dist_w + " DISTANCE HEIGHT: " + dist_h);
}
Return distance between 2 points, stored as 2 pair location at meters;
public double distanceFrom(double lat1, double lng1, double lat2, double lng2)
{
// Return distance between 2 points, stored as 2 pair location;
double dLat = Math.toRadians(lat2 - lat1);
double dLng = Math.toRadians(lng2 - lng1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = EARTH_RADIOUS * c;
return new Double(dist * METER_CONVERSION).floatValue();
}
If you want get radius of area, that showed on screen just need devided by 2.
I hope will useful !
This calculates the radio in km based on the map width:
public double calculateVisibleRadius() {
float[] distanceWidth = new float[1];
VisibleRegion visibleRegion = map.getProjection().getVisibleRegion();
LatLng farRight = visibleRegion.farRight;
LatLng farLeft = visibleRegion.farLeft;
LatLng nearRight = visibleRegion.nearRight;
LatLng nearLeft = visibleRegion.nearLeft;
//calculate the distance between left <-> right of map on screen
Location.distanceBetween( (farLeft.latitude + nearLeft.latitude) / 2, farLeft.longitude, (farRight.latitude + nearRight.latitude) / 2, farRight.longitude, distanceWidth );
// visible radius is / 2 and /1000 in Km:
return distanceWidth[0] / 2 / 1000 ;
}
I have a GroundOverlay on my GoogleMap and I want that its dimensions to not change when I zoom in/out on map. Exact like default map markers that always keep their dimensions. I have tried with both forms of the GroundOverlay.setDimensions() but the image is still resize on zoom. Here is my code:
Bitmap btm = BitmapFactory.decodeResource(getResources(), R.drawable.map_arrow);
BitmapDescriptor arrow = BitmapDescriptorFactory.fromBitmap(btm);
float w = btm.getWidth();
float h = btm.getHeight();
if (groundOverlay != null) groundOverlay.remove();
groundOverlay = mMap.addGroundOverlay(new GroundOverlayOptions()
.image(arrow).position(meLoc, w,h).bearing(bearAngle));
groundOverlay.setDimensions(1000);
you have your width and heigth of overlay and placed it on the map according to your zoom level. It seems good for that zoom level. Right? Now you can calculate radius and get meters of your map screen. Because map background overlay width and height values are meters. We have to go with meter not zoom level or anything else. Maybe someone can find a better solution but I have tried too many ways, and end up with this solution and it worked very well.
float zoomLevel=mMap.getCameraPosition().zoom;
//calculate meters*********************
myBounds = mMap.getProjection().getVisibleRegion().latLngBounds;
myCenter= mMap.getCameraPosition().target;
if (myCenter.latitude==0 || myCenter.longitude==0) {
myCenter=new LatLng(myLocation.getLatitude(),myLocation.getLongitude());
}
LatLng ne = myBounds.northeast;
// r = radius of the earth in statute miles
double r = 3963.0;
// Convert lat or lng from decimal degrees into radians (divide by 57.2958)
double lat1 = myCenter.latitude / 57.2958;
double lon1 = myCenter.longitude / 57.2958;
final double lat2 = ne.latitude / 57.2958;
final double lon2 = ne.longitude / 57.2958;
// distance = circle radius from center to Northeast corner of bounds
double dis = r * Math.acos(Math.sin(lat1) * Math.sin(lat2) +
Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1));
//1 Meter = 0.000621371192237334 Miles
double meters_calc=dis/0.000621371192237334;
float factor=1;
if (zoomLevel==15) { // my default zoom level yours can be different
metersoverlay=meters_calc; // global variable metersoverlay set
}
else { // if my zoom level change then I have to calculate dimension scale factor
factor=(float) (meters_calc/metersoverlay);
}
//******************************* now we are ready to set dimension of background overlay
float dimensions=1000*factor;
loadingGroundOverlayBg.setDimensions(dimensions);
I hope it works for all of you :)
I had the same issue. If you want to place an image, you can use the default markers provided by Google maps API. You can set a custom image as the marker icon, which will remain the same size.
private final List<BitmapDescriptor> mImages = new ArrayList<BitmapDescriptor>();
mImages.add(BitmapDescriptorFactory.fromResource(R.drawable.YOUR_IMAGE));
Marker marker = map.addMarker(new MarkerOptions().icon(mImages.get(0)));
This example shows how to set the icon of the marker, from an element of an image list. Hope it helps.
I'm working on an Android app that uses Geopoints and I want to determinate a Geopoint from another Geopoint, a distance (in any format) and a polar angle. For example, I want to get coordinates of a place 100 meters in the North-North-East (22,5 degres) of my location got by the GPS in my phone.
The only method I've found is Location.distanceBetween(...).
Implementation for Android. This code is great for Unit Testing in your aplication:
public double radiansFromDegrees(double degrees)
{
return degrees * (Math.PI/180.0);
}
public double degreesFromRadians(double radians)
{
return radians * (180.0/Math.PI);
}
public Location locationFromLocation(Location fromLocation, double distance, double bearingDegrees)
{
double distanceKm = distance / 1000.0;
double distanceRadians = distanceKm / 6371.0;
//6,371 = Earth's radius in km
double bearingRadians = this.radiansFromDegrees(bearingDegrees);
double fromLatRadians = this.radiansFromDegrees(fromLocation.getLatitude());
double fromLonRadians = this.radiansFromDegrees(fromLocation.getLongitude());
double toLatRadians = Math.asin( Math.sin(fromLatRadians) * Math.cos(distanceRadians)
+ Math.cos(fromLatRadians) * Math.sin(distanceRadians) * Math.cos(bearingRadians) );
double toLonRadians = fromLonRadians + Math.atan2(Math.sin(bearingRadians)
* Math.sin(distanceRadians) * Math.cos(fromLatRadians), Math.cos(distanceRadians)
- Math.sin(fromLatRadians) * Math.sin(toLatRadians));
// adjust toLonRadians to be in the range -180 to +180...
toLonRadians = ((toLonRadians + 3*Math.PI) % (2*Math.PI) ) - Math.PI;
Location result = new Location(LocationManager.GPS_PROVIDER);
result.setLatitude(this.degreesFromRadians(toLatRadians));
result.setLongitude(this.degreesFromRadians(toLonRadians));
return result;
}
Take a look at great-circle formulas: http://en.wikipedia.org/wiki/Great-circle_distance
This should give You some hints on how to calculate the distances.
For a point in a given distance and heading, check http://williams.best.vwh.net/avform.htm#LL
Those formulas look quite complicated, but are easy to implement ;)