Android set GoolgeMap bounds from database of points - android

Using Google Maps Android API v2, I am trying to set the bounds of the map using LatLngBounds.Builder() with points from a database. I think I am close, however the activity is crashing because I don't think I am properly loading the points. I may be just a couple of lines away.
//setup map
private void setUpMap() {
//get all cars from the datbase with getter method
List<Car> K = db.getAllCars();
//loop through cars in the database
for (Car cn : K) {
//add a map marker for each car, with description as the title using getter methods
mapView.addMarker(new MarkerOptions().position(new LatLng(cn.getLatitude(), cn.getLongitude())).title(cn.getDescription()));
//use .include to put add each point to be included in the bounds
bounds = new LatLngBounds.Builder().include(new LatLng(cn.getLatitude(), cn.getLongitude())).build();
//set bounds with all the map points
mapView.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
}
}
I think there may be an error in how I arranged the for loop to get all the cars, if I remove the bounds statements the map point are plotted correctly as I expected but not bounding the map properly.

you are creating a new LatLngBounds.Builder() everytime in the loop.
try this
private LatLngBounds.Builder bounds;
//setup map
private void setUpMap() {
bounds = new LatLngBounds.Builder();
//get all cars from the datbase with getter method
List<Car> K = db.getAllCars();
//loop through cars in the database
for (Car cn : K) {
//add a map marker for each car, with description as the title using getter methods
mapView.addMarker(new MarkerOptions().position(new LatLng(cn.getLatitude(), cn.getLongitude())).title(cn.getDescription()));
//use .include to put add each point to be included in the bounds
bounds.include(new LatLng(cn.getLatitude(), cn.getLongitude()));
}
//set bounds with all the map points
mapView.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), 50));
}

Related

Get number of markers shown in Maps Android

