hey guys,

How to convert the lat/long (in decimal) to x,y pixel.
my map has a height and width of 800,500

thnx

regards,

Nishan

Dani AI

Generated

— two pieces of information are required before mapping lat/lon to pixels: the map image's geographic bounding box (minLon, maxLon, minLat, maxLat) and the projection used. If the image is a simple equirectangular (plate carrée) image, convert linearly. With a top-left pixel origin (0,0):

x = (lon - minLon) / (maxLon - minLon) width
y = (maxLat - lat) / (maxLat - minLat)
height

Example Java (equirectangular):

public static Point latLonToPixelEquirect(double lat, double lon,
    double minLat, double maxLat, double minLon, double maxLon,
    int width, int height) {
    double xNorm = (lon - minLon) / (maxLon - minLon);
    double yNorm = (maxLat - lat) / (maxLat - minLat); // flip Y for top-left origin
    int x = (int)Math.round(xNorm * (width - 1));
    int y = (int)Math.round(yNorm * (height - 1));
    x = Math.max(0, Math.min(width - 1, x));
    y = Math.max(0, Math.min(height - 1, y));
    return new Point(x, y);
}

For web maps (Google/OSM) the standard is Web Mercator (not linear in latitude). Convert latitude to Mercator Y using ln(tan(pi/4 + lat/2)), normalize against the mercator of the map bounds, then scale to pixels. Clamp latitudes to about +/-85.05112878 degrees to avoid infinities.

Minimal Mercator sketch:

private static double latToMerc(double lat) {
    double r = Math.toRadians(lat);
    return Math.log(Math.tan(Math.PI / 4.0 + r / 2.0));
}

Then normalize lon linearly and mercator Y against lat bounds, flip Y for top-left origin as above.

Checklist / troubleshooting:

  • Confirm whether the image is equirectangular or Web Mercator and get exact min/max lat/lon.
  • Ensure longitude wrapping (e.g., -180/180) is handled for maps crossing the antimeridian.
  • Test with known points (lat=0,lon=0 should be center for world equirectangular with bounds [-180,180] and [-90,90]).
  • Clamp and round pixel values and verify the image origin (top-left vs bottom-left).

pointed to the old thread; this summary provides standalone, ready-to-run code and the key conceptual checks needed for an 800x500 image.

Recommended Answers

All 3 Replies

hi,

i'm sorry about the similarity of the topics but now i want to convert lat/long decimal to pixels in the map.

i thought it would be good to start a new thread.

hope u guys can help me on this.

See my post on the other thread.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.