From 78588aa8ea1876b0d6664f56d17d60723be9ae9e Mon Sep 17 00:00:00 2001 From: euzuro Date: Mon, 22 May 2006 09:55:20 +0000 Subject: [PATCH] adding getPixelFromLonLat() function to Map.js -- the code is lifted from OpenLayers.Layer.Marker's drawMarker() function. also test added to ensure both translation functions return valid objects and that going back and forth is consistent. Note that i only test pixel-lonlat-pixel, because going from lonlat-pixel-lonlat there is loss due to the rounding in the lonlat-pixel phase git-svn-id: http://svn.openlayers.org/trunk/openlayers@246 dc9f47b5-9b13-0410-9fdd-eb0c1a62fdaf --- lib/OpenLayers/Map.js | 17 +++++++++++++++++ tests/test_Map.html | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/lib/OpenLayers/Map.js b/lib/OpenLayers/Map.js index 510b1b133d..f040c9e167 100644 --- a/lib/OpenLayers/Map.js +++ b/lib/OpenLayers/Map.js @@ -271,6 +271,23 @@ OpenLayers.Map.prototype = { center.lat - delta_y * res); }, + /** + * @param {OpenLayers.LonLat} lonlat + * + * @returns An OpenLayers.Pixel which is the passed-in OpenLayers.LonLat, + * translated into screen pixels given the current extent + * and resolution + * @type OpenLayers.Pixel + */ + getPixelFromLonLat: function (lonlat) { + var resolution = this.getResolution(); + var extent = this.getExtent(); + return new OpenLayers.Pixel( + Math.round(1/resolution * (lonlat.lon - extent.left)), + Math.round(1/resolution * (extent.top - lonlat.lat)) + ); + }, + /** * @param {OpenLayers.LonLat} lonlat * @param {int} zoom diff --git a/tests/test_Map.html b/tests/test_Map.html index e3d144d3cc..fa99cb3adf 100644 --- a/tests/test_Map.html +++ b/tests/test_Map.html @@ -113,6 +113,25 @@ } + function test_08_Map_px_lonlat_translation (t) { + t.plan( 3 ); + map = new OpenLayers.Map($('map')); + map.setCenter(new OpenLayers.LonLat(0, 0), 0); + + var pixel = new OpenLayers.Pixel(50,150); + var lonlat = map.getLonLatFromPixel(pixel); + t.ok( lonlat instanceof OpenLayers.LonLat, "getLonLatFromPixel returns valid OpenLayers.LonLat" ); + + var newPixel = map.getPixelFromLonLat(lonlat); + t.ok( newPixel instanceof OpenLayers.Pixel, "getPixelFromLonLat returns valid OpenLayers.Pixel" ); + + // WARNING!!! I'm faily sure that the following test's validity + // depends highly on rounding and the resolution. For now, + // in the default case, it seems to work. This may not + // always be so. + t.ok( newPixel.equals(pixel), "Translation to pixel and back to lonlat is consistent"); + } + function test_99_Map_destroy (t) { t.plan( 2 ); map = new OpenLayers.Map($('map'));