Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript place marker on image onclick

I have this map that will place coordinates into inputfields when you click on the map. It would be great to have a marker to place on the map that will show where was clicked.

Only thing is that the examples I find will leave all of the points on the map when you re-click it, while I only need a marker on the last position clicked on the image. Anyone that can help with this? It is like this or this example. The first one is good but will place marker image under the image itself, and the second one will leave all of the dots on the image.

All help is appreciated!

like image 947
dnsko Avatar asked Jun 29 '16 07:06

dnsko


1 Answers

Extending the accepted solution on Add a marker to an image in javascript?

I just added a unique class to the appending div and then removed all elements with that class on every click event.

MODIFIED CODE:

$(document).ready(function(){ 
    $(document).click(function (ev) {
        if($('div').length < 3) {
            $(".marker").remove();      // remove all existing markers
            $("body").append(            
                $('<div class="marker"></div>').css({       // include a class
                    position: 'absolute',
                    top: ev.pageY + 'px',
                    left: ev.pageX + 'px',
                    width: '10px',
                    height: '10px',
                    background: '#000000'
                })              
            );
        }
    });

});

See the action: JSFIDDLE

Update as requested in comment: FIDDLE

like image 190
Fr0zenFyr Avatar answered Oct 08 '22 10:10

Fr0zenFyr