地图的平移、缩放的实现(android版)

一、平移地图

移动地图的原理是利用手指在屏幕上拖动的距离,转换为在地图上距离,把地图坐标加上偏移的距离实现地图移动。

由于地图是绘制到Bitmap上的,所以地图移动和缩放的过程只要改变Bitmap的矩阵即可,待移动和缩放完成后,再根据新的地图范围重新渲染地图。

地图移动过程的关键代码:

offsetX=newX-lastX

offsetY=newY-lastY

matrix.postTranslate(offsetX, offsetY)

canvas.drawBitmap(Bitmap,matrix,paint)

 

移动完成后重新计算地图范围的关键代码:

1、计算偏移值

offsetX=newX-startX

offsetY=newY- startY

offsetMapX= offsetX*resolution

offsetMapY= offsetY*resolution

2、重新计算坐标

minX = mapExtent.getMinX()-offsetMapX

minY = mapExtent.getMinY()+offsetMapY

maxX = mapExtent.getMaxX()-offsetMapX

maxY = mapExtent.getMaxY()+offsetMapY

二、缩放地图

地图缩放的原理是利用两指在屏幕上滑动时,两指之间的距离变化比值进行缩放地图,地图缩放时,两指之间的中心点保持坐标不变。

地图缩放时的关键代码:

newDis=Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))   //计算两指之间的距离

scale=newDis/lastDis                                                   //两指在点击屏幕到离开屏幕时的距离比

matrix.postScale(scale, scale, this.startX, this.startY);

canvas.drawBitmap(Bitmap,matrix,paint)

三、在android下触发的事件

由于地图的平移和缩放是用手指完成的,所以对地图进行平移和缩放都是在用于绘制地图的view上的onTouchEvent事件里面完成,下面是这个事件的代码(其他代码就不公开了):

public boolean onTouchEvent(MotionEvent motionEvent){
    int x1=(int) motionEvent.getX(0);
    int y1 =(int)motionEvent.getY(0);
    int x2=-1;
    int y2=-1;
    if (motionEvent.getPointerCount() == 1) { //平移
        if(isZoom==true){
            return;
        }
        
        switch (motionEvent.getAction()) {
        case MotionEvent.ACTION_DOWN:
            isTouching=true;
            matrix=new Matrix();
            this.pointerPressed(x1, y1, x2, y2);
            break;
        case MotionEvent.ACTION_UP:
            this.isRefreshMap=false;
            this.pointerReleased(x1, y1, x2, y2);
            isTouching=false;
            break;
        case MotionEvent.ACTION_MOVE:
            this.pointerDragged(x1, y1, x2, y2);
            break;
        }
    } else if (motionEvent.getPointerCount() == 2) {  //缩放
        isZoom=true;
        this.x=-1;
        this.y=-1;
        
        x2=(int)motionEvent.getX(1);
        y2=(int)motionEvent.getY(1);
        
        if(motionEvent.getAction() != MotionEvent.ACTION_MOVE){
            if(this.lastDis<0){
                isTouching=true;
                matrix=new Matrix();
                this.startZoom(x1, y1, x2, y2);
            }else
            {
                this.isRefreshMap=false;
                this.endZoom(x1, y1, x2, y2);
                isZoom=false;
                isTouching=false;
            }
        }else
        {
            this.touchZoom(x1, y1, x2, y2);
        }
    }
}        
原文地址:https://www.cnblogs.com/gdguansun/p/4793097.html