Convert long/lat to pixel x/y on a given picture
Asked Answered
M

10

68

I have a city map of Moscow. We modified a Google Maps image with some artistic elements, but the relation between GPS coordinates and pixels remains the same.

Problem: How do I convert GPS coordinates from various data points we have into pixel coordinates in the image?

Ideally I can do this in Javascript, but PHP would be OK.


I know that on small scales (for example on city scales) it to make simply enough (it is necessary to learn what geographic coordinates has one of picture corners, then to learn "price" of one pixel in geographic coordinates on a picture on axes OX and OY separately).

But on the big scales (country scale) "price" of one pixel will be not a constant, and will vary strongly enough and the method described above cannot be applied.

How to solve a problem on country scales?


Update:

I do not use API Google Maps, I have only: geographic coordinates of the object (they are from google maps), I still have at my site a simple picture *. gif, in which I must draw a point corresponding geographic coordinates.

Monocycle answered 16/4, 2010 at 6:39 Comment(6)
Are you using v2 or v3 of the api?Beacham
What exactly do you mean by "in co-ordinates of google"? Specifically, do you mean you have coordinates in Mercator eastings and northings, or do you have geographic coordinates in latitude and longitude?Montage
Also, this may be useful to you: sharpgis.net/post/2007/07/27/…Montage
@Daniel Pryden, I will correct my question in the light of your comments. I really mean geographic coordinates.Monocycle
I'd still like to know which version of the API you're using.Beacham
@Peter Bailey, I do not use API. Geographic coordinates I take directly from google maps; a "map of the city" lies on the site as a simple image *.gif.Monocycle
S
74

The key to all of this is understanding map projections. As others have pointed out, the cause of the distortion is the fact that the spherical (or more accurately ellipsoidal) earth is projected onto a plane.

In order to achieve your goal, you first must know two things about your data:

  1. The projection your maps are in. If they are purely derived from Google Maps, then chances are they are using a spherical Mercator projection.
  2. The geographic coordinate system your latitude/longitude coordinates are using. This can vary, because there are different ways of locating lat/longs on the globe. The most common GCS, used in most web-mapping applications and for GPS's, is WGS84.

I'm assuming your data is in these coordinate systems.

The spherical Mercator projection defines a coordinate pair in meters, for the surface of the earth. This means, for every lat/long coordinate there is a matching meter/meter coordinate. This enables you to do the conversion using the following procedure:

  1. Find the WGS84 lat/long of the corners of the image.
  2. Convert the WGS lat/longs to the spherical Mercator projection. There conversion tools out there, my favorite is to use the cs2cs tool that is part of the PROJ4 project.
  3. You can safely do a simple linear transform to convert between points on the image, and points on the earth in the spherical Mercator projection, and back again.

In order to go from a WGS84 point to a pixel on the image, the procedure is now:

  1. Project lat/lon to spherical Mercator. This can be done using the proj4js library.
  2. Transform spherical Mercator coordinate into image pixel coordinate using the linear relationship discovered above.

You can use the proj4js library like this:

// include the library
<script src="lib/proj4js-combined.js"></script>  //adjust the path for your server
                                                 //or else use the compressed version
// creating source and destination Proj4js objects
// once initialized, these may be re-used as often as needed
var source = new Proj4js.Proj('EPSG:4326');    //source coordinates will be in Longitude/Latitude, WGS84
var dest = new Proj4js.Proj('EPSG:3785');     //destination coordinates in meters, global spherical mercators projection, see http://spatialreference.org/ref/epsg/3785/


// transforming point coordinates
var p = new Proj4js.Point(-76.0,45.0);   //any object will do as long as it has 'x' and 'y' properties
Proj4js.transform(source, dest, p);      //do the transformation.  x and y are modified in place

//p.x and p.y are now EPSG:3785 in meters
Scend answered 22/4, 2010 at 8:31 Comment(2)
@fmark, plugged the code, as you said, the script gives an error on the line Proj4js.Proj = OpenLayers.Class({...}) it said: OpenLayers is not defined. How solve the problem?Monocycle
How do I find the WGS84 lat/long of the corners of the image ?Riverhead
L
18

