Tips & Tricks: Getting a location from a mouse click
08 January 2016 by Richard Süselbeck
First, make sure have the mapsjs-mapevents module loaded to enable events on your map.
Second, make sure you have instantiated the MapEvents class. The following line of code also implements the default interactions (pan, zoom, etc.) for the map.
The event we are looking for is tap, which signals that a pointer has touched the map surface or a map object. Next we have to add an event listener to check for mouse clicks.
As you can see, evt holds the coordinates of the mouse click in relation to the map's viewport. This may already be what you're looking for. If so, congratulations: you're done! In many cases however, you are actually interested in the geographic coordinates associated with the click's location. To convert the screen coordinates to a latitude and longitude, you can use the screenToGeo method. Wrapped up in a function our code now looks like this.
That's it! Pretty simple. You can check out the full HTML+JS code in our API Explorer.