Answer to converting lat/long to x/y on mercator not working for me when changing location from Germany to US

StackOverflow https://stackoverflow.com/questions/21841355

  •  12-10-2022
  •  | 
  •  

Question

I'm using an answer from Raphael from this post (https://stackoverflow.com/a/10401734/3321095) to convert lat/long to xy coordinates plotted on a mercator map. Raphael's example uses an area in Hamburg, Germany. I tested it and it does work. I then changed it to find a point within the United States but the coordinates are always beyond the size of the image. Can someone help?

<script type="text/javascript">
        var mapWidth = 749; //1500;
        var mapHeight = 462; //1577;

        var mapLonLeft = 125; //9.8;
        var mapLonRight = 65 //10.2;
        var mapLonDelta = mapLonRight - mapLonLeft;

        var mapLatBottom = 25 //53.45;
        var mapLatBottomDegree = mapLatBottom * Math.PI / 180;

        function convertGeoToPixel(lat, lon)
        {
            var position = new Array(2);

            var x = (lon - mapLonLeft) * (mapWidth / mapLonDelta);

            var lat = lat * Math.PI / 180;
            var worldMapWidth = ((mapWidth / mapLonDelta) * 360) / (2 * Math.PI);
            var mapOffsetY = (worldMapWidth / 2 * Math.log((1 + Math.sin(mapLatBottomDegree)) / (1 - Math.sin(mapLatBottomDegree))));

            var y = mapHeight - ((worldMapWidth / 2 * Math.log((1 + Math.sin(lat)) / (1 - Math.sin(lat)))) - mapOffsetY);

            position[0] = x;
            position[1] = y;

            return position;
        }

        var coordinates = convertGeoToPixel(30.274333164300643, -97.74064064025879); //convertGeoToPixel(53.7, 9.95);
        alert("x: " + coordinates[0] + " y: " + coordinates[1]);
    </script>

No correct solution

OTHER TIPS

Hope you figured this out in the last year. Your code helped me with a similar project. Your code is missing a minus sign and should look like this:

    var mapLonLeft = -125; //9.8;
    var mapLonRight = -65 //10.2;

Longitude is negative in the USA.

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