将点击事件处理程序添加到 Leafletjs 中的标记

Adding Click Event Handler to Marker in Leafletjs

我试图在 LeafletJS 的地图上的标记中添加点击事件,但点击事件似乎没有触发。这是代码:

// jshint esversion: 10

// Keep this out of global scope
jQuery(document).ready(function() {

/**
 * Since singleton classes don't really work in JS, we're just using a variable
 * with properties and functions. This acts like a Singleton.
 *
 * This class's purpose is to handle user interaction with a map
 * of property listings on the page. There should be a div on the page
 * with ID rel-listing-map, which the map will be displayed inside.
 * @author Nate Lanza
 * @type {Object}
 */
var MapManager = {

  /**
   * Stores the Leaflet map object
   * @type {L.Map}
   */
  map: null,

  /**
   * All listings displayed on the map, as Listing objects
   * @type {array}
   */
  listings: null,

  /**
   * Whether this object's init function has been called. If false, no other functions can run
   * @type {Boolean}
   */
  initialized: false,

  /**
   * @throws Error if init has not been called
   * @return {void}
   */
  checkInit: function() {
    if (!this.initialized)
      throw new Error("Must call init first");
  },

  /**
   * Gets listings to be displayed on the map
   * and stores them in the listings field
   * Currently retrieves listings from a custom element with id 'rel-listing-data'
   */
  getListings: function() {
    this.checkInit();
    this.listings = JSON.parse( document.getElementById("rel-listing-data").dataset.listings );
  },

  /**
   * Retrieves a listing by ID
   * @param  {int} ID ID of the listing to retrieve
   * @return {Object || bool}    Listing object, or false if not found
   */
  getListing: function(ID) {
    for (var listing of this.listings)
      if (listing.listingId == ID)
        return listing;

    return false;
  },

  /**
   * Places a marker on the map for each listing to be displayed
   * Fields map and listings should both be initialized
   * @return {void}
   */
  populateMap: function() {
    this.checkInit();
    if (this.listings == null)
      throw new Error("getListings must be called before populateMap");

    // Create onclick function for markers
    function onClick(e) {
      console.log("Clicked");
      // Get listing
      var listing = MapManager.getListing(this.ID);
      if (!listing)
        throw new Error("Listing " + this.ID + " not found");

      // Display info
      jQuery('#rel-listing-map-info').innerHTML = "<p>" + listing.privateRemarks + "</p>";
    }

    // Add each listing to map
    for (var listing of this.listings) {
      // Create marker
      var marker = new L.Marker(
        new L.LatLng(listing.lat, listing.lng)
      );
      marker.ID = listing.listingId;
      // Add to map & add onclick action
      marker.addTo(this.map).on('click', onClick);
      console.log(marker);
    }

  },

  /**
   * Initializes the Map field, retrieves listings from a global variable,
   * fills the listings field, and populates the map with listing markers.
   * Must be executed before any other functions in this 'class',
   * otherwise an error will be thrown
   * @return {void}
   */
  init: function() {
    // Init map
    this.map = L.map('rel-listing-map', {
      center: [43.6177, -116.1997],
      zoom: 8,
      // Canvas doesn't work on IE,
      // but the other option, SVG, doesn't work on Android
      preferCanvas: true,
      attributionControl: true,
    });

    // Create map background
    L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors',
      maxZoom: 18,
    }).addTo(this.map);

    // Center map
    var houston = new L.LatLng(29.97, -95.35);
    this.map.setView(houston, 13);

    //this.map.on('click', function(e) {
    //  console.log(e);
    //});

    this.initialized = true;

    // Init listings
    this.getListings();
    // Populate map
    this.populateMap();
  }
};

// Code to run when page is loaded
MapManager.init();
});

当我尝试单击标记时,onClick 函数从未触发。这发生在多个浏览器中。当我将标记 objects 打印到控制台时,他们似乎在 _leaflet_events 字段中有一个点击事件,但是当我检查 HTML 地图上的标记 objects 时,他们似乎没有将我的 onClick 函数添加为事件。这可以在具有单个 div、ID rel-listing-map、此脚本、jQuery 和 header 中包含的 leaflet.js 的空页面上重现。

对于遇到此问题的其他人,我找到了解决方案:这张地图位于 WordPress 网站上。网站上的其他一些脚本包括一个名为 Bundle.css 的文件,它破坏了地图。我能够使用以下代码从站点中排除此 css 文件(仅适用于 Wordpress):

add_filter( 'style_loader_src', function($href) {
      if ($href == 'http://www.idxhome.com/service/resources/dist/wordpress/bundle.css?1627639643157') {
        return false;
      }

      return $href;
    });

即使这个特定的 css 文件不是您的问题,我还是建议您右键单击标记并使用浏览器的检查元素来验证它们是否位于所有其他元素之上。如果 inspect element 没有提取代表标记的 元素,则您遇到了 CSS 问题。

导致我来到这里的故障排除步骤是尝试在空白 HTML 文件中复制问题 - 我也建议您这样做,即使您没有使用 Wordpress,看看是否还有其他问题scripts/styles 破坏了您的代码。