0

I found some code for converting latitude/longitude to pixels on a given image and vice versa. I ported it to JavaScript but am getting incorrect return values on the latitude. I tested the original, unmodified code and it gives the same inaccuracies. Below is the code with the values it returns.

function degrees_pixels(latitude, longitude, width, height) {
    return {
        x:  ( longitude + 180 ) * ( width / 360 ),
        y:  ( height / 2 ) - ( width * Math.log(Math.tan(( Math.PI / 4 ) + ( ( latitude * Math.PI / 180 ) / 2 )) ) / ( 2 * Math.PI ) )
    };
};

function pixels_degrees(pixel_x, pixel_y, width, height) {
    return {
        latitude:   ( Math.exp( -( pixel_y - ( height / 2 ) ) / width * ( 2 * Math.PI )) - Math.tan(( Math.PI / 4 )) * 2 ) / ( Math.PI / 180 ),
        longitude:  ( pixel_x - ( width / 2 ) ) / ( width / 360 )
    };
};

var tmp1 = degrees_pixels(40.7127, -74.0059, 256, 256);
console.log(tmp1); // Prints {"x":75.3735822222222,"y":96.2511781695169} which is correct
console.log(pixels_degrees(tmp1.x, tmp1.y, 256, 256)); // Prints {"latitude":10.3018054035438,"longitude":-74.0059} of which the latitude is incorrect

I have tried fixing it myself but I am struggling with the math. I am not really sure why it is off the way it is.

  • Most map folks don't reinvent the maths, and use a projection library (e.g. [D3](https://www.jasondavies.com/maps/transition/), [proj4js](http://proj4js.org/), et al.) to transform coordinates between projections and to fit on a screen. – Mike T Mar 15 '16 at 04:34
  • I spent months playing with OpenLayers 3 and various other libraries. For what I want to do I need to create my own. Besides, none of those convert to pixels. – Nicholas J Ingrassellino Mar 15 '16 at 17:44

1 Answers1

1

Have you already tried this?

So your code looks something like

function degrees_pixels(latitude, longitude, width, height) {
    return {
        x: Math.round((longitude + 180) * (width / 360));,
        y: Math.round(((-1 * latitude) + 90) * (height / 180))
    };
};
function pixels_degrees(pixel_x, pixel_y, width, height) {
    return {
        latitude: (pixel_y/(height/180)-90)/-1,
        longitude: pixel_x/(width/360)-180
    };
};

Or if you don't want a whole world map this

And make sure your coordinates are given in EPSG:3857 standard.

Community
  • 1
  • 1
  • degrees_pixels() should yield something like 75x96. It is instead returning 75x70. I am testing this by using a reference image in GIMP (of the same size I specify) and seeing where those pixel values fall. – Nicholas J Ingrassellino Mar 15 '16 at 17:20