[GIS] Leaflet JS – open popup on button click

htmljavascriptleaflet

New to JavaScript, coming from Python background. Created a custom control and have added buttons inside the _div using a for loop and innerHTML.

I want to zoom to and open the popup of a layer of the specific button I click. When I click on the button the function zooms to the marker, but does not open the popup.

The popup is definitely attached, since when I click on the marker the popup opens. When I enter the same command into the web console tool, the map zooms to and then opens the popup. Not sure what I am doing wrong.

What really confuses me is the fact that the function behaves differently when I use the button vs when I use the web console.

//variables
var map_object = L.map('mapid');
var map_tile_object = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
var resume_markers = []
var resume_control = L.control();
var resume_control_title = '<h4>Interactive Map</h4>';
var resume_control_description = '<p>Click on item for more information</p>';

//functions
function zoomTo(num) {
  var feature_cord = resumeData[num].geometry.coordinates;
  var markerBounds = L.latLng(feature_cord[1], feature_cord[0]);
  map_object.setView(markerBounds, 18);
  console.log(num);
  resume_markers[num].openPopup();
};

function main(map, tiles, data, resume, title, description){
    map.setView([41.505, -77], 6);
    tiles.addTo(map);
    for (x in data){
      var popup_content = data[x].properties.responsibilities;
      var marker = L.geoJSON(data[x]).bindPopup(popup_content);
      resume_markers.push(marker);
    };

    for (x in resume_markers){
      resume_markers[x].addTo(map);
    };

    resume.onAdd = function(map) {
      this._div = L.DomUtil.create('div', 'resume');
      this._div.innerHTML = title + '<br>' + description;
      return this._div;
    };

    resume.addTo(map);
    for (var i = 0; i < resume_markers.length; ++i){
      resume._div.innerHTML +=
      '<button onclick=zoomTo('+ i + ')>' +
      data[i].properties.position +
      '</button>';
    };

};

//execute
var app = main(
  map_object,
  map_tile_object,
  resumeData,
  resume_control,
  resume_control_title,
  resume_control_description
);

Best Answer

Not a complete solution but setting the map object's closePopupOnClick option to false did the trick. The real issue is that when I click on the button I also click on the map below the button. Good enough of work around for me though.