You will have to implement the Google Maps API projection in your language. I have the C# source code for this:

public class GoogleMapsAPIProjection
{
    private readonly double PixelTileSize = 256d;
    private readonly double DegreesToRadiansRatio = 180d / Math.PI;
    private readonly double RadiansToDegreesRatio = Math.PI / 180d;
    private readonly PointF PixelGlobeCenter;
    private readonly double XPixelsToDegreesRatio;
    private readonly double YPixelsToRadiansRatio;

    public GoogleMapsAPIProjection(double zoomLevel)
    {
        var pixelGlobeSize = this.PixelTileSize * Math.Pow(2d, zoomLevel);
        this.XPixelsToDegreesRatio = pixelGlobeSize / 360d;
        this.YPixelsToRadiansRatio = pixelGlobeSize / (2d * Math.PI);
        var halfPixelGlobeSize = Convert.ToSingle(pixelGlobeSize / 2d);
        this.PixelGlobeCenter = new PointF(
            halfPixelGlobeSize, halfPixelGlobeSize);
    }

    public PointF FromCoordinatesToPixel(PointF coordinates)
    {
        var x = Math.Round(this.PixelGlobeCenter.X
            + (coordinates.X * this.XPixelsToDegreesRatio));
        var f = Math.Min(
            Math.Max(
                 Math.Sin(coordinates.Y * RadiansToDegreesRatio),
                -0.9999d),
            0.9999d);
        var y = Math.Round(this.PixelGlobeCenter.Y + .5d * 
            Math.Log((1d + f) / (1d - f)) * -this.YPixelsToRadiansRatio);
        return new PointF(Convert.ToSingle(x), Convert.ToSingle(y));
    }

    public PointF FromPixelToCoordinates(PointF pixel)
    {
        var longitude = (pixel.X - this.PixelGlobeCenter.X) /
            this.XPixelsToDegreesRatio;
        var latitude = (2 * Math.Atan(Math.Exp(
            (pixel.Y - this.PixelGlobeCenter.Y) / -this.YPixelsToRadiansRatio))
            - Math.PI / 2) * DegreesToRadiansRatio;
        return new PointF(
            Convert.ToSingle(latitude),
            Convert.ToSingle(longitude));
    }
}

Source:

http://code.google.com/p/geographical-dot-net/source/browse/trunk/GeographicalDotNet/GeographicalDotNet/Projection/GoogleMapsAPIProjection.cs

Lightfingered answered 25/4, 2010 at 1:45 Comment(3)
I double-checked and this matches the gheat code referred to above, which was extracted from the actual JS shipped by Google Maps servers. So I think we can say: problem solved.Anemology
Thanks @Jader Dias. Your code worked for me. I have taken static google map of size 256*256.Flagman
Shouldn't the FromPixelToCoordinates method rather return PointF(Convert.ToSingle(longitude), Convert.ToSingle(latitude)) ? [+1]Eyestalk
A
8

So you want to take latitude/longitude coordinates and find out the pixel coordinates on your image of that location?

The main GMap2 class provides transformation to/from a pixel on the displayed map and a lat/long coordinate:

Gmap2.fromLatLngToContainerPixel(latlng)

For example:

var gmap2 = new GMap2(document.getElementById("map_canvas"));
var geocoder = new GClientGeocoder();

geocoder.getLatLng( "1600 Pennsylvania Avenue NW Washington, D.C. 20500",
    function( latlng ) {
        var pixel_coords = gmap2.fromLatLngToContainerPixel(latlng);

        window.alert( "The White House is at pixel coordinates (" + 
            pixel_coodrs.x + ", " + pixel_coords.y + ") on the " +
            "map image shown on this page." );
    }
);

So assuming that your map image is a screen grab of the Google Map display, then this will give you the correct pixel coordinate on that image of a lat/long coordinate.

