Tips & Tricks: Getting a location from a mouse click

08 January 2016 by Richard Süselbeck

One of the more frequent questions about the HERE Maps JavaScript API is how to get a location based on a mouse click on the map. We actually have a very nice example of how to do this in our JavaScript API Explorer, but it's admittedly a little hidden, so let's have a closer look at how this works.

Getting the location of a click on the map using the HERE JavaScript API

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.

top