Search code examples
javascriptgeolocationgpsfabricjslatitude-longitude

Converting Latitude and Longitude to coordinates on image


I am trying to convert a location to a point on image. I am using fabricjs to draw the map, the map object I made out of an image of the earth. I convert the image to an array, where land is 1 and 0 is water. My problem is that I cant convert the location to a point properly. I am using this formula which works, but not for the image I am using.

function getMapCoordsByLatAndLng(latitude, longitude, mapWidth, mapHeight){
    var x = (longitude + 180 )* (mapWidth / 360);
    var latRad = latitude* Math.PI /180;
    var mercN = Math.log(Math.tan(( Math.PI /4)+(latRad/2)));
    var y = (mapHeight / 2) - ( mapWidth *mercN/(2 * Math.PI));

    return {
        x: x,
        y: y
    };
}

Here is my result for now. enter image description here I have used two locations - Los Angeles and Sydney. As you can see the coordinates on the map are not correct. Here is a fiddle with all the code.

Edit: I ended up following a suggestion to use equirectangular projection instead of mercator one. Thus the algorythm for finding the coordinates on the canvas changed.

    function getMapCoords(latitude, longitude, mapWidth, mapHeight){
        return {
            x: parseInt((longitude + 180.0) * (mapWidth / 360.0)),
            y: parseInt(((latitude * -1.0) + 90.0) * (mapHeight / 180.0))
        }
    }

I have updated my code and the result can be found here.


Solution

  • Your map is off and the coordinates for Sydney are plain wrong.

    With better coordinates:

    map