Load Map with bubbles on page load in android - android

In my application there is a map and the map has many pins. When the user taps on a pin, name of the touched pin appears in a balloon. What I want is to display all balloons on page loads, not when the user touches a pin. I have written the ItemizedOverlayWithBubble class and it overrides a method called onSingleTapUpHelper:
#Override protected boolean onSingleTapUpHelper(final int index, final Item item, final MapView mapView) {
showBubbleOnItem(index, mapView, true);
return true;
}
Inside that there is another method call showBubbleOnItem(index, mapView, true);
public void showBubbleOnItem(final int index, final MapView mapView, boolean panIntoView) {
ExtendedOverlayItem eItem = (ExtendedOverlayItem)(getItem(index));
mItemWithBubble = eItem;
if (eItem != null){
eItem.showBubble(mBubble, mapView, panIntoView);
//setFocus((Item)eItem);
}
}
I played around with it for a while to see if I could get it working on page load but got no luck. Any help is greatly appreciated.

Possibly your points are overlaps with each other. Especially if you create GeoPoints from integers with small difference like 11,1 and 12,2 and 13,3 this will couse overlaped overlay items
Have a look at here
package org.osmdroid.util.GeoPoint
when you use
GeoPoint(final int aLatitudeE6, final int aLongitudeE6)
Your value will not be multiplyed with 1E6(which is 1.000.000)
So there is no place difference between this two points on MapView
GeoPoints(11,1) and GeoPoints(12,2)

Related

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

