Assign ID to marker in leaflet

后端 未结 7 1090
忘了有多久
忘了有多久 2020-12-23 11:47

So i try to achieve a result as on foursquare: https://foursquare.com/explore?cat=drinks&mode=url&near=Paris which is when you clik on a marker on the map, it scrol

7条回答
  •  遥遥无期
    2020-12-23 12:23

    A fairly straight forward and easy way to accomplish creating an array of clickable markers within a leaflet map object is to manipulate the class list of the created marker by adding a custom incremented class name to each marker. Then it is easy to create a listener and know which marker was clicked. By skipping the active one or not, each has a retrievable click event with a reliable ID.

      // creates markers, each with a leaflet supplied class
      if (length === 1) {
        for (i = 0; i < parks.length; ++i) {
          if (parks[i].parksNumber !== parks.parksNumber)
            L.marker([parks[i].latitude, parks[i].longitude], {
              icon: parks[i].iconMarker
            }).addTo(mymap);
        }
      }
    
      // select all of the leaflet supplied class
      let markers = document.querySelectorAll(".leaflet-marker-icon");
    
      // loop through those elements and first assign the indexed custom class
      for (i = 0; i < markers.length; ++i) {
        markers[i].classList.add("marker_" + parks[i].parksNumber);
    
        // then add a click listener to each one
        markers[i].addEventListener("click", e => {
    
          // pull the class list
          let id = String(e.target.classList);
    
          // pull your unique ID from the list, be careful cause this list could 
          // change orientation,  if so loop through and find it
          let parksNumber = id.split(" ");
          parksNumber = parksNumber[parksNumber.length - 1].replace("marker_", "");
    
          // you have your unique identifier to then do what you want with
          search_Number_input.value = parksNumber;
          HandleSearch();
        });
      }
    

提交回复
热议问题