I am showing a list of n markers in a map, then I make zoom to my location and I would like to know if its possible to count just how many markers are displayed in my area.
Thanks.
You can call below method for each marker to see if they are inside the Maps visible area.
map.getBounds().contains(marker.getPosition())
If the getBounds method is not available try this:
VisibleRegion region = map.getProjection().getVisibleRegion();
LatLngBounds mapBound = region.latLngBounds;
int count 0;
for(Marker marker : makers) { // markers is the List of marker you have
if(mapBound.contains(marker.getPosition()){
count = count + 1;
}
}
You can keep a List of marker within your Activity or Fragment and then do a loop on it to see if its in the visible area List.size() to get the number of marker.
private List<Marker> mMarkerArray = new ArrayList<Marker>();
///to get number of marker
int marker_count = = 0;
for(int i =0;i<=mMarkerArray.size();i++){
if(mMap.latLngBounds.contains(new LatLng(mMarkerArray.get(i).getLocation().getLongitude(), mMarkerArray.get(i).getLocation().getLatitude())){
marker_count++;
}
}
just make sure you add the marker in the list after you add it to your map object

Find Marker by Tag Google Maps API (Android)

How/Where could I get a reference of all marker objects current on the map, in order to check something like this:
if (Markers.getTag().equals("something"))
By reading the documentation on Marker it said "This is easier than storing a separate Map", so I don't want to use HashMap unless someone say I absolutely have to.
Thanks, the following is a pseudo-pseudo code
// The uid is the Marker's tag
// 1) Someway to Check if the tag exists for the current profile
// 2) If it exists, then just move the marker, just set a new position of this marker.
// 3) If it doesn't, then create a new marker, add a marker.
// 4) Set profile uid as the Marker's Tag, via .setTag()
// 5) Animate move camera to the latlng position
3-5 is okay, just 1-2
// 3) Create a new marker
// Marker to show on the map
Marker friendMarker;
// Add a marker when the image is loaded
friendMarker = googleMap.addMarker(new MarkerOptions()
.position(friendLatLng)
.icon(BitmapDescriptorFactory.fromBitmap(bitmap))
.title(friendProfile.getName()));
// Set the tag on this friend marker, so we can retrieve or update it later
friendMarker.setTag(friendProfile.getUid());
// 5) Animate the camera to that location
CameraPosition cameraPosition = new CameraPosition.Builder().target(friendLatLng).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Create a List of Marker
List<Marker> markers = new ArrayList<>();
Then add your marker in your markers list
// Marker to show on the map
Marker friendMarker;
// Add a marker when the image is loaded
friendMarker = googleMap.addMarker(new MarkerOptions()
.position(friendLatLng)
.icon(BitmapDescriptorFactory.fromBitmap(bitmap))
.title(friendProfile.getName()));
//Add now the marker in markers list
markers.add(friendMarker);
Then to access all markers
for (Marker marker : markers) {
if (marker.getTag().equals("something")) { //if a marker has desired tag
//Do something in the way. Hmmmm. Yeah
}
}

Android - GoogleMapAPI v2 marker icons out of bounds

actually I'm working on an android application using the Google Map APIv2, so far I'm trying to display some markers on a the map, also i want to have all the markers inside my camera view, for this I'm using
LatLngBounds.Builder builder = new LatLngBounds.Builder();
LatLngBounds bounds;
int padding = 0;
//markMap is a hashmap populated with my markers positions.
HashMap<String, LatLng> markMap = new HashMap<String, LatLng>();
for (Entry<String, LatLng> entry : markMap.entrySet())
{
map.addMarker(new MarkerOptions().position(entry.getValue()));
builder.include(entry.getValue());
}
bounds = builder.build();
CameraUpdate update = CameraUpdateFactory.newLatLngBounds(bounds, padding);
map.animateCamera(update);
This works perfectly fine, but there is only one problem with it, and that is : my current camera zoom level only includes the marker points, but the marker icon itself is usually, totally or partially, out of bounds.
Any suggestions on what i should do so i can have a the markers icons included inside my camera view ?
Why not just add some padding:
CameraUpdate update = CameraUpdateFactory.newLatLngBounds(bounds, 50);
I don't see why CameraUpdate should take into consideration the width of the marker itself. It includes the coordinates not the marker itself.
Another option could be:
CameraPosition cameraPosition =
new CameraPosition.Builder().target(ll).zoom(16).build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
You can see more about "Camera Position" here

Google Map's doesn't animate camera with new boundries

I've got GoogleMap in my android app and what I want to do is to animate camera to be exacly above items in my cluster. It works when the map is first lunched but never again in this session. This is how I want to update my map view:
List<LatLng> pointsList = new ArrayList<LatLng>();
for(MyObject myObject: ObjectsList) {
pointsList.add(new LatLng(myObject.getLatitude(), myObject
.getLongitude()));
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : pointsList) {
builder.include(latLng);
}
LatLngBounds bounds = builder.build();
int padding = 100;
mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mGoogleMap.animateCamera(mCameraUpdate);
I call this whenever I've got new ObjectList to set new boundries. But except first time it never works. I also can show how i put my objects into cluster:
mClusterManager = new ClusterManager<MyClusterItem>(mActivity, mGoogleMap);
mGoogleMap.setOnCameraChangeListener(mClusterManager);
mGoogleMap.setOnMarkerClickListener(mClusterManager);
mClusterManager.setRenderer(new MyClusterRenderer(mActivity, mGoogleMap, mClusterManager));
for (MyObject p : ObjectsList) {
MyClusterItem myClusterItem = new MyClusterItem(p);
mClusterManager.addItem(myClusterItem);
}
Can anybody explain me how to set camera to fit my objects and nothing else every time my objects list has changed?

OSMDroid Routing problems when following a tutorial

I utilise the following code to put a route overlay onto an OSM droid map, using code gotten from the following tutorial (http://code.google.com/p/osmbonuspack/wiki/Tutorial_1) but slightly tweaked into a custom method, rather than being used in the OnCrerate method.
Now this does route and produces a green overlay on the map. However, there is a problem exhibited from the For Loop onwards. This is because road.mNodes is always size zero indicating that no instructions are coming down.
Incidently I also inspected RoadNodes and RoadItems and both were also size zero. This means the bubbles (ExtendedOVerlayItems) are never displayed on the route.
Any advice would be greatly appreciated.
//======================================================================================================
/**
* Add a route overlay between two geopoints with Bubble overlays on the route points.
*
* #param startPoint Route start.
* #param endPoint Route end.
*//
//======================================================================================================
public void addRouteOverlay(GeoPoint startPoint, GeoPoint endPoint)
{
//1 Routing via road manager
RoadManager roadManager = new OSRMRoadManager();
roadManager.addRequestOption("routeType=bicycle");
//Then, retreive the road between your start and end point:
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
waypoints.add(startPoint);
waypoints.add(endPoint); //end point
Road road = roadManager.getRoad(waypoints);
// then, build an overlay with the route shape:
PathOverlay roadOverlay = RoadManager.buildRoadOverlay(road, map.getContext());
roadOverlay.setColor(Color.GREEN);
//Add Route Overlays into map
map.getOverlays().add(roadOverlay);
map.invalidate();//refesh map
Drawable marker = ctx.getResources().getDrawable(R.drawable.map_marker_blue);
final ArrayList<ExtendedOverlayItem> roadItems =
new ArrayList<ExtendedOverlayItem>();
ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodes =
new ItemizedOverlayWithBubble<ExtendedOverlayItem>(ctx, roadItems, map);
for (int i=0; i<road.mNodes.size(); i++)
{
RoadNode node = road.mNodes.get(i);
ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem("Step "+i, "", node.mLocation, ctx);
nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
nodeMarker.setMarker(marker);
roadNodes.addItem(nodeMarker);
nodeMarker.setDescription(node.mInstructions);
nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration));
Drawable icon = ctx.getResources().getDrawable(R.drawable.ic_continue);
nodeMarker.setImage(icon);
}//end for
map.getOverlays().add(roadNodes);
}//===================================================================================================
I had this problem today and managed to solve it. The problem lies with an old version of the bonus pack. I updated to version osmbonuspack_v4.1.jar from osmbonuspack_v3.8.jar and it solved the problem. I also used the MapQuestRoadManager() option as opposed to the OSRMRoadManager().However, its worth bearing in mind that when doing this a few of the super type methods changed in the bonus pack - such as the onOpen() method on ExtendedOverlayItem required its parameter to be cast after calling.
final RoadManager manager= new MapQuestRoadManager();
manager.addRequestOption("routeType=fastest");

Categories

Resources