I am trying to a make custom InfoWindow after a click on a marker with the new Google Maps API v2. I want it to look like in the original maps application by Google. Like this:
When I have ImageButton inside, its not working - the entire InfoWindow is slected and not just the ImageButton. I read that it is because there isn't a View itself but it's snapshot, so individual items cannot be distinguished from each other.
EDIT:
In the documentation (thanks to Disco S2):
As mentioned in the previous section on info windows, an info window
is not a live View, rather the view is rendered as an image onto the
map. As a result, any listeners you set on the view are disregarded
and you cannot distinguish between click events on various parts of
the view. You are advised not to place interactive components — such
as buttons, checkboxes, or text inputs — within your custom info
window.
But if Google use it, there must be some way to make it. Does anyone have any idea?
I was looking for a solution to this problem myself with no luck, so I had to roll my own which I would like to share here with you. (Please excuse my bad English) (It's a little crazy to answer another Czech guy in English :-) )
The first thing I tried was to use a good old PopupWindow. It's quite easy - one only has to listen to the OnMarkerClickListener and then show a custom PopupWindow above the marker. Some other guys here on StackOverflow suggested this solution and it actually looks quite good at first glance. But the problem with this solution shows up when you start to move the map around. You have to move the PopupWindow somehow yourself which is possible (by listening to some onTouch events) but IMHO you can't make it look good enough, especially on some slow devices. If you do it the simple way it "jumps" around from one spot to another. You could also use some animations to polish those jumps but this way the PopupWindow will always be "a step behind" where it should be on the map which I just don't like.
At this point, I was thinking about some other solution. I realized that I actually don't really need that much freedom - to show my custom views with all the possibilities that come with it (like animated progress bars etc.). I think there is a good reason why even the google engineers don't do it this way in the Google Maps app. All I need is a button or two on the InfoWindow that will show a pressed state and trigger some actions when clicked. So I came up with another solution which splits up into two parts:
First part:
The first part is to be able to catch the clicks on the buttons to trigger some action. My idea is as follows:
Keep a reference to the custom infoWindow created in the InfoWindowAdapter.
Wrap the MapFragment (or MapView) inside a custom ViewGroup (mine is called MapWrapperLayout)
Override the MapWrapperLayout's dispatchTouchEvent and (if the InfoWindow is currently shown) first route the MotionEvents to the previously created InfoWindow. If it doesn't consume the MotionEvents (like because you didn't click on any clickable area inside InfoWindow etc.) then (and only then) let the events go down to the MapWrapperLayout's superclass so it will eventually be delivered to the map.
Here is the MapWrapperLayout's source code:
package com.circlegate.tt.cg.an.lib.map;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.Marker;
import android.content.Context;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
public class MapWrapperLayout extends RelativeLayout {
/**
* Reference to a GoogleMap object
*/
private GoogleMap map;
/**
* Vertical offset in pixels between the bottom edge of our InfoWindow
* and the marker position (by default it's bottom edge too).
* It's a good idea to use custom markers and also the InfoWindow frame,
* because we probably can't rely on the sizes of the default marker and frame.
*/
private int bottomOffsetPixels;
/**
* A currently selected marker
*/
private Marker marker;
/**
* Our custom view which is returned from either the InfoWindowAdapter.getInfoContents
* or InfoWindowAdapter.getInfoWindow
*/
private View infoWindow;
public MapWrapperLayout(Context context) {
super(context);
}
public MapWrapperLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MapWrapperLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Must be called before we can route the touch events
*/
public void init(GoogleMap map, int bottomOffsetPixels) {
this.map = map;
this.bottomOffsetPixels = bottomOffsetPixels;
}
/**
* Best to be called from either the InfoWindowAdapter.getInfoContents
* or InfoWindowAdapter.getInfoWindow.
*/
public void setMarkerWithInfoWindow(Marker marker, View infoWindow) {
this.marker = marker;
this.infoWindow = infoWindow;
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean ret = false;
// Make sure that the infoWindow is shown and we have all the needed references
if (marker != null && marker.isInfoWindowShown() && map != null && infoWindow != null) {
// Get a marker position on the screen
Point point = map.getProjection().toScreenLocation(marker.getPosition());
// Make a copy of the MotionEvent and adjust it's location
// so it is relative to the infoWindow left top corner
MotionEvent copyEv = MotionEvent.obtain(ev);
copyEv.offsetLocation(
-point.x + (infoWindow.getWidth() / 2),
-point.y + infoWindow.getHeight() + bottomOffsetPixels);
// Dispatch the adjusted MotionEvent to the infoWindow
ret = infoWindow.dispatchTouchEvent(copyEv);
}
// If the infoWindow consumed the touch event, then just return true.
// Otherwise pass this event to the super class and return it's result
return ret || super.dispatchTouchEvent(ev);
}
}
All this will make the views inside the InfoView "live" again - the OnClickListeners will start triggering etc.
Second part:
The remaining problem is, that obviously, you can't see any UI changes of your InfoWindow on screen. To do that you have to manually call Marker.showInfoWindow. Now, if you perform some permanent change in your InfoWindow (like changing the label of your button to something else), this is good enough.
But showing a button pressed state or something of that nature is more complicated. The first problem is, that (at least) I wasn't able to make the InfoWindow show normal button's pressed state. Even if I pressed the button for a long time, it just remained unpressed on the screen. I believe this is something that is handled by the map framework itself which probably makes sure not to show any transient state in the info windows. But I could be wrong, I didn't try to find this out.
What I did is another nasty hack - I attached an OnTouchListener to the button and manually switched it's background when the button was pressed or released to two custom drawables - one with a button in a normal state and the other one in a pressed state. This is not very nice, but it works :). Now I was able to see the button switching between normal to pressed states on the screen.
There is still one last glitch - if you click the button too fast, it doesn't show the pressed state - it just remains in its normal state (although the click itself is fired so the button "works"). At least this is how it shows up on my Galaxy Nexus. So the last thing I did is that I delayed the button in it's pressed state a little. This is also quite ugly and I'm not sure how would it work on some older, slow devices but I suspect that even the map framework itself does something like this. You can try it yourself - when you click the whole InfoWindow, it remains in a pressed state a little longer, then normal buttons do (again - at least on my phone). And this is actually how it works even on the original Google Maps app.
Anyway, I wrote myself a custom class which handles the buttons state changes and all the other things I mentioned, so here is the code:
package com.circlegate.tt.cg.an.lib.map;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import com.google.android.gms.maps.model.Marker;
public abstract class OnInfoWindowElemTouchListener implements OnTouchListener {
private final View view;
private final Drawable bgDrawableNormal;
private final Drawable bgDrawablePressed;
private final Handler handler = new Handler();
private Marker marker;
private boolean pressed = false;
public OnInfoWindowElemTouchListener(View view, Drawable bgDrawableNormal, Drawable bgDrawablePressed) {
this.view = view;
this.bgDrawableNormal = bgDrawableNormal;
this.bgDrawablePressed = bgDrawablePressed;
}
public void setMarker(Marker marker) {
this.marker = marker;
}
#Override
public boolean onTouch(View vv, MotionEvent event) {
if (0 <= event.getX() && event.getX() <= view.getWidth() &&
0 <= event.getY() && event.getY() <= view.getHeight())
{
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: startPress(); break;
// We need to delay releasing of the view a little so it shows the pressed state on the screen
case MotionEvent.ACTION_UP: handler.postDelayed(confirmClickRunnable, 150); break;
case MotionEvent.ACTION_CANCEL: endPress(); break;
default: break;
}
}
else {
// If the touch goes outside of the view's area
// (like when moving finger out of the pressed button)
// just release the press
endPress();
}
return false;
}
private void startPress() {
if (!pressed) {
pressed = true;
handler.removeCallbacks(confirmClickRunnable);
view.setBackground(bgDrawablePressed);
if (marker != null)
marker.showInfoWindow();
}
}
private boolean endPress() {
if (pressed) {
this.pressed = false;
handler.removeCallbacks(confirmClickRunnable);
view.setBackground(bgDrawableNormal);
if (marker != null)
marker.showInfoWindow();
return true;
}
else
return false;
}
private final Runnable confirmClickRunnable = new Runnable() {
public void run() {
if (endPress()) {
onClickConfirmed(view, marker);
}
}
};
/**
* This is called after a successful click
*/
protected abstract void onClickConfirmed(View v, Marker marker);
}
Here is a custom InfoWindow layout file that I used:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginRight="10dp" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Title" />
<TextView
android:id="#+id/snippet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="snippet" />
</LinearLayout>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Test activity layout file (MapFragment being inside the MapWrapperLayout):
<com.circlegate.tt.cg.an.lib.map.MapWrapperLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map_relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
</com.circlegate.tt.cg.an.lib.map.MapWrapperLayout>
And finally source code of a test activity, which glues all this together:
package com.circlegate.testapp;
import com.circlegate.tt.cg.an.lib.map.MapWrapperLayout;
import com.circlegate.tt.cg.an.lib.map.OnInfoWindowElemTouchListener;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ViewGroup infoWindow;
private TextView infoTitle;
private TextView infoSnippet;
private Button infoButton;
private OnInfoWindowElemTouchListener infoButtonListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout)findViewById(R.id.map_relative_layout);
final GoogleMap map = mapFragment.getMap();
// MapWrapperLayout initialization
// 39 - default marker height
// 20 - offset between the default InfoWindow bottom edge and it's content bottom edge
mapWrapperLayout.init(map, getPixelsFromDp(this, 39 + 20));
// We want to reuse the info window for all the markers,
// so let's create only one class member instance
this.infoWindow = (ViewGroup)getLayoutInflater().inflate(R.layout.info_window, null);
this.infoTitle = (TextView)infoWindow.findViewById(R.id.title);
this.infoSnippet = (TextView)infoWindow.findViewById(R.id.snippet);
this.infoButton = (Button)infoWindow.findViewById(R.id.button);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
getResources().getDrawable(R.drawable.btn_default_normal_holo_light),
getResources().getDrawable(R.drawable.btn_default_pressed_holo_light))
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoButton.setOnTouchListener(infoButtonListener);
map.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener.setMarker(marker);
// We must call this to set the current marker and infoWindow references
// to the MapWrapperLayout
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
// Let's add a couple of markers
map.addMarker(new MarkerOptions()
.title("Prague")
.snippet("Czech Republic")
.position(new LatLng(50.08, 14.43)));
map.addMarker(new MarkerOptions()
.title("Paris")
.snippet("France")
.position(new LatLng(48.86,2.33)));
map.addMarker(new MarkerOptions()
.title("London")
.snippet("United Kingdom")
.position(new LatLng(51.51,-0.1)));
}
public static int getPixelsFromDp(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dp * scale + 0.5f);
}
}
That's it. So far I only tested this on my Galaxy Nexus (4.2.1) and Nexus 7 (also 4.2.1), I will try it on some Gingerbread phone when I have a chance. A limitation I found so far is that you can't drag the map from where is your button on the screen and move the map around. It could probably be overcome somehow but for now, I can live with that.
I know this is an ugly hack but I just didn't find anything better and I need this design pattern so badly that this would really be a reason to go back to the map v1 framework (which btw. I would really really like to avoid for a new app with fragments etc.). I just don't understand why Google doesn't offer developers some official way to have a button on InfoWindows. It's such a common design pattern, moreover this pattern is used even in the official Google Maps app :). I understand the reasons why they can't just make your views "live" in the InfoWindows - this would probably kill performance when moving and scrolling map around. But there should be some way how to achieve this effect without using views.
I see that this question is already old but still...
We made a sipmle library at our company for achieving what is desired - An interactive info window with views and everything. You can check it out on github.
I hope it helps :)
Here's my take on the problem. I create AbsoluteLayout overlay which contains Info Window (a regular view with every bit of interactivity and drawing capabilities). Then I start Handler which synchronizes the info window's position with position of point on the map every 16 ms. Sounds crazy, but actually works.
Demo video: https://www.youtube.com/watch?v=bT9RpH4p9mU (take into account that performance is decreased because of emulator and video recording running simultaneously).
Code of the demo: https://github.com/deville/info-window-demo
An article providing details (in Russian): http://habrahabr.ru/post/213415/
For those who couldn't get choose007's answer up and running
If clickListener is not working properly at all times in chose007's solution, try to implement View.onTouchListener instead of clickListener. Handle touch event using any of the action ACTION_UP or ACTION_DOWN. For some reason, maps infoWindow causes some weird behaviour when dispatching to clickListeners.
infoWindow.findViewById(R.id.my_view).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = MotionEventCompat.getActionMasked(event);
switch (action){
case MotionEvent.ACTION_UP:
Log.d(TAG,"a view in info window clicked" );
break;
}
return true;
}
Edit : This is how I did it step by step
First inflate your own infowindow (global variable) somewhere in your activity/fragment. Mine is within fragment. Also insure that root view in your infowindow layout is linearlayout (for some reason relativelayout was taking full width of screen in infowindow)
infoWindow = (ViewGroup) getActivity().getLayoutInflater().inflate(R.layout.info_window, null);
/* Other global variables used in below code*/
private HashMap<Marker,YourData> mMarkerYourDataHashMap = new HashMap<>();
private GoogleMap mMap;
private MapWrapperLayout mapWrapperLayout;
Then in onMapReady callback of google maps android api (follow this if you donot know what onMapReady is Maps > Documentation - Getting Started )
#Override
public void onMapReady(GoogleMap googleMap) {
/*mMap is global GoogleMap variable in activity/fragment*/
mMap = googleMap;
/*Some function to set map UI settings*/
setYourMapSettings();
MapWrapperLayout initialization
http://stackoverflow.com/questions/14123243/google-maps-android-api-v2-
interactive-infowindow-like-in-original-android-go/15040761#15040761
39 - default marker height
20 - offset between the default InfoWindow bottom edge and it's content bottom edge
*/
mapWrapperLayout.init(mMap, Utils.getPixelsFromDp(mContext, 39 + 20));
/*handle marker clicks separately - not necessary*/
mMap.setOnMarkerClickListener(this);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
YourData data = mMarkerYourDataHashMap.get(marker);
setInfoWindow(marker,data);
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
}
SetInfoWindow method
private void setInfoWindow (final Marker marker, YourData data)
throws NullPointerException{
if (data.getVehicleNumber()!=null) {
((TextView) infoWindow.findViewById(R.id.VehicelNo))
.setText(data.getDeviceId().toString());
}
if (data.getSpeed()!=null) {
((TextView) infoWindow.findViewById(R.id.txtSpeed))
.setText(data.getSpeed());
}
//handle dispatched touch event for view click
infoWindow.findViewById(R.id.any_view).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = MotionEventCompat.getActionMasked(event);
switch (action) {
case MotionEvent.ACTION_UP:
Log.d(TAG,"any_view clicked" );
break;
}
return true;
}
});
Handle marker click separately
#Override
public boolean onMarkerClick(Marker marker) {
Log.d(TAG,"on Marker Click called");
marker.showInfoWindow();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(marker.getPosition()) // Sets the center of the map to Mountain View
.zoom(10)
.build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),1000,null);
return true;
}
Just a speculation, I have not enough experience to try it... )-:
Since GoogleMap is a fragment, it should be possible to catch marker onClick event and show custom fragment view. A map fragment will be still visible on the background. Does anybody tried it? Any reason why it could not work?
The disadvantage is that map fragment would be freezed on backgroud, until a custom info fragment return control to it.
I have build a sample android studio project for this question.
output screen shots :-
Download full project source code Click here
Please note: you have to add your API key in Androidmanifest.xml
It is really simple.
googleMap.setInfoWindowAdapter(new InfoWindowAdapter() {
// Use default InfoWindow frame
#Override
public View getInfoWindow(Marker marker) {
return null;
}
// Defines the contents of the InfoWindow
#Override
public View getInfoContents(Marker marker) {
// Getting view from the layout file info_window_layout
View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);
// Getting reference to the TextView to set title
TextView note = (TextView) v.findViewById(R.id.note);
note.setText(marker.getTitle() );
// Returning the view containing InfoWindow contents
return v;
}
});
Just add above code in your class where you are using GoogleMap. R.layout.info_window_layout is our custom layout that is showing the view that will come in place of infowindow. I just added the textview here. You can add additonal view here to make it like the sample snap. My info_window_layout was
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="#+id/note"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
I hope it will help. We can find a working example of custom infowindow at http://wptrafficanalyzer.in/blog/customizing-infowindow-contents-in-google-map-android-api-v2-using-infowindowadapter/#comment-39731
EDITED : This code is shows how we can add custom view on infoWindow. This code did not handle the clicks on Custom View items. So it is close to answer but not exactly the answer that's why It is not accepted as answer.

