Search code examples
javascriptleafletzooming

Leaflet Zoom Button in Popup


I am trying to add a 'zoom to' button in a leaflet popup that will pan and zoom to the feature when clicked. I can't figure out exactly how to do this with the code below (I know I am massacring the code):

function getLoc(e){
    map.setView(e.latlng);
    }
        
        // Load Mile Castles
        $.ajax({url:'load_milecastles.php',
               success: function(response){
                   
                   
                       
                   jsnParks = JSON.parse(response);
                   lyrParks = L.geoJSON(jsnParks, 
                                { pointToLayer: function(feature,latlng){return L.marker(latlng,{icon: redMarker});}, 
                                  onEachFeature: function (feature, layer) {
                                layer.bindPopup(
                       "<center><h4><b>"+feature.properties.full_name+"</b></h4></center>" +
                       "<button onclick= 'getLoc(e)'>Zoom</button>");
                      }
                 }).addTo(map);

Solution

  • Replace your code with:

    function getLoc(latlng){
        map.setView(JSON.parse(latlng));
    }
    
    var latlngStr = JSON.stringify([layer.getLatLng().lat,layer.getLatLng().lng]);
    layer.bindPopup("<center><h4><b>"+feature.properties.full_name+"</b></h4></center>" +
                           "<button onclick= 'getLoc(\""+latlngStr+"\")'>Zoom</button>");
    
    
    1. e should be a variable but can not readed out because it is a string onclick='getLoc(e)'
    2. e never defined you should add your latlng to the function and not a event
    3. Now the latlng is converted to a array and then added as string to the function. When the function is called it convert it back to a array and then the view is moved to the latlng