MapKit JS add annotation on user click?

I looked through supported events for mapkit.Map, however I couldn't find anything that would allow me to setup an event listener that adds an annotation on the location of user mouse click.


I understand that MapKit JS is still in beta, but I really expected this to be in the very first alpha release of annotations. Will this be supported?

Accepted Reply

MapKit JS relies as much as possible on existing DOM events. Here is an example using native DOM events to add annotations to a map on user click:


map.element.addEventListener("click", function(event) {
    if (event.target.parentNode !== map.element) {
        // This condition prevents clicks on controls. Binding to a 
        // secondary click is another option to prevent conflict
        return;
    }
    var domPoint = new DOMPoint(event.pageX, event.pageY);
    var coordinate = map.convertPointOnPageToCoordinate(domPoint);
    map.addAnnotation(new mapkit.MarkerAnnotation(coordinate));
});


If there are ways you would like to see this improved during or after the Beta, please file an enhancement request via Apple Bug Reporter.

Replies

MapKit JS relies as much as possible on existing DOM events. Here is an example using native DOM events to add annotations to a map on user click:


map.element.addEventListener("click", function(event) {
    if (event.target.parentNode !== map.element) {
        // This condition prevents clicks on controls. Binding to a 
        // secondary click is another option to prevent conflict
        return;
    }
    var domPoint = new DOMPoint(event.pageX, event.pageY);
    var coordinate = map.convertPointOnPageToCoordinate(domPoint);
    map.addAnnotation(new mapkit.MarkerAnnotation(coordinate));
});


If there are ways you would like to see this improved during or after the Beta, please file an enhancement request via Apple Bug Reporter.

Thanks, for your reply, Eric and I appologise for the late response. I will definitely try this out.

This approach works with one bug - the annotation gets added each time the finger is lifted from the button - including ending of a drag. But it's a good start nonetheless. Thanks again!

Hi Eimantas, did you find a solution to prevent the firing of the click event at the end of a drag?

Hi,

How can I remove the annotations when added

        map.annotations[0].removeAnnotation;
        map.removeAnnotation[0];
map.removeAnnotations;


i tried these but none work

please help

The Add Annotations example at https://developer.apple.com/maps/web/shows how to add annotations on click and also how to remove annotations.