Things are trickier if you're grabbing tile images and stitching them together yourself since the area of the complete tile set will lie outside the area of the displayed map.

In this case, you'll need to use the left and top values of the top-left image tile as an offset from the coordinates that fromLatLngToContainerPixel(latlng:GLatLng) gives you, subtracting the left coordinate from the x coordinate and top from the y coordinate. So if the top-left image is positioned at (-50, -122) (left, top), and fromLatLngToContainerPixel() tells you a lat/long is at pixel coordinate (150, 320), then on the image stitched together from tiles, the true position of the coordinate is at (150 - (-50), 320 - (-122)) which is (200, 442).

It's also possible that a similar GMap2 coordinate translation function:

GMap2.fromLatLngToDivPixel(latlng:GLatLng)

will give you the correct lat/long to pixel translation for the stitched-tiles case - I've not tested this, nor is it 100% clear from the API docs.

See here for more: http://code.google.com/apis/maps/documentation/reference.html#GMap2.Methods.Coordinate-Transformations

Adjutant answered 22/4, 2010 at 11:2 Comment(0)
C
7

You may have a look at code that used on gheat, it's ported from js to python.

Clansman answered 17/4, 2010 at 17:1 Comment(1)
The link is offlineAcademy
W
4

The translation you are addressing has to do with Map Projection, which is how the spherical surface of our world is translated into a 2 dimensional rendering. There are multiple ways (projections) to render the world on a 2-D surface.

If your maps are using just a specific projection (Mercator being popular), you should be able to find the equations, some sample code, and/or some library (e.g. one Mercator solution - Convert Lat/Longs to X/Y Co-ordinates. If that doesn't do it, I'm sure you can find other samples - https://stackoverflow.com/search?q=mercator. If your images aren't map(s) using a Mercator projection, you'll need to determine what projection it does use to find the right translation equations.

If you are trying to support multiple map projections (you want to support many different maps that use different projections), then you definitely want to use a library like PROJ.4, but again I'm not sure what you'll find for Javascript or PHP.

Warnock answered 21/4, 2010 at 23:18 Comment(2)
PROJ.4 is great, but when you're already dealing with maps you're getting from Google Maps, it's easier just to use the coordinate transformation API it already provides. This handles projection translation (Google Maps seems to use Mercatorhttp://code.google.com/apis/maps/documentation/reference.html#GMercatorProjection) and makes it easy to go from lat/long to a pixel.Adjutant
@Donnelly - Excellent point - she did say her map image matches Google's map image. GMercatorProjection should be an answer in itself - you should add it as a separate answer [alternatively, I'll update this answer to include it]. I did read the second part of her question (the part below the line) to be a more general about how to match lat/lon coordinates to map images in general (not necessarily Google), so I tried to give a more general answer. I might have been reading a much into her question.Warnock
T
3

If each pixel is assumed to be of the same area then the following article about converting distances to longitude/latitude co-ordinates may be of some help to you:

http://www.johndcook.com/blog/2009/04/27/converting-miles-to-degrees-longitude-or-latitude/

Tammy answered 16/4, 2010 at 7:21 Comment(1)
It is far enough from my problem, I do not know as it it is possible to use.Monocycle
E
3

You need formulas to convert latitude and longitude to rectangular coordinates. There are a great number to choose from and each will distort the map in a different way. Wolfram MathWorld has a good collection:

http://mathworld.wolfram.com/MapProjection.html

Follow the "See Also" links.

Ezzo answered 16/4, 2010 at 11:18 Comment(0)
O
3

One of the important things to take into account is the "zoom" level of your projection (for Google Maps in particular).

As Google explains it:

At zoom level 1, the map consists of 4 256x256 pixels tiles, resulting in a pixel space from 512x512. At zoom level 19, each x and y pixel on the map can be referenced using a value between 0 and 256 * 2^19

