Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pixel location to latitude/longitude & vise versa

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));
like image 858
Tyler Egeto Avatar asked Aug 10 '11 23:08

Tyler Egeto


People also ask

How do you convert degrees latitude to meters?

Note that one degree of longitude is 111 km at the equator, but less for other latitudes. There's a simple approximative formula to find the length in km of 1° of longitude in function of latitude : 1° of longitude = 40000 km * cos (latitude) / 360 (and of course it gives 111 km for latitude = 90°).

What translated coordinates to pixels in D3?

„The translation offset determines the pixel coordinates of the projection's center“ (D3 Documentation).

How do you convert numbers to latitude?

Latitude can be stated in degree form -- with minutes and seconds -- or in decimal form. You can convert a latitudinal measurement from degrees to a decimal by following a mathematical formula. Divide minutes by 60. For example, if you had a degree followed by 45 minutes, you would divide 45 by 60 to get 0.75.


1 Answers

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.

like image 175
Markcf Avatar answered Sep 30 '22 10:09

Markcf