Harry Wood
home
>
maps
>
examples
> openlayers >
OpenLayers Click Event
OpenLayers Click Event
Simple handling of click events (clicks anywhere on the basemap)
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <meta name="apple-mobile-web-app-capable" content="yes"> <title>OpenLayers Click Event Example</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/2.11/lib/OpenLayers.js"></script> <style type="text/css"> html, body, #mapdiv { width:100%; height:100%; margin:0; } .olImageLoadError { display: none; } /* no pink tiles */ </style> <script type="text/javascript"> //Set up a click handler 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) { //A click happened! var lonlat = map.getLonLatFromViewPortPx(e.xy) lonlat.transform( new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326") ); alert("You clicked near " + lonlat.lat + " N, " + + lonlat.lon + " E"); } }); var map; function init(){ map = new OpenLayers.Map('mapdiv'); map.addLayer(new OpenLayers.Layer.OSM()); map.zoomToMaxExtent(); var click = new OpenLayers.Control.Click(); map.addControl(click); click.activate(); } </script> </head> <body onload="init()"> <div id="mapdiv"></div> </body> </html>
view directly
Home
Blog
About
Maps
Other
Contact