Question

I am writing an app to display bike rack stations in a city. I am pulling the coordinates from a json file and trying to convert the latitude/longitudes into screen coordinates.

The framework I am using (Qt) calculates y from top to bottom and x from left to right, so obviously I wrote conversion functions for this. The conversion functions look like this:

/* 
The minLatitude has already been calculated to be
the latitude of the southernmost rack

*/
qreal BikeRackSystem::getY(qreal latitude)
{
  qreal diffY = latitude - minLatitude;
  return height - (diffY*height);
}

/* 
The minLatitude has already been calculated to be
the latitude of the southernmost rack

*/
qreal BikeRackSystem::getX(qreal longitude)
{
  qreal diffX = longitude - minLongitude;
  return width * diffX;
}

However I end up with this kind of image

enter image description here

This is close, but not quite what I was looking for. How can I change my conversion functions to give me screen coordinates that span the whole screen?

Edit: If it is at all interesting...I am using QGraphicsEllipseItem subclasses to draw the racks on a QGraphicsScene.

Was it helpful?

Solution

I found out that my conversion function wasn't properly set up. I found the best answer here

The crucial part mentioned in the answer was:

        x - min                                  max - min
f(x) = ---------   ===>   f(min) = 0;  f(max) =  --------- = 1
       max - min                                 max - min

OTHER TIPS

One solution is to set the scene geometry to the view geometry. For example, you can overwrite the resize event of your QGraphicsView:

void MyQgraphicsView::resizeEvent(QResizeEvent *event)
{
    /* always resize the scene accordingly */
    if (scene())
        scene()->setSceneRect(QRect(QPoint(0, 0), event->size()));

    QGraphicsView::resizeEvent(event);
}

Then you can use the width and height of the scene for setting up your internal coordinate system. This is an example of a widget that would always auto-zoom the contents.

Often you don't want this (e.g. the user should be able to zoom and pan the map with the mouse). Then you should determine a good initial configuration of the QGraphicsView. For this you can either use the setSceneRect() or the setTransform() method on the graphicsview. The latter is more powerful (e.g. it enables rotation), while the former is easier to use. In this case, you would set a generic scene size of your liking (e.g. 1-by-1) to ease the handling of internal coordinates. You might even use the latitudes and longitudes as x, y values and then let the transformation matrix handle it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top