Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

HERE Maps API - How to find the nearest Marker

From Wiki
Jump to: navigation, search

This code example shows how to find the nearest Marker from any point on the map. The code is useful for finding the Markers that are located close to the user's current position or destination.

Article Metadata
Code ExampleTested with
Devices(s): Firefox , Internet Explorer, Google Chrome, Opera
Platform(s): Web Browser
Dependencies: HERE Maps API 2.5.3
Keywords: HERE Maps, JavaScript, Marker
Created: Maveric (13 Nov 2011)
Last edited: jasfox (20 Dec 2013)


This example demonstrates how to find the nearest map Marker from any point on the map. In the example there are five Markers on the Nokia Map and you can click anywhere on the map. Based on where you clicked, the script will calculate the distance to the Marker that is located closest to the point of your click. To display the result, the label text of the Marker is retrieved and shown on the page.


Example code

After setting up five markers, the code continues by adding a click event to the map.

function addClickEventListenerToMap(map){
map.addListener("click", function(evt){
var coords = map.pixelToGeo(evt.targetX , evt.targetY);
findNearestMarker (coords);
}, false);

The findNearestMarker() method iterates through each marker on the map and calculates the distance. The lowest distance so far is kept.

function findNearestMarker(coords) { 
var minDist = 1000;
var nearest_text = "*None*";
for (i=0; i< map.objects.getLength(); i++)
if ( map.objects.get(i) instanceof ) {
var markerDist = map.objects.get(i).coordinate.distance(coords);
if (markerDist < minDist) {
minDist = markerDist;
nearest_text = map.objects.get(i).text
alert (nearest_text);

The fully working example can be found at:

This page was last modified on 20 December 2013, at 15:52.
154 page views in the last 30 days.