简体   繁体   中英

HTML Link to a Leaflet / Mapbox marker

I use Mapbox for a dynamic map on a website. It works really well except, I have a sidebar which list the pins with a little more description and an image. I want to make it so when I click on that sidebar, it would fire the click event of that marker on the map.

I used to do this all the time with Google Maps but now I'm stuck because even in the case that I can keep the instance of the marker, I cannot fire the click on it for some reason. It simply does nothing (maybe I need to re-bind the click event on it but I don't know how with mapbox)

I've encountered a few questions about this on Google and SO but none bring a real answer to that question except "keep the instance" which isn't always possible in some cases.

So basically I have a jQuery click event like this:

var marker = {
    type: 'Feature',
    geometry: {
        type: 'Point',
        coordinates: [lng, lat]
    },
    properties: {}
};

if (isPin) {
    marker.properties = pinStyles.pin;
} else if (isWinery) {
    marker.properties = pinStyles.winery;
} else {
    marker.properties = pinStyles.user;
}

marker.properties.title = locationName;
marker.properties.description = pin.description;

var markerObject = L.mapbox.markerLayer(marker);

// Add to cluster
markers.addLayer(markerObject);
$('#marker_list a.marker_item:last').click(function() {
    var geoJson = markerObject.getGeoJSON();
    markerObject.fire('click'); // does nothing (openPopup makes "Uncaught TypeError: Object [object Object] has no method 'openPopup' " so I guess I'm not doing it right)
});

And I have this (click event for mapbox marker):

map.markerLayer.on('click', function(e) {
    map.setView(e.layer.getLatLng(), map.getZoom());
});

Anyone has an idea about wether 1) fix the non-firing event OR 2) make an HTML link fire a mapbox marker click event OR .openPopup?

Thanks and have a nice day!

MapBox's marker layer is a collection of Leaflet markers. You can create an href to a function that look for a particular marker based on it's layer id.

map.markerLayer.getLayers() returns an array of layer objects that contain both a _leaflet_id and the method togglePopup .

Try matching your href call to the leaflet id and then fire map.markerLayer.getLayers()[i].togglePopup()

Let me know if this helps.

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