Map lat lng to a portion of the world map


I want to project GPS coordinates on a screen of a specific size. This screen must not be representing the entire world map, but a small portion, something like 200 meters x 100 meters at a certain place .

This are my draw() and LatLngtoXY() functions:

void draw()
  if(newData) {
    fill(#FFFFFF, 10);
    rect(xCoord, yCoord, rectSizeX, rectSizeY);


void LatLngtoXY(float lat, float lon) {
    float mapWidth    = width;
    float mapHeight   = height;
    // get x value
    xCoord = (lon+180)*(mapWidth/360);
    // convert from degrees to radians
    float latRad = lat*PI/180;
    // get y value
    float mercN = log(tan((PI/4)+(latRad/2)));
    yCoord     = (mapHeight/2)-(mapWidth*mercN/(2*PI));

I got the conversion bit of code online. Now I think that maps the entire world map doesn’t it?
How can I adjust the code so that the trail of blocks that is drawn is shown in a 200meters x 100 meters representation?

Thanks in advance!

1 Like

I thought it would be most convenient to draw each shape in center of the window,
so it needs to zoom in a certain amount, and center the rectangle in the canvas. I haven’t found out how to do this yet.

I think the standard approach for this would be to partition your map into a grid. Ie divide the lat/long points by the width/height of the square you wish to draw and use round or floor. This way it ensures that it remains bound to a rectangular location.

So if we wanted 10x10 squares, and your point was at 12,19 you would divide 12/10 and 19/10 and floor it. it would give you a coordinate of 1,1 which would be the index 1 for x, and index 1 for y. You would then be able to easily assign it to the correct space on the map.If you wanted to center your map around said square you would then use the translate function to translate to 15,15 as that corresponds to half way between 10 and 20.

1 Like