Convert pixel location to latitude / longitude and vice versa

I need to convert latitude longitude values โ€‹โ€‹to pixel positions, and also do the opposite. I found a lot of solutions to go from lat / lng-> pixel, but can't find anything on the back.

A few notes:

  • A map of a fixed size, without scaling, without fragments.
  • I donโ€™t need anything super precise, it doesnโ€™t matter.
  • Mercator projection is preferred, but not required. I do not show the result. (Any two-dimensional projection)
  • I cannot rely on any web APIs i.e. no google maps

A solution in almost any programming language will be perfect if it does not depend on any platform APIs.

This is an example transition 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)); 
+4
source share
1 answer
 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 sure about this math, since it was done in my head, but they should work, just check them first.

+5
source

All Articles