views:

830

answers:

4

I need an algorithm that will convert a GPS coordinate to a screen location on a displayed google map. I would think this would be simple- get the coordinates for the four corners of the displayed map, find the differential and create a scaling factor for a pixel location on the screen. Is this correct or am I missing something. I'm know this has been done ad nauseum but I am hoping I can hear from someone who has implemented it successfully or has a resource for implementing it.

+1  A: 

The Google Maps API lets you do stuff like this.

Here is some JS code I've written using the APIs that does something similar:

var map = new GMap2(document.getElementById("map"));

//...

var location = new GLatLng(37.771008, -122.41175);
map.setCenter(location);

var marker = new GMarker(location);
var overlay_caption = "Our location!";

GEvent.addListener(marker, "click", function() {
  marker.openInfoWindowHtml(overlay_caption);
});

map.addOverlay(marker);
marker.openInfoWindowHtml(overlay_caption);
Kip
A: 

You can also redirect the page to a new map with a URL like this:

http://maps.google.com/maps?q=37.771008,+-122.41175+(You+can+insert+your+text+here)&iwloc=A&hl=en

Kip
A: 

Basically you need the code for Transverse Mercator projection (which is used by Google maps and others). Here's a C# snippet I used my Kosmos software:

public Point2<int> ConvertMapToViewCoords (Point2<double> mapCoords)
{
    double x = (mapCoords.X - MapPosition.Longitude) / resolution;
    double y = Math.Log (Math.Tan (Math.PI*(0.25 + mapCoords.Y/360)))*u180dPiResolution;

    return new Point2<int> ((int)(x + viewWidthHalf), (int)((y0 - y) + viewHeightHalf));
}

variables used:

double resolution = 360.0 / (Math.Pow (2, MapPosition.ZoomFactor) * 256);
double u180dPiResolution = 40.7436654315252 * Math.Pow(2, MapPosition.ZoomFactor);
double y0 = Math.Log(Math.Tan(Math.PI * (0.25 + MapPosition.Latitude / 360))) * u180dPiResolution;
float viewWidthHalf = ViewWidth / 2.0f;
float viewHeightHalf = ViewHeight / 2.0f;

ZoomFactor is Google zoom level (see http://laudontech.com/GISBlog/?p=28). BTW the same code works for OpenStreetMap, Yahoo Maps etc., since they all use the same projection and tiling system.

Igor Brejc
A: 

If you need the pixel coordinate of a latitude/longitude position of a current instance of Google Maps you may use the fromLatLngToDivPixel() function.

Assuming map is an instance of an initialized GMap2:

var location = new GLatLng(37.771008, -122.41175);
var point = map.fromLatLngToDivPixel(location);

alert("X: " + point.x + ", Y: " + point.y);

Depending on your needs, see also fromLatLngToContainerPixel.

stefpet