MapView very slow with 1000 overlayitems on the map, even with only 2 visibles

I have a mapview showing 1000 overlayitems on the mapview. The map moves very slow even if only two overlayitems are visibles on the map (huge zoom applyed)
It is possible to optimice the mapview to move more fast if only low cuantity of overlayitems are visibles?
Thanks
You might have fallen in the usual pit. If you've made your own customoverlay make sure that your addOverlay methode don't populate. Populate should first happen when all overlays has been added. If you populate each time you add you'll end up with many overlays on top of each other.
Make sure it uses 2 methods for this process, 1 to add and 1 to populate:
public void addOverlay(CustomOverlayItem overlay) {
mOverlays.add(overlay);
}
public void populateOverlay() {
populate();
}
If that is not the issue then you should look into dynamically removing pins when they are outside the screen range or grouping pins together. I believe there is some open source project that have done the work for you in this regard.
Found a link http://onthefencedevelopment.com/blog/using-google-maps-your-android-applications-%E2%80%93-part-3-adding-place-markers drawing only the overlays which are on the screen. haven't tested it yet but seems promising.
EDIT: it works
subclass MapView, override dispatchDraw(). Detect changes in map center or zoom level:
#Override
public void dispatchDraw(Canvas canvas)
{
super.dispatchDraw(canvas);
GeoPoint gpCenterPoint = getMapCenter();
int nZoomLevel = getZoomLevel();
// either diff't zoom level or change to center point?
if ( (gpCenterPoint.getLatitudeE6() != mCenterPoint.getLatitudeE6()) ||
(gpCenterPoint.getLongitudeE6() != mCenterPoint.getLongitudeE6()) ||
(nZoomLevel != mZoomLevel) )
{
// update pins here
updatePINS();
mZoomLevel = nZoomLevel;
mCenterPoint = gpCenterPoint;
}
}
void updatePINS()
{
int nLatitudeSpan = mapView.getLatitudeSpan();
int nLongitudeSpan = mapView.getLatitudeSpan();
// TODO insert/remove PINS as needed
}

