简体   繁体   中英

Leaflet - Center map on marker, zoom and open popup

I have leaflet map that draws markers from geojson and binds popups to them. GeoJSON feature collection is stored in geojsonFeature variable. The code looks like this:

<script>
    var map = L.map('map').setView([42.652, 18.102], 13);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    var sidebar = L.control.sidebar('sidebar').addTo(map);

    function onEachFeature(feature, layer) {
        var popupContent = '<h3>'+feature.properties.Naziv+'</h>';
        if (feature.properties.Slika) {
            popupContent += '<br /><img src="slike/'+feature.properties.Slika+'.jpg" alt="Slika" style="width:300px;">';
        }     
    layer.bindPopup(popupContent);
}

    L.geoJSON(geojsonFeature, {
        onEachFeature: onEachFeature
    }).addTo(map);
</script>

This works fine, but I want to add a list with features outside the map. The list would be clickable and an onClick event would pass feature id to the function that zooms the map on selected feature and opens the popup.

The only problem is that I don't know how to zoom map to the feature and open the popup programmatically using the point's ID from source GeoJSON.

Found a way to work around this. I added a clickable list of features outside of map with ID-s and "ref" class. Then I made the following jQuery listener:

$(".ref").click(function () {
        //extract ID from list HTML element
        var id=eval(this.id);
        //find object with extracted ID in original GeoJSON 
        //use object's coordinates and features to pan the map and display popup
        map.setView([geojsonFeature.features[id].geometry.coordinates[1], geojsonFeature.features[id].geometry.coordinates[0]], 16);
        var popupData = '<h3>'+geojsonFeature.features[id].properties.Naziv+'</h>';;
        if(geojsonFeature.features[id].properties.Slika) {
            popupData += '<br /><img src="slike/'+geojsonFeature.features[id].properties.Slika+'.jpg" alt="Slika" style="width:300px;">';
        }
        var popup = L.popup()
        .setLatLng([geojsonFeature.features[id].geometry.coordinates[1], geojsonFeature.features[id].geometry.coordinates[0]])
        .setContent(popupData)
        .openOn(map);            
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM