toPixels()返回切片的像素,而不是屏幕

时间:2012-03-12 14:58:54

标签: android google-maps map osmdroid

我有一个使用OSMDroid显示地图的Android应用程序。 我想在屏幕上获得GeoPoint的投影像素,而不是在图块上。 请考虑以下代码:

Projection projection = getProjection();
GeoPoint geoPoint1 = (GeoPoint)projection.fromPixels(0, 0);  
Point pixelsPoint = new Point();
projection.toPixels(geoPoint1, pixelsPoint);
GeoPoint geoPoint2 = (GeoPoint)projection.fromPixels(pixelsPoint.x, pixelsPoint.y);

我希望geoPoint1等于geoPoint2。相反,我得到2个完全不同的“GeoPoint”。 在我看来,问题出在这一行:

projection.toPixels(geoPoint1, pixelsPoint);

out变量pixelsPoint填充的值远远高于屏幕尺寸(x和y得到10,000+),我怀疑这是瓷砖上的像素,而不是屏幕像素。

如何从GeoPoint来回屏幕像素来回?

1 个答案:

答案 0 :(得分:7)

您需要补偿左上角偏移量,这些方法应该有效:

/**
 * 
 * @param x  view coord relative to left
 * @param y  view coord relative to top
 * @param vw MapView
 * @return GeoPoint
 */

private GeoPoint geoPointFromScreenCoords(int x, int y, MapView vw){
    if (x < 0 || y < 0 || x > vw.getWidth() || y > vw.getHeight()){
        return null; // coord out of bounds
    }
    // Get the top left GeoPoint
    Projection projection = vw.getProjection();
    GeoPoint geoPointTopLeft = (GeoPoint) projection.fromPixels(0, 0);
    Point topLeftPoint = new Point();
    // Get the top left Point (includes osmdroid offsets)
    projection.toPixels(geoPointTopLeft, topLeftPoint);
    // get the GeoPoint of any point on screen 
    GeoPoint rtnGeoPoint = (GeoPoint) projection.fromPixels(x, y);
    return rtnGeoPoint;
}

/**
 * 
 * @param gp GeoPoint
 * @param vw Mapview
 * @return a 'Point' in screen coords relative to top left
 */

private Point pointFromGeoPoint(GeoPoint gp, MapView vw){

    Point rtnPoint = new Point();
    Projection projection = vw.getProjection();
    projection.toPixels(gp, rtnPoint);
    // Get the top left GeoPoint
    GeoPoint geoPointTopLeft = (GeoPoint) projection.fromPixels(0, 0);
    Point topLeftPoint = new Point();
    // Get the top left Point (includes osmdroid offsets)
    projection.toPixels(geoPointTopLeft, topLeftPoint);
    rtnPoint.x-= topLeftPoint.x; // remove offsets
    rtnPoint.y-= topLeftPoint.y;
    if (rtnPoint.x > vw.getWidth() || rtnPoint.y > vw.getHeight() || 
            rtnPoint.x < 0 || rtnPoint.y < 0){
        return null; // gp must be off the screen
    }
    return rtnPoint;
}