ItemizedOverlay and custom marker on OsmDroid for Android, no more touch event

I'm curently using a class which extends from the Drawable on OsmDroid.
And on this class I draw a geometric form for each car I receive from internet.
I would like to add a listener on each car in order to give some informations when we touch the car.
With a OverlayItem we can do this :
ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
carOverlay.draw(new Canvas());
overlayItem = new OverlayItem("test", ""+i, geoPoint);
overlayItem.setMarker(carOverlay.getCurrent());
items.add(overlayItem);
ItemizedOverlay<OverlayItem> overlay = new ItemizedOverlayWithFocus<OverlayItem>(this.getApplicationContext(), items,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
Log.i("Touch","you just tap the car");
return true;
}
#Override
public boolean onItemLongPress(final int index, final OverlayItem item) {
return false;
}
});
With this piece of code, I can see the image I've just drawn, but no event when I touch a car, and if I remove the line :
overlayItem.setMarker(carOverlay.getCurrent());
to let the default marker being displayed instead of my custom marker, the touch events occure.
So what am I doing wrong ? must be the same no ?
This is not a 'proper' answer but as I am facing similar problem I resorted to using BOTH default draw and custom at the same time.
I just call super() at the end of my custom draw method on ItemizedIconOverlay and both my drawing and 'default' item marker are drawn.
Maybe it would be possible to tweak default marker to make it invisible (empty bitmap)... experiment. :)
#Override
public void draw(Canvas canvas, MapView mv, boolean shadow) {
if(!shadow) {
//my draw code
}
super.draw(canvas, mv, shadow);
}
tmouse is correct. If you're overriding the ItemizedOverlayWithFocus.draw() method to draw your car with canvas, you'll need to add:
super.draw(canvas, view, shadow);
The super will setup and use the OverlayItem's Hotspot which is (from what I can see in the source) used as the touchable area for gestures.
However you'll still see the original Markers AND your canvas drawn ones. PLUS if you move your cars, the touchable area won't move with it. (the Hotspot will not be for the new location you drew at)
There are only 2 real solutions.
1) You re-implement ItemizedOverlayWithFocus.draw() and ItemizedOverlayWithFocus.onDrawItem() in your own ItemizedOverlayWithFocus class. (only you'll call onDrawItem(), onDrawCar(), and call it instead from the overridden draw() method)
That's not worth it unless you want to change the offset of the Marker being drawn. e.g. I have a tower icon, and I want 10 pixels from the bottom to be the Y point so it looks like the tower is standing on the GeoPoint, not at the edge of it.
2) You create your own Markers from a Bitmap first, and set it as a Drawable Marker in the OverlayItem.setMarker() method. Try creating a a Bitmap using Canvas:
Bitmap bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
// Draw on your car on the canvas...
Then try assigning the Bitmap:
overlayItem.setMarker(new BitmapDrawable(bitmap));
Don't override draw() unless you want to draw some other stuff, and if you do ensure you super.draw() so the Marker and its Hotspot work with the gestures.
You can try also this code
Drawable newMarker = this.getResources().getDrawable(R.drawable.ic_marker);
this.mMyLocationOverlay = new ItemizedIconOverlay<OverlayItem>(items,
newMarker, "listener try null", new DefaultResourceProxyImpl(getActivity()));
mapView.getOverlays().add(mMyLocationOverlay);

