Home Ask Login Register

Developers Planet

Your answer is one click away!

MCattelan February 2016

Unable to display correct coordinates of a selected marker

I built a map with Leaflet (inside a Qlikview extension) with many markers. I want my users go to the map and when they double click on a marker, it displays coordinates. With the following code, when I click on a marker, I have always coordinates of last marker fetched, not the selected one. I want to put coordinates in latSel e lonSel variables.

for (var i=0,k=_this.Data.Rows.length;i<k;i++){
       var row = _this.Data.Rows [i];

       var latitude = parseFloat(row[0].text.replace(",","."));
       var longitude = parseFloat(row[1].text.replace(",","."));

       //Check to see coordinates are valid
        if (latitude != NaN && latitude !='' && latitude <= 90 && latitude >= -90 && longitude != NaN && longitude !='' && longitude <= 180 && latitude >= -180) {

         var latlng = new L.LatLng(latitude, longitude);
         var poptext = 'Lat & Long:'+latlng+'<br/>'+ row[2].text +'<br/>'+ 'Measure: ' + row[4].text;
         var marker = L.marker(latlng).addTo(map).bindPopup(poptext);

         marker.on('dblclick', function(e){
                                        latSel = marker.getLatLng().lat;
                                        lonSel = marker.getLatLng().lng
                                        //_this.Data.SelectTextsInColumn(0, true, latSel);
                                        alert("latitude = " + latSel);


        } else {

What I'm doing wrong? Thanks in advance.


chrki February 2016

Assigning onClick listeners in loops can be a bit tricky (search for "javascript onclick loop" in your favourite search engine and you will find some solutions).

Instead of using the marker variable, in Leaflet you can use the variable this inside the callback which refers back to the marker, like so:

marker.on('dblclick', function(e){
    latSel = this.getLatLng().lat;
    lonSel = this.getLatLng().lng;

See demo code here: http://plnkr.co/edit/RU3SsoI6A16AYOQAq0xV?p=preview

Post Status

Asked in February 2016
Viewed 1,803 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life