Convert LongLat To Mercator

From Openmoko

Jump to: navigation, search

Here is a little piece of code i have wrote to be able to convert any longitude / latitude to a x,y coordinate plotted on a map based on a Mercator Projection. For this to work, you will need 2 points you know on the map (Set up those two points in p1x, p1y, p1lat, p1long, p2x, p2y, p2lat, p2long). Then put the longitude / latitude in fakeLong / fakeLat and it should give you the x,y coordinate of this point. This is wrote with C++.

#include <math.h>
#include <iostream>

// This is the first reference point (Here it is a top left corner point on the example map i used).
        int     p1x     = 0;
        int     p1y     = 0;
        float   p1lat   = 45.554141f;
        float   p1long  = 0.633598f;

// The second reference point (Bottom right corner of my example map):
        int     p2x     = 1500;
        int     p2y     = 1500;
        float   p2lat   = 45.510440f;
        float   p2long  = 0.696285f;

        int     delta_x         = abs(p1x - p2x);
        float   delta_longitude = fabs(p1long - p2long);
        float   x_factor                = delta_x / delta_longitude;

        float   p1mercY         = lat2UMT(p1lat);
        float   p2mercY         = lat2UMT(p2lat);
        int     delta_y               = abs(p1y-p2y);
        float   delta_mercator  = fabs(p1mercY-p2mercY);
        float   y_factor                = delta_y / delta_mercator;

// Here we input the point we want to convert.
        float   fakeLat        = 45.530824f;
        float   fakeLong    = 0.663729f;
        
        int     plotX, plotY;
        plotX   = p1x + (int)((fakeLong-p1long)*x_factor);
        if (fakeLat < p1lat)
                plotY   = p1y + (int)((fabs(p1mercY-lat2UMT(fakeLat)))*y_factor);
        else
                plotY   = p1y - (int)((fabs(p1mercY-lat2UMT(fakeLat)))*y_factor);
        std::cout << plotX << "," << plotY << ".\n";

float rad (float angle) {
        return angle*(M_PI/180.0f);
}

float lat2UMT(float latitude) {
        return 0.5f*log((1.0f+sin(rad(latitude))) / (1.0f-sin(rad(latitude))));
}
Personal tools