I am using OSMdroid to show an offline map with user's current location.
1) PREFERRED - I would like to change the default icon showing current location to a custom icon. Also I need it to change its rotation based on bearing returned from GPS lets say every 5 seconds. The position of the icon should be in the center of the screen.
OR
2) possibility - rotating the map with custom current location icon fixed on the bottom of the screen.
Is there any way to do it in osmdroid?
Thanks.
1) that's been supported for a while with osmdroid. There are several my location type overlays and examples on how to use them. Depending on what version of osmdroid you're using, the mechanism to replace the default icon is a bit different.
2) there's a pull request open for osmdroid to support this feature. i'm pretty sure it allowed for the my location offset to be anywhere on the screen.
Seems like I figured out the first possibility.
I added a marker to the map which changes its position when onLocationChanged() is called. Also the map moves so the marker is in the center. Then I do marker.setRotation(bearing).
myLocationOverlay = new DirectedLocationOverlay(this);
Drawable d = ResourcesCompat.getDrawable(getResources(), R.drawable.direction_arrow, null);
Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
myLocationOverlay.setDirectionArrow(bitmap);
//code to change default location icon
map.getOverlays().add(myLocationOverlay);
need to implement onLocationChanged method
#Override
public void onLocationChanged(final Location pLoc) {
long currentTime = System.currentTimeMillis();
if (mIgnorer.shouldIgnore(pLoc.getProvider(), currentTime))
return;
double dT = currentTime - mLastTime;
if (dT < 100.0) {
//Toast.makeText(this, pLoc.getProvider()+" dT="+dT, Toast.LENGTH_SHORT).show();
return;
}
mLastTime = currentTime;
GeoPoint newLocation = new GeoPoint(pLoc);
if (!myLocationOverlay.isEnabled()) {
//we get the location for the first time:
myLocationOverlay.setEnabled(true);
map.getController().animateTo(newLocation);
}
GeoPoint prevLocation = myLocationOverlay.getLocation();
myLocationOverlay.setLocation(newLocation);
myLocationOverlay.setAccuracy((int) pLoc.getAccuracy());
if (prevLocation != null && pLoc.getProvider().equals(LocationManager.GPS_PROVIDER)) {
mSpeed = pLoc.getSpeed() * 3.6;
long speedInt = Math.round(mSpeed);
TextView speedTxt = findViewById(R.id.speed);
speedTxt.setText(speedInt + " km/h");
//TODO: check if speed is not too small
if (mSpeed >= 0.1) {
mAzimuthAngleSpeed = pLoc.getBearing();
myLocationOverlay.setBearing(mAzimuthAngleSpeed);
}
}
if (mTrackingMode) {
//keep the map view centered on current location:
map.getController().animateTo(newLocation);
map.setMapOrientation(-mAzimuthAngleSpeed);
} else {
//just redraw the location overlay:
map.invalidate();
}
if (mIsRecordingTrack) {
recordCurrentLocationInTrack("my_track", "My Track", newLocation);
}
}
Related
I have added current location via google map routing with
Routing routing = new Routing.Builder()
.travelMode(Routing.TravelMode.DRIVING)
.key(getResources().getString(R.string.google_maps_api))
.withListener(this)
.waypoints(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()), site_location)
.alternativeRoutes(false)
.build();
routing.execute();
#Override
public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex) {
if (polylines.size() > 0) {
for (Polyline poly : polylines) {
poly.remove();
}
}
polylines = new ArrayList<>();
//add route(s) to the map.
for (int i = 0; i < route.size(); i++) {
//In case of more than 5 alternative routes
int colorIndex = i % COLORS.length;
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(getResources().getColor(COLORS[colorIndex]));
polyOptions.width(10 + i * 13);
polyOptions.addAll(route.get(i).getPoints());
Polyline polyline = googleMap.addPolyline(polyOptions);
polylines.add(polyline);
int distance = route.get(i).getDistanceValue();
if (distance < 1000){
totalKm.setText( distance+" Metres");
}else {
totalKm.setText( (distance/1000) +" km");
}
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(new LatLng(mLastKnownLocation.getLatitude(), mLastKnownLocation.getLongitude()));
builder.include(site_marker.getPosition());
LatLngBounds bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 100);
googleMap.animateCamera(cu);
}
THis displays a driving directions like
But am trying to display the default google map driving icon with zoomed view like
How do i proceed to add such a map while still retaining the polylines to show driving view.
Jinesh Francis totally right in his answer: you should either run the default map Google Maps application through intent or modify the standard MapView (or MapFragment).
TLDR;
If you chose the second way - easiest approach is to use standard classes of Android Google Maps API to create view like in your example (other way is to create MapView-based custom view).
At first read carefully p 3.2.4 Restrictions Against Misusing the Services (d) of Google Maps Platform Terms of Service:
(d) No Re-Creating Google Products or Features. Customer will not use
the Services to create a product or service with features that are
substantially similar to or that re-create the features of another
Google product or service. Customer’s product or service must contain
substantial, independent value and features beyond the Google products
or services. For example, Customer will not: (i) re-distribute the
Google Maps Core Services or pass them off as if they were Customer’s
services; (ii) create a substitute of the Google Maps Core Services,
Google Maps, or Google Maps mobile apps, or their features; (iii) use
the Google Maps Core Services in a listings or directory service or to
create or augment an advertising product; (iv) combine data from the
Directions API, Geolocation API, and Maps SDK for Android to create
real-time navigation functionality substantially similar to the
functionality provided by the Google Maps for Android mobile app.
and if you not violate Terms of Service you can do what you want with that steps/tasks:
1) get user current location;
2) get a route path segment nearest to user current location (because user location rarely exactly on road);
3) get a azimuth (bearing) of this segment;
4) show map with route path and user current position marker with appropriate tilt and rotation according path segment bearing.
Task 1 can be solved like in this answer of Axxiss:
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
//your code here
}
};
Task 2 can be solved via PolyUtil.isLocationOnPath() like in that answer:
private LatLng getMarkerProjectionOnSegment(LatLng carPos, List<LatLng> segment, Projection projection) {
LatLng markerProjection = null;
Point carPosOnScreen = projection.toScreenLocation(carPos);
Point p1 = projection.toScreenLocation(segment.get(0));
Point p2 = projection.toScreenLocation(segment.get(1));
Point carPosOnSegment = new Point();
float denominator = (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y);
// p1 and p2 are the same
if (Math.abs(denominator) <= 1E-10) {
markerProjection = segment.get(0);
} else {
float t = (carPosOnScreen.x * (p2.x - p1.x) - (p2.x - p1.x) * p1.x
+ carPosOnScreen.y * (p2.y - p1.y) - (p2.y - p1.y) * p1.y) / denominator;
carPosOnSegment.x = (int) (p1.x + (p2.x - p1.x) * t);
carPosOnSegment.y = (int) (p1.y + (p2.y - p1.y) * t);
markerProjection = projection.fromScreenLocation(carPosOnSegment);
}
return markerProjection;
}
Task 3 can be solved with code like that:
private float getBearing(LatLng begin, LatLng end) {
double dLon = (end.longitude - begin.longitude);
double x = Math.sin(Math.toRadians(dLon)) * Math.cos(Math.toRadians(end.latitude));
double y = Math.cos(Math.toRadians(begin.latitude))*Math.sin(Math.toRadians(end.latitude))
- Math.sin(Math.toRadians(begin.latitude))*Math.cos(Math.toRadians(end.latitude)) * Math.cos(Math.toRadians(dLon));
double bearing = Math.toDegrees((Math.atan2(x, y)));
return (float) bearing;
}
where begin and end is begin and end of current route path segment.
Task 4 can be solved with code like that:
as marker you can use vector drawable of north oriented arrow like that:
ic_up_arrow_circle.xml (also you can adjust transparency and colors):
<vector android:height="24dp" android:viewportHeight="93.934"
android:viewportWidth="93.934"
android:width="24dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<path
android:fillColor="#8fFF0000"
android:pathData="m0,46.9666c0,25.939 21.028,46.967 46.967,46.967c25.939,-0 46.967,-21.028 46.967,-46.967c0,-25.939 -21.027,-46.967 -46.967,-46.967c-25.939,-0 -46.967,21.028 -46.967,46.967zM78.262,67.4396l-31.295,-16.845l-31.295,16.845l31.295,-51.614l31.295,51.614z"
/>
<path
android:fillColor="#FFFFFF"
android:pathData="M78.262,67.4396l-31.295,-16.845l-31.295,16.845l31.295,-51.614l31.295,51.614z"
/>
</vector>
and you can place it on map with code like that:
public Marker addDirectionMarker(LatLng latLng, float angle) {
Drawable circleDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_up_arrow_in_circle);
BitmapDescriptor markerIcon = getMarkerIconFromDrawable(circleDrawable, 150, 150);
return mGoogleMap.addMarker(new MarkerOptions()
.position(latLng)
.anchor(0.5f, 0.5f)
.rotation(angle)
.flat(true)
.icon(markerIcon)
);
}
where 150 is marker size in pixels. NB! You need flat marker for its rotation and tilt with map and 0.5f for move marker anchor exactly on its center point.
then you can show all of this on map:
...
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(userPosition)
.tilt(tilt)
.zoom(zoom)
.bearing(bearing)
.build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
...
But if you do only that marker of user current position appeared in the center of screen (because GoogleMap.moveCamera() sets the center exactly at .target()). So, to avoid it you need to shift down the map slightly - in that case user location marker should be appeared at the bottom of screen. For map center shift you need get current map center screen coordinates, then change y coordinate and get new screen center. Something like that:
...
LatLng mapCenter = mGoogleMap.getCameraPosition().target;
Projection projection = mGoogleMap.getProjection();
Point centerPoint = projection.toScreenLocation(mapCenter);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int displayHeight = displayMetrics.heightPixels;
centerPoint.y = centerPoint.y - (int) (displayHeight / 4.5); // move center down for approx 22%
LatLng newCenterPoint = projection.fromScreenLocation(centerPoint);
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(newCenterPoint, zoom));
...
And with all of this stuff, for your route (with zoom = 15 and tilt = 50) you should get something like that:
As you can see, the route path is not exactly on road, so you need to get route path points more precisely than Directions API response. You can get that e.g. via Google Maps Roads API part Snap to Road which
returns the best-fit road geometry for a given set of GPS coordinates.
This service takes up to 100 GPS points collected along a route, and
returns a similar set of data with the points snapped to the most
likely roads the vehicle was traveling along.
like in that answer. If your route path has more than points you need to split in into 100-points portions and process them separately (also Snap to Road API has 2500 request per day per user (IP) and 10 requests per sec. restriction).
And as Jaswant Singh answered you:
need to set a custom marker (with icon same as that blue arrow) on
your current location and move it to the new location every time there
is onLocationChanged() callback is called (Also animate the camera to
that new location).
Also, you need to select zoom and tilt properties according, for example, current user speed: when user drives faster tilt -> 0. And so on. It's not a simple task.
In addition to Jinesh’s answer,
If you still want to add that marker for development, you need to set a custom marker (with icon same as that blue arrow) on your current location and move it to the new location every time there is onLocationChanged() callback is called (Also animate the camera to that new location).
And tilt the map a little to get the exact look of the google maps navigation view, though you won’t get to use all the functionalities but it’s worth to give it a try.
When I click on polyline I want time (custom object) to be displayed at that particular lat long position.
Code to achieve polyline
PolylineOptions lineOptions = new PolylineOptions().width(7).color(Color.BLACK).geodesic(true);
for (int i = 0; i < points.size(); i++) {
LatLng latLng1 = new LatLng(Double.parseDouble(points.get(i).getmLatitude()), Double.parseDouble(points.get(i).getmLongitude()));
lineOptions.add(latLng1);
}
if (mPolyline != null) {
mPolyline.remove();
}
mPolyline = mMap.addPolyline(lineOptions);
mPolyline.setClickable(true);
for (int i = 0; i < points.size(); i++) {
//setting tags to be used on ployline click
mPolyline.setTag(points.get(i).getTime());
}
List<PatternItem> pattern = Arrays.asList(
new Gap(15), new Dash(15), new Gap(15));
mPolyline.setPattern(pattern);
mPolyline.setJointType(JointType.ROUND);
Now when I click on polyline I get only one tag which is same for all. I want unique tags(custom objects) for every polyline position which relate to lat long
mMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() {
#Override
public void onPolylineClick(Polyline polyline) {
Toast.makeText(mContext, (String) polyline.getTag(), Toast.LENGTH_SHORT).show();
}
});
Thanks for contributing :)
EDIT
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
boolean isOnRoute = PolyUtil.isLocationOnPath(latLng, lineOptions.getPoints(), false, 25);
if (isOnRoute) {
for (LocationVo mCoordinates : points) {
double distanceInMeters = SphericalUtil.computeDistanceBetween(latLng, mCoordinates.getmLatLong());
boolean isWithin50m = distanceInMeters < 50;
if (isWithin50m) {
Toast.makeText(mContext, mCoordinates.getTime(), Toast.LENGTH_SHORT).show();
break;
}
}
}
}
});
Not all my polylines match with the conditions and show no toast on click
With a tolerance of 25 meters you are defining a corridor along each path segment 25 meters on either side. So as implemented, all this tells you is the click point is somewhere in the corridor centered on the path - or effectively they've clicked on the polyline with some room for error.
The problem you are having is in your assumption that you'll always be within 50 meters of a point - this is incorrect and also not what you want as best as I can tell. By definition, once isOnRoute is true, you always want to find a point since by definition they've clicked on the polyline; this is done (inefficiently) by simply calculating all distances from click-point to all polyline points and determining the shortest distance (a simple loop
with a min logic); then use this point for your toast.
Now if you really wanted to limit what are considered "successful" clicks, where a successful click is both "on the polyline" and "near a point" then your distance check would be added using some acceptable value - this would be in effect defining a "box" around each point with dimensions 50 meters (25 x 2)-by-whatever your distance check is. Note this is not the same as just checking a radius circle around each point unless the radius of the desired circle is equivalent to the polyline tolerance.
(One other trivial point - your mixing measurement systems when using false for geodesic and then computing spherical distance - but should not be an issue with your implementation.) (If helpful I'll add a picture later.)
Summary of modification: "check if user clicks along the polyline" AND "determine closest point along line" AND "display some toast for that point".
So make this modification after isOnRoute is true:
LocationVo closestPoint = null;
double minDist = -1;
for (LocationVo mCoordinates : points) {
double distanceInMeters = SphericalUtil.computeDistanceBetween(latLng, mCoordinates.getmLatLong());
if (minDist < 0 || distanceInMeters < minDist) {
minDist = distanceInMeters;
closestPoint = mCoordinates;
}
}
if (closestPoint != null) {
Toast.makeText(mContext, closestPoint.getTime(), Toast.LENGTH_SHORT).show();
}
To implement the "box" discussed above around each point modify the one condition:
if ((distanceInMeters < MAX_DISTANCE_FROM_POINT) && (minDist < 0 || distanceInMeters < minDist)) {
Note this means in some cases you will not get a toast even if they clicked along the polyline.
I use Google Maps in an app and it is likely that multiple markers are attached to same location where each marker represent a person. In this situation user will not know that there are other markers/persons behind this particular marker.
I looked around to handle this situation and one question on SO suggests that I can display a single marker and associate all persons with that single marker. When user taps that marker I should display a list of all the user associated with that marker. This is a good workaround but I would want to avoid displaying a view that mostly hides Google Maps.
Has anyone used any workaround in similar situation?
Workaround I used is to display markers with same location little bit apart on map so that user gets a slight idea of multiple marker.
I keep track of markers on map and their locations on map, and whenever I want to add a marker on map I make sure that no other marker is displayed on same location. If yes, then I add an offset to location of new marker that I want to add.
static final float COORDINATE_OFFSET = 0.00002f; // You can change this value according to your need
Below method returns the location that has to be used for new marker. This method takes as parameters new marker's current latitude and longitude.
// Check if any marker is displayed on given coordinate. If yes then decide
// another appropriate coordinate to display this marker. It returns an
// array with latitude(at index 0) and longitude(at index 1).
private String[] coordinateForMarker(float latitude, float longitude) {
String[] location = new String[2];
for (int i = 0; i <= MAX_NUMBER_OF_MARKERS; i++) {
if (mapAlreadyHasMarkerForLocation((latitude + i
* COORDINATE_OFFSET)
+ "," + (longitude + i * COORDINATE_OFFSET))) {
// If i = 0 then below if condition is same as upper one. Hence, no need to execute below if condition.
if (i == 0)
continue;
if (mapAlreadyHasMarkerForLocation((latitude - i
* COORDINATE_OFFSET)
+ "," + (longitude - i * COORDINATE_OFFSET))) {
continue;
} else {
location[0] = latitude - (i * COORDINATE_OFFSET) + "";
location[1] = longitude - (i * COORDINATE_OFFSET) + "";
break;
}
} else {
location[0] = latitude + (i * COORDINATE_OFFSET) + "";
location[1] = longitude + (i * COORDINATE_OFFSET) + "";
break;
}
}
return location;
}
// Return whether marker with same location is already on map
private boolean mapAlreadyHasMarkerForLocation(String location) {
return (markerLocation.containsValue(location));
}
In above code, markerLocation is a HashMap.
HashMap<String, String> markerLocation; // HashMap of marker identifier and its location as a string
This answer has code for android but same logic applies in iOS.
Maybe you should take a look at marker clustering. It's a common solution for showing a lot of markers on the same place.
Google article about it: https://developers.google.com/maps/articles/toomanymarkers
There are also existing libraries to do this, e.g.:
https://code.google.com/p/android-maps-extensions/
https://github.com/twotoasters/clusterkraf
You could handle the click event of the (single) marker, and use it to update an element that sits outside of the Google Map canvas with the details about the people at that marker.
Giving offset will make the markers faraway when the user zoom in to max. So i found a way to achieve that. this may not be a proper way but it worked very well.
for loop markers
{
//create marker
let mapMarker = GMSMarker()
mapMarker.groundAnchor = CGPosition(0.5, 0.5)
mapMarker.position = //set the CLLocation
//instead of setting marker.icon set the iconView
let image:UIIMage = UIIMage:init(named:"filename")
let imageView:UIImageView = UIImageView.init(frame:rect(0,0, ((image.width/2 * markerIndex) + image.width), image.height))
imageView.contentMode = .Right
imageView.image = image
mapMarker.iconView = imageView
mapMarker.map = mapView
}
set the zIndex of the marker so that you will see the marker icon which you want to see on top, otherwise it will animate the markers like auto swapping.
when the user tap the marker handle the zIndex to bring the marker on top using zIndex Swap.
Inspired by the Geek's answer, I created a function. This function returns a new latitude longitude pair, nearby the original value, almost in a circular fashion. COORINDATE_OFFSET is adjustable based on the need.
private static final float COORDINATE_OFFSET = 0.000085f;
private ArrayList<LatLng> markerCoordinates = new ArrayList<>();
private int offsetType = 0;
private LatLng getLatLng(LatLng latLng) {
LatLng updatedLatLng;
if (markerCoordinates.contains(latLng)) {
double latitude = 0;
double longitude = 0;
if (offsetType == 0) {
latitude = latLng.latitude + COORDINATE_OFFSET;
longitude = latLng.longitude;
} else if (offsetType == 1) {
latitude = latLng.latitude - COORDINATE_OFFSET;
longitude = latLng.longitude;
} else if (offsetType == 2) {
latitude = latLng.latitude;
longitude = latLng.longitude + COORDINATE_OFFSET;
} else if (offsetType == 3) {
latitude = latLng.latitude;
longitude = latLng.longitude - COORDINATE_OFFSET;
} else if (offsetType == 4) {
latitude = latLng.latitude + COORDINATE_OFFSET;
longitude = latLng.longitude + COORDINATE_OFFSET;
}
offsetType++;
if (offsetType == 5) {
offsetType = 0;
}
updatedLatLng = getLatLng(new LatLng(latitude, longitude));
} else {
markerCoordinates.add(latLng);
updatedLatLng = latLng;
}
return updatedLatLng;
}
I really like the accepted answer, but I believe it uses to much code. Here's a variation in JavaScript, you can try it in you browser's console:
var positions = Array([46,-2],[46,-2],[46,-2],[46.3,-2.1]);
var used_locations = [];
for (let position of positions) {
while (used_locations.includes(position[0].toString() + position[1].toString())) {
let lat = position[0];
let lng = position[1] * 1.001;
position = [lat, lng];
}
used_locations.push(position[0].toString() + position[1].toString());
//add_marker(position);
}
console.log(used_locations);
When a marker is clicked, the default behavior for the camera is to center it on screen, but because I usually have long text description in the info window, it's more convenient to actually change the camera position so that the marker is on the bottom of screen(making the info window in the center of screen). I think I should be able to do that by overriding onMarkerClick function like below (the default behavior is cancelled when this function return true)
#Override
public boolean onMarkerClick(final Marker marker) {
// Google sample code comment : We return false to indicate that we have not
// consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move
// such that the
// marker is centered and for the marker's info window to open, if it
// has one).
marker.showInfoWindow();
CameraUpdate center=
CameraUpdateFactory.newLatLng(new LatLng(XXXX,
XXXX));
mMap.moveCamera(center);//my question is how to get this center
// return false;
return true;
}
Edit:
Problem solved using accepted answer's steps, codes below:
#Override
public boolean onMarkerClick(final Marker marker) {
//get the map container height
LinearLayout mapContainer = (LinearLayout) findViewById(R.id.map_container);
container_height = mapContainer.getHeight();
Projection projection = mMap.getProjection();
LatLng markerLatLng = new LatLng(marker.getPosition().latitude,
marker.getPosition().longitude);
Point markerScreenPosition = projection.toScreenLocation(markerLatLng);
Point pointHalfScreenAbove = new Point(markerScreenPosition.x,
markerScreenPosition.y - (container_height / 2));
LatLng aboveMarkerLatLng = projection
.fromScreenLocation(pointHalfScreenAbove);
marker.showInfoWindow();
CameraUpdate center = CameraUpdateFactory.newLatLng(aboveMarkerLatLng);
mMap.moveCamera(center);
return true;
}
Thanks for helping ^ ^
I might edit this answer later to provide some code, but what I think could work is this:
Get LatLng (LatLng M) of the clicked marker.
Convert LatLng M to a Point (Point M) using the Projection.toScreenLocation(LatLng) method. This gives you the location of the marker on the device's display (in pixels).
Compute the location of a point (New Point) that's above Point M by half of the map's height.
Convert the New Point back to LatLng and center the map on it.
Look here for my answer on how to get the map's height.
// googleMap is a GoogleMap object
// view is a View object containing the inflated map
// marker is a Marker object
Projection projection = googleMap.getProjection();
LatLng markerPosition = marker.getPosition();
Point markerPoint = projection.toScreenLocation(markerPosition);
Point targetPoint = new Point(markerPoint.x, markerPoint.y - view.getHeight() / 2);
LatLng targetPosition = projection.fromScreenLocation(targetPoint);
googleMap.animateCamera(CameraUpdateFactory.newLatLng(targetPosition), 1000, null);
I prefer Larry McKenzie's answer which it doesn't depend on screen projection (i.e. mProjection.toScreenLocation()), my guess is the projection resolution will go poor when the map zoom level is low, it made me sometimes couldn't get an accurate position. So, calculation based on google map spec will definitely solve the problem.
Below is an example code of moving the marker to 30% of the screen size from bottom.
zoom_lvl = mMap.getCameraPosition().zoom;
double dpPerdegree = 256.0*Math.pow(2, zoom_lvl)/170.0;
double screen_height = (double) mapContainer.getHeight();
double screen_height_30p = 30.0*screen_height/100.0;
double degree_30p = screen_height_30p/dpPerdegree;
LatLng centerlatlng = new LatLng( latlng.latitude + degree_30p, latlng.longitude );
mMap.animateCamera( CameraUpdateFactory.newLatLngZoom( centerlatlng, 15 ), 1000, null);
If you don't care about the map zooming in and just want the marker to be at the bottom see below, I think it's a simpler solution
double center = mMap.getCameraPosition().target.latitude;
double southMap = mMap.getProjection().getVisibleRegion().latLngBounds.southwest.latitude;
double diff = (center - southMap);
double newLat = marker.getPosition().latitude + diff;
CameraUpdate centerCam = CameraUpdateFactory.newLatLng(new LatLng(newLat, marker.getPosition().longitude));
mMap.animateCamera(centerCam);
I had the same issue, I tried the following perfectly working solution
mMap.setOnMarkerClickListener(new OnMarkerClickListener()
{
#Override
public boolean onMarkerClick(Marker marker)
{
int yMatrix = 200, xMatrix =40;
DisplayMetrics metrics1 = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics1);
switch(metrics1.densityDpi)
{
case DisplayMetrics.DENSITY_LOW:
yMatrix = 80;
xMatrix = 20;
break;
case DisplayMetrics.DENSITY_MEDIUM:
yMatrix = 100;
xMatrix = 25;
break;
case DisplayMetrics.DENSITY_HIGH:
yMatrix = 150;
xMatrix = 30;
break;
case DisplayMetrics.DENSITY_XHIGH:
yMatrix = 200;
xMatrix = 40;
break;
case DisplayMetrics.DENSITY_XXHIGH:
yMatrix = 200;
xMatrix = 50;
break;
}
Projection projection = mMap.getProjection();
LatLng latLng = marker.getPosition();
Point point = projection.toScreenLocation(latLng);
Point point2 = new Point(point.x+xMatrix,point.y-yMatrix);
LatLng point3 = projection.fromScreenLocation(point2);
CameraUpdate zoom1 = CameraUpdateFactory.newLatLng(point3);
mMap.animateCamera(zoom1);
marker.showInfoWindow();
return true;
}
});
I also faced this problem and fixed it in a hacky way. Let's declare a double field first. You need to adjust the value of it based on your requirement but I recommend you keep it between 0.001~0.009 otherwise you can miss your marker after the zoom animation.
double offset = 0.009
/*You can change it based on your requirement.
For left-right alignment please kindly keep it between 0.001~0.005 */
For bottom-centered:
LatLng camera = new LatLng(marker.getPosition().latitude+offset , marker.getPosition().longitude);
//Here "marker" is your target market on which you want to focus
For top-centered:
LatLng camera = new LatLng(marker.getPosition().latitude-offset , marker.getPosition().longitude);
For left-centered:
LatLng camera = new LatLng(marker.getPosition().latitude, marker.getPosition().longitude+offset);
For right-centered:
LatLng camera = new LatLng(marker.getPosition().latitude-offset , marker.getPosition().longitude-offset);
Then finally call the -
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(camera, yourZoom));
I did a little research and according to the documentation the map is square and at zero zoom level the width and height is 256dp and +/- 85 degrees N/S. The map width increases with zoom level so that width and height = 256 * 2N dp. Where N is the zoom level. So in theory you can determine the new location by getting the map height and dividing it by 170 total degrees to get dp per degree. Then get the screen height (or mapview height) in dp divided it by two and convert half view size to degrees of latitude. Then set your new Camera point that many degrees of latitude south. I can add code if you need it but I'm on a phone at the moment.
I have been trying out all the solutions proposed here, and came with a combined implementation of them. Considering, map projection, tilt, zoom and info window height.
It doesn't really place the marker at the bottom of the "camera view", but I think it accommodates the info window and the marker centre pretty well in most cases.
#Override
public boolean onMarkerClick(Marker marker) {
mIsMarkerClick = true;
mHandler.removeCallbacks(mUpdateTimeTask);
mLoadTask.cancel(true);
getActivity().setProgressBarIndeterminateVisibility(false);
marker.showInfoWindow();
Projection projection = getMap().getProjection();
Point marketCenter = projection.toScreenLocation(marker.getPosition());
float tiltFactor = (90 - getMap().getCameraPosition().tilt) / 90;
marketCenter.y -= mInfoWindowAdapter.getInfoWindowHeight() / 2 * tiltFactor;
LatLng fixLatLng = projection.fromScreenLocation(marketCenter);
mMap.animateCamera(CameraUpdateFactory.newLatLng(fixLatLng), null);
return true;
}
And then, your custom adapter would have to keep an instance of the info window inflated view, to be able to fetch its height.
public int getInfoWindowHeight(){
if (mLastInfoWindoView != null){
return mLastInfoWindoView.getMeasuredHeight();
}
return 0;
}
Anyone who's still looking to center the camera according to location coordinates
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(Lat, Lon))
.zoom(15)
.bearing(0)
.tilt(45)
.build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Credits
After some experiences i've implemented the solution that fine for me.
DisplayMetrics metrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(metrics);
Point targetPoint = new Point(metrics.widthPixels / 2, metrics.heightPixels - metrics.heightPixels / 9);
LatLng targetLatlng = map.getProjection().fromScreenLocation(targetPoint);
double fromCenterToTarget = SphericalUtil.computeDistanceBetween(map.getCameraPosition().target, targetLatlng);
LatLng center = SphericalUtil.computeOffset(new LatLng(location.latitude, location.longitude), fromCenterToTarget/1.2, location.bearing);
CameraUpdate camera = CameraUpdateFactory.newLatLng(center);
map.animateCamera(camera, 1000, null);
Here. First, we pick the physical point on the screen where the marker should be moved. Then, convert it to LatLng. Next step - calculate distance from current marker position (in center) to target. Finally, we move the center of map straight from the marker to calculated distance.
I needed something similar, but with also zoom, tilt and bearing in the equation.
My problem is more complex, but the solution is a sort of generalization so it could be applied also to the problem in the question.
In my case, I update programmatically the position of a marker; the camera can be rotated, zoomed and tilted, but I want the marker always visible at a specific percentage of the View height from the bottom. (similar to the car marker position in the Maps navigation)
The solution:
I first pick the map location on the center of the screen and the location of a point that would be visible at a percentage of the View from the bottom (using map projection); I get the distance between these two points in meters, then I calculate a position, starting from the marker position, moving for the calculated distance towards the bearing direction; this new position is my new Camera target.
The code (Kotlin):
val movePointBearing =
if (PERCENTAGE_FROM_BOTTOM > 50) {
(newBearing + 180) % 360
} else newBearing
val newCameraTarget = movePoint(
markerPosition,
distanceFromMapCenter(PERCENTAGE_FROM_BOTTOM),
markerBearing)
with the movePoint method copied from here:
https://stackoverflow.com/a/43225262/2478422
and the distanceFromMapCenter method defined as:
fun distanceFromMapCenter(screenPercentage: Int): Float {
val screenHeight = mapFragment.requireView().height
val screenWith = mapFragment.requireView().width
val projection = mMap.projection
val center = mMap.cameraPosition.target
val offsetPointY = screenHeight - (screenHeight * screenPercentage / 100)
val offsetPointLocation = projection.fromScreenLocation(Point(screenWith / 2, offsetPointY))
return distanceInMeters(center, offsetPointLocation)
}
then just define a distanceInMeters method (for example using android Location class)
I hope the idea is clear without any further explanations.
One obvious limitation: it applies the logic using the current zoom and tilt, so it would not work if the new camera position requires also a different zoom_level and tilt.
I am using a customised version of the mapview (OSMDroid version).
I am using custom tiles within it and I only want the user to be able to view the area where I have my custom tiles.
Is there a way to set the boundary lat longs so when they pan the map it doesn't go past these boundaries?
Update: I know this is an old question, but osmdroid now has a setScrollableAreaLimit() method that will achieve what you are looking for. There is also a setMinZoomLevel() and setMaxZoomLevel() method to easily restrict zoom levels.
Original answer:
Please keep an eye on:
http://code.google.com/p/osmdroid/issues/detail?id=209
A patch has already been created, and will likely be integrated shortly.
This is cross-posted from the osmdroid thread. There's now lists a BoundedMapView class, which implements the afortementioned patch.
For those of use using the .jar or otherwise not that familiar with
patches, I cobbled together a subclass of MapView that supports
limiting the user's view to a specific area.
Details on how to use it,
if not obvious, can be found at
http://www.sieswerda.net/2012/08/15/boundedmapview-a-mapview-with-limits/
Incase it helps anyone....
I have sort of a solution that I am using, it works ok, but could definitely be better as the map can go abit too far off the screen before it jumps back!
It uses the lat longs and works out where the map is, I set 4 coordinates which are roughly the 4 corners of the map I have found it works better if you set them slightly into the map rather exactly the corners, I then work out if the lat longs have left the screen completely.. if so it will bounce it halfway back:
I overrode the mapview and the OnTouch event of the map
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP) {
// (only works for north of equator)
// * map right side (lat) can't go past the left (lat) of screen
// get geopoints of the 4 corners of the screen
Projection proj = getProjection();
GeoPoint screenTopLeft = proj.fromPixels(0, 0);
GeoPoint screenTopRight = proj.fromPixels(getWidth(), 0);
GeoPoint screenBottomLeft = proj.fromPixels(0, getHeight());
double screenTopLat = screenTopLeft.getLatitudeE6() / 1E6;
double screenBottomLat = screenBottomLeft.getLatitudeE6() / 1E6;
double screenLeftlong = screenTopLeft.getLongitudeE6() / 1E6;
double screenRightlong = screenTopRight.getLongitudeE6() / 1E6;
double mapTopLat = BoundsTopLeftCorner.getLatitudeE6() / 1E6;
double mapBottomLat = BoundsBottomLeftCorner.getLatitudeE6() / 1E6;
double mapLeftlong = BoundsTopLeftCorner.getLongitudeE6() / 1E6;
double mapRightlong = BoundsTopRightCorner.getLongitudeE6() / 1E6;
// screen bottom greater than map top
// screen top less than map bottom
// screen right less than map left
// screen left greater than map right
boolean movedLeft = false;
boolean movedRight = false;
boolean movedUp = false;
boolean movedDown = false;
boolean offscreen = false;
if (screenBottomLat > mapTopLat) {
movedUp = true;
offscreen = true;
}
if (screenTopLat < mapBottomLat) {
movedDown = true;
offscreen = true;
}
if (screenRightlong < mapLeftlong) {
movedLeft = true;
offscreen = true;
}
if (screenLeftlong > mapRightlong) {
movedRight = true;
offscreen = true;
}
if (offscreen) {
// work out on which plane it's been moved off screen (lat/lng)
if (movedLeft || movedRight) {
double newBottomLat = screenBottomLat;
double newTopLat = screenTopLat;
double centralLat = newBottomLat
+ ((newTopLat - newBottomLat) / 2);
if (movedRight)
this.getController().setCenter(
new GeoPoint(centralLat, mapRightlong));
else
this.getController().setCenter(
new GeoPoint(centralLat, mapLeftlong));
}
if (movedUp || movedDown) {
// longs will all remain the same
double newLeftLong = screenLeftlong;
double newRightLong = screenRightlong;
double centralLong = (newRightLong + newLeftLong) / 2;
if (movedUp)
this.getController().setCenter(
new GeoPoint(mapTopLat, centralLong));
else
this.getController().setCenter(
new GeoPoint(mapBottomLat, centralLong));
}
}
}
return super.onTouchEvent(ev);
}}
A few things I should point out if you are considering using this:
I make no guarentees that it will work for your situation and you should only use it as a starting point.
It will only work for areas north of the equator (I think) due to the way I've done the coords!
It works on the "action up" of the touch event, so it takes the point where the user takes their finger off the screen. This means when the map flings it's completely inaccurate as I could not work out where the map stopped, because of this I turned off the fling by overriding the fling event and not doing anything in it.. this does make the map a bit jolty!
If anyone has any better solutions or can improve my code please feel free!
I'm looking for exactly the same thing.
My best lead is to add an Overlay, which extends boolean onScroll(...). If this returns true, then the scroll is cancelled.
This is exactly how I want it, except for one thing: flinging/flicking. The same approach can be used to cancel fling events, though you only get to hear about it at the start of the fling.
Ideally, you'd be able to listen to the computeScroll() method, and limit the (x, y) of the scroll, based on mScroller.getCurX() and mScroller.getCurY().