0
votes

I'm trying to get coordinates from a mouse click on the map.

The coordinates are right until I scroll the map. After that they are wrong - they are shifted from the position of the click. If I change the zoomlevel, next coordinates are right until I scroll the map again.

First I thought getLayerPxFromViewPortPx returns wrong value, because if I scroll to the left and to the top and click there it gives me a pixel with negative x and y. But I suppose it is the way it works and x and y are relative to the layers center.

Here is what I have:

map.events.register("click", map, function(e){
        var opx = map.getLayerPxFromViewPortPx(e.xy) ;
        var lonlat = map.getLonLatFromPixel(opx);
        console.log(lonlat)

        var marker = new OpenLayers.Marker(lonlat);
        markers.addMarker(marker)

What else could be failing?

2
Could you provide a complete example, including map and layers set-up?Alex Morega
I changed getLonLatFromPixel() with var lonlat = map.getLonLatFromViewPortPx(e.xy) and now it seems working. However I'm still curious why did the previous fail. About the complete example, you can find it here: dev.ivanatora.info/spirkiIvan Petrushev

2 Answers

1
votes

I changed getLonLatFromPixel() with var lonlat = map.getLonLatFromViewPortPx(e.xy) and now it seems working. However I'm still curious why did the previous fail.

0
votes

in init function()

 var click = new OpenLayers.Control.Click();
map.addControl(click);
click.activate();

init function out

OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
defaultHandlerOptions: {
    'single': true,
    'double': false,
    'pixelTolerance': 0,
    'stopSingle': false,
    'stopDouble': false
},

initialize: function (options) {
    this.handlerOptions = OpenLayers.Util.extend(
                    {}, this.defaultHandlerOptions
                );
    OpenLayers.Control.prototype.initialize.apply(
                    this, arguments
                );
    this.handler = new OpenLayers.Handler.Click(
                    this, {
                        'click': this.trigger
                    }, this.handlerOptions
                );
},

trigger: function (e) {
    var lonlat = map.getLonLatFromPixel(e.xy);

    N = lonlat.lat;
    E = lonlat.lon;

    alert("Bu koordinatlar civarındasınız: " + N + " N, " + E + " E");






}

});