Google Map Marker Clickable Area

I am using this example: https://github.com/galex/android-mapviewballoons
My problem is that the clickable area is wider than the marker itself. For example, my Google Map marker is 25x25 then the clickable area would extend up to 70x70. This is a big problem for overlapping markers.
When I clicked on the tip of that arrow, onTap is activated, even though the tap area is far from the marker.
Please help me. Thanks.
This is the default behaivior of ItemizedOverlay. 25x25 px is generally not an adquate touchable area for most human fingers.
You should override the hitTest() method if you want to modify the way an overlay item hit is tested.
For debugging :
Try using a TouchDelegate for the View, you can specify the Touch rect for a give View
An example showing how to use the TouchDelegate :
public class TouchDelegateSample extends Activity {
Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.touch_delegate_view);
mButton = (Button)findViewById(R.id.delegated_button);
View parent = findViewById(R.id.touch_delegate_root);
// post a runnable to the parent view's message queue so its run
after
// the view is drawn
parent.post(new Runnable() {
#Override
public void run() {
Rect delegateArea = new Rect();
Button delegate = TouchDelegateSample.this.mButton;
delegate.getHitRect(delegateArea);
delegateArea.top -= 200;
TouchDelegate expandedArea = new TouchDelegate(delegateArea,
delegate);
// give the delegate to an ancestor of the view we're
delegating the
// area to
if (View.class.isInstance(delegate.getParent())) {
((View)delegate.getParent()).setTouchDelegate(expandedArea);
}
}
});
}
}
hitTest()
See if a given hit point is within the bounds of an item's marker. Override to modify the way an item is hit tested. The hit point is relative to the marker's bounds. The default implementation just checks to see if the hit point is within the touchable bounds of the marker.