( See https://developers.google.com/maps/documentation/javascript/maptypes?hl=en#MapCoordinates)

To factor in the "zoom" value, I recommend the simple and effective deltaLonPerDeltaX and deltaLatPerDeltaY functions below. While x-pixels and longitudes are strictly proportional, this is not the case for y-pixels and latitudes, for which the formula requires the initial latitude.

// Adapted from : http://blog.cppse.nl/x-y-to-lat-lon-for-google-maps


window.geo = {

    glOffset: Math.pow(2,28), //268435456,
    glRadius:  Math.pow(2,28) / Math.PI,
    a: Math.pow(2,28),
    b: 85445659.4471,
    c: 0.017453292519943,
    d: 0.0000006705522537,
    e: Math.E, //2.7182818284590452353602875,
    p: Math.PI / 180,

    lonToX: function(lon) {
        return Math.round(this.glOffset + this.glRadius * lon * this.p);
    },

    XtoLon: function(x) {
        return -180 + this.d * x;
    },

    latToY: function(lat) {
        return Math.round(this.glOffset - this.glRadius *
                          Math.log((1 + Math.sin(lat * this.p)) /
                          (1 - Math.sin(lat * this.p))) / 2);
    },

    YtoLat: function(y) {
        return Math.asin(Math.pow(this.e,(2*this.a/this.b - 2*y/this.b)) /
                                 (Math.pow(this.e, (2*this.a/this.b - 2*y/this.b))+1) -
                                 1/(Math.pow(this.e, (2*this.a/this.b - 2*y/this.b))+1)
                        ) / this.c;
    },

    deltaLonPerDeltaX: function(deltaX, zoom) {
        // 2^(7+zoom) pixels <---> 180 degrees
        return deltaX * 180 / Math.pow(2, 7+zoom);
    },

    deltaLatPerDeltaY: function(deltaY, zoom, startLat) {
        // more complex because of the curvature, we calculte it by difference
        var startY = this.latToY(startLat),
            endY = startY + deltaY * Math.pow(2, 28-7-zoom),
            endLat = this.YtoLat(endY);

        return ( endLat - startLat ); // = deltaLat
    }
}
Ory answered 7/8, 2014 at 21:0 Comment(1)
would you give a example of use ?Chert
M
2

my approach works without a library and with cropped maps. Means it works with just parts from a Mercator image. Maybe it helps somebody: https://mcmap.net/q/82798/-mercator-longitude-and-latitude-calculations-to-x-and-y-on-a-cropped-map-of-the-uk

Meteorite answered 2/5, 2012 at 5:51 Comment(0)
M
0

Struggled with this - Have both openstreet map and google street map and wanted to project an external graphic image

var map = new OpenLayers.Map({
            div:"map-id",
            allOverlays: true
    });
    var osm = new OpenLayers.Layer.OSM("OpenStreeMao");
    var gmap = new OpenLayers.Layer.Google("Google Streets", {visibility: false});

    map.addLayers([osm,gmap]);

    var vectorLayer = new OpenLayers.Layer.Vector("IconLayer");


    var lonlatObject = new OpenLayers.LonLat(24.938622,60.170421).transform(
            new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()
    );
    console.log(lonlatObject);

    var point = new OpenLayers.Geometry.Point(lonlatObject.lon, lonlatObject.lat);
    console.log(point);

    var point2 = new OpenLayers.Geometry.Point(lonlatObject.x, lonlatObject.y);
    console.log(point2);

    var feature = new OpenLayers.Feature.Vector(point, null, {
        externalGraphic:  "http://cdn1.iconfinder.com/data/icons/SUPERVISTA/networking/png/72/antenna.png",
        graphicWidth: 72,
        graphicHeight: 72,
        fillOpacity: 1
    });


    vectorLayer.addFeatures(feature);

    map.addLayer(vectorLayer);


    map.setCenter(
            new OpenLayers.LonLat(24.938622,60.170421).transform(
            new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()
            ),
            12);

     map.addControl(new OpenLayers.Control.LayerSwitcher());

http://jsfiddle.net/alexcpn/N9dLN/8/

Madelyn answered 22/1, 2013 at 7:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.