In my android app I have simple "map", which is satellite map based image. I have exact LatLng
positions on two corners of this map: Left-Top and Right-Bottom to be precise. Now, by given LatLng
point I want to create a small view add place it on the map (a marker). In order to this I have to calculate percentage x and y in pixels on my "map".
So to sum up here's my data:
LatLng MAP_LEFT_TOP; //constant point
LatLng MAP_RIGHT_BOTTOM; //constant point
LatLng location; //point, which should be inside map rectangle
What I have to calculate:
float percentageX; //percentage x position of "location" on the map
float percentageY; //percentage y position of "location" on the map
Here I found function:
LatLng interpolate(LatLng from, LatLng to, double fraction)
and I need something, which works in the opposite way. Here's my implementation, but it doesn't give me correct result (the same for y/longitude):
double findFractionX(double latitudeLeftTop, double latitudeRightBottom, double latitude){
return (latitude - latitudeLeftTop) / (latitudeRightBottom - latitudeLeftTop);
}
Then I can get final position of the marker like this:
float imageViewWidth; //width of the imageView holding map
float imageViewHeight; //height of the imageView holding map
float x = percentageX * imageViewWidth;
float y = percentageY * imageViewHeight;
Edit: my mistake was using latitude to get x and longitude to get y while it's just the opposite.
Still something's wrong, here's how it looks in the app:
Here's where it should have been (I used scribble to make this example):
Just to make it clear I'm talking about point named "1.1", don't pay your attention for the others, they're hardcoded in the image itself.
Since I got another idea to write up, I'll just put both in a full answer to have more space.
First, check if you don't accidentally switched long
/lat
or x
/y
:
Long = x
and lat = y
.
Then, how does you view look that you add? While you get the exact position of the map marker, simply adding a view to that location may look off.
The view itself probably has a width and height itself and you may want it placed on top of the marker like when clicking on a store on Google maps? If you just put it at the calculated position, it will put its top-left corner at that position.