find nearest point and show properties from nearest point into user created marker in Leaflet

Tags: ,



Example I’m trying to find the nearest markers on a map of a specific location with Leaflet, want to show popup info on user created marker which is find nearest point, popup info should be include with nearest point properties from the geojson data layer. example maker.bindpopup(feature.properties.name).addTo(map)

(function() {
   
    var geojosn1= 'url1';
    var geojsonn2= 'url2';
    
    var stations,
        $body = $('body'),
        $locate = $('#locate'),
        $findNearest = $('#find-nearest'),
        $status = $('#status');
    
    $.getJSON(geojosn1, function(data) {
  
        //$('#loader').fadeOut();
        $body.addClass('loaded');
        
        stations = L.geoJson(data, {
            
            pointToLayer : function(feature, latlng) {
               return L.circleMarker(latlng, {
                   stroke : false,
                   fillColor : 'orange',
                   fillOpacity : 1,
                   radius: 2
               });
            }
        }).addTo(map); 
        

        $locate.fadeIn().on('click', function(e) {
            
            $status.html('finding your location');
            
            if (!navigator.geolocation){
                alert("<p>Sorry, your browser does not support Geolocation</p>");
                return;
            }
            
            $body.removeClass('loaded');
              
            navigator.geolocation.getCurrentPosition(success, error);
            
           $locate.fadeOut();
            
        });   
    });

    function success(position) {
        
        $body.addClass('loaded');
        
        var currentPos = [position.coords.latitude,position.coords.longitude];
        
        map.setView(currentPos, zoomLevel);

        var myLocation = L.marker(currentPos)
                            .addTo(map)
                            .bindTooltip("you are here")
                            .openTooltip();
        
            
        $findNearest.fadeIn()
            .on('click', function(e) {
                
                $findNearest.fadeOut();
                
                $status.html('finding your nearest locations')
            
                queryFeatures(currentPos, 5);
            
                myLocation.unbindTooltip();
            
                
        });

    };

   
    function queryFeatures(currentPos, numResults) {
        
        var distances = [];
        
        stations.eachLayer(function(l) {
            
            var distance = L.latLng(currentPos).distanceTo(l.getLatLng())/1000;
            
            distances.push(distance);

        });
        
        distances.sort(function(a, b) {
            return a - b;
        });
        
        var stationsLayer = L.featureGroup();
            

        stations.eachLayer(function(l) {
            
            var distance = L.latLng(currentPos).distanceTo(l.getLatLng())/1000;
            
            if(distance < distances[numResults]) {
                
                l.bindTooltip(distance.toLocaleString() + ' km from current location.');
                
                L.polyline([currentPos, l.getLatLng()], {
                    color : 'orange',
                    weight : 2,
                    opacity: 1,
                    dashArray : "5, 10"
                }).addTo(stationsLayer);
                
            }
        });
        
        map.flyToBounds(stationsLayer.getBounds(), {duration : 3, easeLinearity: .1 });
        
        map.on('zoomend', function() {
          
            map.addLayer(stationsLayer);
        })
      
    }

})()

Answer

Try this:

function queryFeatures(currentPos, numResults) {
    var stationsLayer = L.featureGroup();
    
    var result = {
        layer: null,
        dis: 0,
        marker: null
    };
    
    stations.eachLayer(function(l) {
        var distance = L.latLng(currentPos).distanceTo(l.getLatLng())/1000;
        if(result.layer == null || distance < result.dis) {
            var line = L.polyline([currentPos, l.getLatLng()], {
                color : 'orange',
                weight : 2,
                opacity: 1,
                dashArray : "5, 10"
            });
            
            result = {
                layer: line,
                dis: distance,
                marker: l
            };
        }
    });
    
    result.marker.bindTooltip(result.dis.toLocaleString() + ' km from current location.');
    result.layer.addTo(stationsLayer);
    
    map.flyToBounds(stationsLayer.getBounds(), {duration : 3, easeLinearity: .1 });
    
    map.on('zoomend', function() {
        map.addLayer(stationsLayer);
    });
}


Source: stackoverflow