这里是基本步骤,下面是完整代码。经过测试,效果很好。
首先,假设我们使用的是标记图标位图,大小为 27 x 27 像素,并且您希望将锚点从图标的默认左下角移动到右下角。
将锚点移至右下方:marker.setAnchor(1,0);
一个图标在 x 方向的宽度是 27 DPs,但我们需要知道这是多少像素。
offsetPoint.x -= MapUtils.convertDpToPx(CreateRouteActivity.this, offsetDPX);
现在我们知道屏幕上的点在哪里,所以只需从中获取 LatLng:marker.setPosition(projection.fromScreenLocation(offsetPoint));
如果您想将图标移到离手指更远的位置,只需尝试使用 ANCHOR_FACTOR 值即可。
这是我的 CreateRouteActivity:
private GoogleMap.OnMarkerDragListener onMarkerDragListener = new GoogleMap.OnMarkerDragListener() {
float offsetDPX;
float offsetDPY;
Projection projection;
@Override
public void onMarkerDragStart(Marker marker) {
// Save the projection every time a marker starts to drag. This keeps the anchors and drop points synced up.
// If we don't save the projection at the point the marker starts to drag and the user zooms out, the icon pixel size
// will remain the same but the LatLng distances will have way fewer pixels, messing up the drop point.
projection = gMap().getProjection();
// GoogleMap's default anchor is located at the lower left point of the marker icon.
// An ANCHOR_FACTOR of 1 will move the drag point to the lower right of the icon.
// An ANCHOR_FACTOR of 2 will move the drag point to the lower right x 2. (The icon will move from under the user's finger to 2 width's above and to the left.)
float ANCHOR_FACTOR = 1f;
// 27 is my original icon's width in pixels.
// Android increases the pixel size of the image in high-density screens, so make sure you use 27 DPs, not 27 pixels.
offsetDPX = 27*ANCHOR_FACTOR;
offsetDPY = 27*(ANCHOR_FACTOR-1);
// Always set the anchor by percentage of icon width. 0,0 is lower left. 1,0 is lower right.
marker.setAnchor(ANCHOR_FACTOR,ANCHOR_FACTOR-1);
}
@Override
public void onMarkerDrag(Marker marker) {
// If you want something to happen while you drag, put it here.
}
@Override
public void onMarkerDragEnd(Marker marker) {
// getPosition returns pixel location
Point offsetPoint = projection.toScreenLocation(marker.getPosition());
// We need to offset by the number of DPs, so convert DPs to pixels.
offsetPoint.x -= MapUtils.convertDpToPx(CreateRouteActivity.this, offsetDPX);
offsetPoint.y -= MapUtils.convertDpToPx(CreateRouteActivity.this, offsetDPY);
// set the marker's LatLng from offsetPoint (in pixels)
marker.setPosition(projection.fromScreenLocation(offsetPoint));
};
以及我的 MapUtils 对象中的一些转换工具:
public static float convertDpToPx(Context context, float dp) {
return dp * context.getResources().getDisplayMetrics().density;
}
public static float convertPxToDp(Context context, float px) {
return px / context.getResources().getDisplayMetrics().density;
}