Convert Lat/Longs to X/Y Co-ordinates

后端 未结 3 1627

I have the Lat/Long value of New York City, NY; 40.7560540,-73.9869510 and a flat image of the earth, 1000px × 446px.

I would like to be able to convert, using Javas

相关标签:
3条回答
  • 2020-11-30 22:27

    The projection you use is going to change everything, but this will work assuming a Mercator projection:

    <html>
    <head>
    <script language="Javascript">
    var dot_size = 3;
    var longitude_shift = 55;   // number of pixels your map's prime meridian is off-center.
    var x_pos = 54;
    var y_pos = 19;
    var map_width = 430;
    var map_height = 332;
    var half_dot = Math.floor(dot_size / 2);
    function draw_point(x, y) {
        dot = '<div style="position:absolute;width:' + dot_size + 'px;height:' + dot_size + 'px;top:' + y + 'px;left:' + x + 'px;background:#00ff00"></div>';
        document.body.innerHTML += dot;
    }
    function plot_point(lat, lng) {
        // Mercator projection
    
        // longitude: just scale and shift
        x = (map_width * (180 + lng) / 360) % map_width + longitude_shift;
    
        // latitude: using the Mercator projection
        lat = lat * Math.PI / 180;  // convert from degrees to radians
        y = Math.log(Math.tan((lat/2) + (Math.PI/4)));  // do the Mercator projection (w/ equator of 2pi units)
        y = (map_height / 2) - (map_width * y / (2 * Math.PI)) + y_pos;   // fit it to our map
    
        x -= x_pos;
        y -= y_pos;
    
        draw_point(x - half_dot, y - half_dot);
    }
    </script>
    </head>
    <body onload="plot_point(40.756, -73.986)">
        <!-- image found at http://www.math.ubc.ca/~israel/m103/mercator.png -->
        <img src="mercator.png" style="position:absolute;top:0px;left:0px">
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-30 22:35

    A basic conversion function in js would be:

    MAP_WIDTH = 1000;
    MAP_HEIGHT = 446;
    
    function convert(lat, lon){
        var y = ((-1 * lat) + 90) * (MAP_HEIGHT / 180);
        var x = (lon + 180) * (MAP_WIDTH / 360);
        return {x:x,y:y};
    }
    

    This will return the number of pixels from upper left. This function assumes the following:

    1. That your image is properly aligned with the upper left corner (0,0) aligning with 90* North by 180* West.
    2. That your coords are signed with N being -, S being +, W being - and E being +
    0 讨论(0)
  • 2020-11-30 22:39

    If you have a picture of the whole earth, the projection does always matter. But maybe I just don't understand your question.

    0 讨论(0)
提交回复
热议问题