Porting a Google Maps app to Osmdroid - problem with overlay

I'm porting a Google Maps based project to Osmdroid in order to use OpenStreetMaps. The port is working OK apart from adding my overlay which consists of a number of straight lines and some text. In both projects I add the Overlay by means of a timer thread and handler calling redrawOverlay.
In the OSM project my overlay is just a grey square completely hiding the map. If I remove the call to redrawOveraly, the OSM tiles are shown OK. I've reduced the overlay code to the bare minimum of a single diagonal line in the code samples below. It works fine in the Google app, overlaying the map tile. The com.google.android.maps.Overlay has a draw method, the OSM has an onDraw, so I have in the OSM version:
private MapView mv;
private MapOverlay mmapOverlay = null;
private void redrawOverlay() {
gPt = mv.getMapCenter();
if (mmapOverlay == null)
mmapOverlay = new MapOverlay(getApplicationContext());
List<Overlay> listOfOverlays = mv.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mmapOverlay);
mv.invalidate();
}
public class MapOverlay extends org.osmdroid.views.overlay.Overlay {
public MapOverlay(Context ctx) {
super(ctx);
// TODO Auto-generated constructor stub
}
#Override
public void onDraw(Canvas canvas, MapView mapView) {
Paint lp3;
lp3 = new Paint();
lp3.setColor(Color.RED);
lp3.setAntiAlias(true);
lp3.setStyle(Style.STROKE);
lp3.setStrokeWidth(1);
lp3.setTextAlign(Paint.Align.LEFT);
lp3.setTextSize(12);
canvas.drawLine(10, 10, 150, 150, lp3);
}
Whilst in the Google maps original I have the equivalent :
public class MapOverlay extends com.google.android.maps.Overlay {
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
super.draw(canvas, mapView, shadow);
Paint lp3;
lp3 = new Paint();
.....etc.
redrawOverlay is the same except the instantiation of the overlay is just:
mmapOverlay = new MapOverlay();
All suggestions will be gratefully received
UPDATE Question for kurtzmarc:
Thanks for you help so far, I see that you are one of the authors of Osmdroid. I like what it's doing so far. I would like to suppress the 'jump to and zoom in' that you get on double tap. I'd like it to do nothing at all. I think it's probably hitting this bit in your source and doing the zoomInFixing:
private class MapViewDoubleClickListener implements GestureDetector.OnDoubleTapListener {
#Override
public boolean onDoubleTap(final MotionEvent e) {
for (int i = mOverlays.size() - 1; i >= 0; i--)
if (mOverlays.get(i).onDoubleTapUp(e, MapView.this))
return true;
final GeoPoint center = getProjection().fromPixels(e.getX(), e.getY());
return zoomInFixing(center);
}
It doesn't seem that I can override it. I'm using the 3.0.1 jar and the associated javadocs. I'm wondering if the Mapview's setTouchDelegate method would help, but there is no reference to it in the javadocs. Have you any suggestions please?
I'm not sure where you are calling redrawOverlay() from, but if you look at the MinimapOverlay you will see an example where something is drawn at a fixed location on the screen. In other words, you are drawing in screen coordinates not in map coordinates.
Example:
#Override
protected void onDraw(final Canvas pC, final MapView pOsmv) {
// Calculate the half-world size
final Rect viewportRect = new Rect();
final Projection projection = pOsmv.getProjection();
final int zoomLevel = projection.getZoomLevel();
final int tileZoom = projection.getTileMapZoom();
mWorldSize_2 = 1 << (zoomLevel + tileZoom - 1);
// Find what's on the screen
final BoundingBoxE6 boundingBox = projection.getBoundingBox();
final Point upperLeft = org.osmdroid.views.util.Mercator
.projectGeoPoint(boundingBox.getLatNorthE6(), boundingBox.getLonWestE6(),
zoomLevel + tileZoom, null);
final Point lowerRight = org.osmdroid.views.util.Mercator
.projectGeoPoint(boundingBox.getLatSouthE6(), boundingBox.getLonEastE6(), zoomLevel
+ tileZoom, null);
// Save the Mercator coordinates of what is on the screen
viewportRect.set(upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y);
// Offset into OSM coordinates
viewportRect.offset(-mWorldSize_2, -mWorldSize_2);
// Draw a line from one corner to the other
canvas.drawLine(viewportRect.left, viewportRect.top, viewportRect.right, viewportRect.bottom);
From here viewportRect represents the upper left to the lower right of the screen. You can use this to draw at any fixed points on the screen.
UPDATE:
To answer your second question - what you need to do is override onDoubleTap in your Overlay and return "true". Returning "true" indicates to the base class that you "consumed" the event and no further processing should take place. Take a look at the minimap overlay code for a good example:
http://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/org/osmdroid/views/overlay/MinimapOverlay.java
We are right in the middle of overhauling the Overlays, so some of this will be handled a little better in the near future. For example, the getOverlays().clear() bug you ran into has also been reported elsewhere and we've since fixed it.

Categories

Resources