Search code examples
androidcanvasgoogle-maps-api-2

Move a map marker by a set number of pixels on Google Maps v2


I have added custom map markers from drawable shapes to my Google map. These markers are various coloured dots. When the user taps on one of the markers a polyline is drawn from a source location to the selected marker; see Figure 1;

]

Figure 1: My current map

The line draws straight to the coordinate marked by the coloured dots. However, as is clearly evident with the purple dot the markers are drawn on top - I'd rather the polylines intersect the circle's centre such that the line from every angle looks a bit more like this;

/] http://milspace.viecorefsd.com/~nlehman/example.png

Figure 2: The desired polyline-circle intersection

To achieve this I attempted to translate the canvas backing the drawable by the dot radius. Here is my attempt;

    // Circular marker.
    final int px = getResources().getDimensionPixelSize(dimen.map_dot_marker_size);
    final Bitmap mDotMarkerBitmap = Bitmap.createBitmap(px, px, Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(mDotMarkerBitmap);
    final Drawable shape = getResources().getDrawable(drawable.purple_map_dot);
    shape.setBounds(0, 0, px, px);
    canvas.translate(0, px/2);
    shape.draw(canvas);
    final MarkerOptions options = new MarkerOptions();
    options.position(spot.getNearestCityLatLng());
    options.icon(BitmapDescriptorFactory.fromBitmap(mDotMarkerBitmap));
    options.title(spot.getNearestCity());
    lastLocationSelectionMarker.addMarker(options);

This bit of code did indeed move the drawable but the size of the backing canvas remained constant meaning the circle was chopped in half with the other half not visible.

Can the community advise how best to go about achieving the effect I'm after in Figure 2 with the marker centre directly over the coordinate it is marking?


Solution

  • You have to use anchor property when you create Marker. By default, anchor is set to 0.5f,1f which points to the center horizontal and bottom vertical part of your marker. For your type of markers, I would assume you need to use [0.5f,0.5f] anchor (refer to documentation)

    So your code would look like:

    // Circular marker.
    final MarkerOptions options = new MarkerOptions();
    options.position(spot.getNearestCityLatLng());
    options.icon(BitmapDescriptorFactory.fromResource(R.drawable.purple_map_dot));
    options.title(spot.getNearestCity());
    options.anchor(0.5f, 0.5f);
    lastLocationSelectionMarker.addMarker(options);