0

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>
Community
  • 1
  • 1
user3321095
  • 185
  • 1
  • 10
  • I may as well ask what output you're getting and what output you're expecting. Looks like that point is the capitol building in Austin, Texas. Is that what it's supposed to be? – jpmc26 Feb 17 '14 at 23:47
  • Yes, it should be. The map I'm using is 749x462 but the point I get from the code above is x:2781 and y:536. It should be closer to x:373 and y:324. – user3321095 Feb 17 '14 at 23:53

1 Answers1

2

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.

Jeff
  • 382
  • 1
  • 7