10

I need to convert latitude longitude values into pixel positions as well as do the opposite. I've found many solutions to go from lat/lng->pixel, but can't find anything on the reverse.

A couple of notes:

  • The map is a fixed size, no zooming, no tiles.
  • I don't need anything super accurate, its not important.
  • Preferably mercator projection, but not required. I'm not actually display the result. (Any 2D projection)
  • I can't rely on any web based API's, ie: no Google Maps

A solution in almost any programming language would be fine, as long as it doesn't rely on any platform specific APIs.

This is an example of going from lat/lng->pixel:

var y = Math.round(((-1 * lat) + 90) * (this.MAP_HEIGHT / 180));
var x = Math.round((lng + 180) * (this.MAP_WIDTH / 360));
Tyler Egeto
  • 5,505
  • 3
  • 21
  • 29
  • 2
    You need to know which map projection the computation must work for. The example computation in your question will _not_ work for a Mercator map; it assumes an [equirectangular projection](http://en.wikipedia.org/wiki/Equirectangular_projection). – hmakholm left over Monica Aug 10 '11 at 23:25
  • I'm open to any 2D projection, equirectangular will meet my needs perfectly. I'm not visualizing the result, so I'm not tied to a specific projection. – Tyler Egeto Aug 10 '11 at 23:28
  • If you are not displaying anything, then what on earth (!) are you using pixels for in the first place? – hmakholm left over Monica Aug 10 '11 at 23:31
  • Doing some server side stuff that needs to translate lat/lng to a 2D plane, it eventually gets converted back to lat/lng before it gets visualized client side. Pixels is not a very accurate word for the problem, but helped me to express what I needed. – Tyler Egeto Aug 10 '11 at 23:41
  • But (latitude,longitude) _already_ constitutes 2D coordinates. You can call it "pixels" in your head (x=longitude, y=latitude) without changing them in any way, if that will help you visualize a computation. – hmakholm left over Monica Aug 10 '11 at 23:47
  • I needed to work with whole numbers for my particular solution. I don't doubt there are ways of accomplishing my goal without the conversion, (they're probably better), but that's the one I came up with. – Tyler Egeto Aug 11 '11 at 00:00
  • What unit is MAP_HEIGHT? – Michael T Oct 14 '20 at 09:21

1 Answers1

9
var y = Math.round(((-1 * lat) + 90) * (this.MAP_HEIGHT / 180));
var x = Math.round((lng + 180) * (this.MAP_WIDTH / 360));

Use some algebra and I came out with:

var lat=(y/(this.MAP_HEIGHT/180)-90)/-1
var lng = x/(this.MAP_WIDTH/360)-180

Not completely confident in that math since it was done in my head, but those should work, just make sure to test them first.

ChristopheCVB
  • 7,269
  • 1
  • 29
  • 54
Markcf
  • 165
  • 5