How to find the x and y position given a latitude and longitude coordinate

geometrylinear algebraspherical trigonometry

I am building an app that allows me to track the user's position inside a building. For this I use GPS and an image of the floor plan.

I have the latitude and longitude of each of the four corners and I now want to work out what the x and y position is in the image based on the GPS coordinate I receive.

I have provided an image to make this a lot clearer:

Click here – don't have enough rep yet 🙁

I've tried many things so far, but this one came the closest:

Find the range between top left (min lat/lon) and bottom right (max lat/lon):

  • lonrange = |minLon – maxLon|
  • latrange = |minLat – maxLat|

Calculate the scale factors for pixel per degree:

  • scalex = width / lonrange
  • scaley = height / latrange

Now get pixel positions:

  • x = (currentLon – minLon) * scalex
  • y = (currentLat – minLat) * scaly

What I've done above is kinda accurate when the lat/lon point I'm trying to convert is somewhere directly between the topLeft and bottomRight of the image but gets wildly inaccurate the more I deviate towards the other corners.

I think it's probably because of how rotated my image is compared to the map but I don't know how to account for it (I don't even know how much it's rotated angle wise).

Any help would be appreciated!

Note: also I apologise if my tags are inaccurate! I'm not very well versed in terms of what is what in maths.

Best Answer

Using $x$ and $y$ coordinates is a method to describe a position in a plain. However, the earth is not a plane. Therefore, you need to use a projection to project the points, described as lat-lng-values on a reference ellipsoid, to points on a map. Many different map projections are known, each of them with different properties. The first step is to choose one projection that suits your need. For example, you could use UTM projections.

After you projected your coordinates onto the map, all you have to do is to perform a rotation (which can be achieved by applying a $2\times 2$ rotation matrix to a point) and translation (which can be achieved by adding a vector).

Related Question