简体   繁体   中英

How to add drawable in runtime properly using Mapsforge

I could get Mapsforge lib 0.30 working on Android and I'm really satisfied with it. Problem I have is I can't add a custom drawable in a proper way. When I add a drawable to be drawn, the drawable doesn't show up in the right position, but it shows in the left top corner of the screen. This is an example of my test code:

MapView mapView = new MapView(this);
mapView.setClickable(true);
mapView.setBuiltInZoomControls(true);
mapView.setEnabled(true);
mapView.setMapFile(new File("/sdcard/remob/netherlands.map"));

setContentView(mapView);

// Creating my own custom drawable
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(60, 60, conf);
Drawable drawable = new BitmapDrawable(getResources(), bmp) {
@Override
public void draw(Canvas canvas) {
    super.draw(canvas);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.BLUE);
    paint.setStyle(Style.FILL);

    canvas.drawCircle(30, 30, 15, paint);
}
};

// create an ItemizedOverlay with the default marker
ArrayItemizedOverlay itemizedOverlay = new ArrayItemizedOverlay(drawable);

// create a GeoPoint with the latitude and longitude coordinates
GeoPoint geoPoint = new GeoPoint(51.92434, 4.47769);

// create an OverlayItem with title and description
OverlayItem item = new OverlayItem(geoPoint, "MyPoint", "This is my own point.");
item.setMarker(ItemizedOverlay.boundCenter(drawable));

// add the OverlayItem to the ArrayItemizedOverlay
itemizedOverlay.addItem(item);

// add the ArrayItemizedOverlay to the MapView
mapView.getOverlays().add(itemizedOverlay);

So can anyone please help me to do it the right way? In short, I want to create a drawable in runtime and put it on the right position. Just adding a drawable from resource is not a problem, that is working good, but from runtime, the drawable is not on the right position. Thank you.

You need to call Marker.boundCenter(...) on it.

I use a line like:

ef_icon = Marker.boundCenter(getResources().getDrawable(R.drawable.ef_icon));

I'm working from Trunk (looks like 0.3.1-snapshot to Maven).

If that method is missing from your version of Mapsforge then the full method is:

public static Drawable boundCenter(Drawable drawable) {
    int intrinsicWidth = drawable.getIntrinsicWidth();
    int intrinsicHeight = drawable.getIntrinsicHeight();
    drawable.setBounds(intrinsicWidth / -2, intrinsicHeight / -2, intrinsicWidth / 2, intrinsicHeight / 2);
    return drawable;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM