Search code examples
javascripthtmlmapboxpost-parameter

Link to mapbox marker on an outside website?


I have a page that includes a mapbox map with about 7 markers. Each of those markers includes a thumbnail that is also added to a navigation toolbar, and clicking on that thumbnail takes you to the marker and opens it.

I'd like to include similar links on an external website. Is it possible to have a link on an outside webpage that takes me to my mapbox page and opens a specific marker?

//populate markers
oneArtPlease.on('layeradd', function(e) {
    var marker = e.layer,
    feature = marker.feature;

    // popupz
    var popupContent =  '<div class="thumbnail"><a target="_blank" class="popup" href="' + feature.properties.url + '">' +
        '<img src="' + feature.properties.image + '" width="300" title="Click for the full picture" /><br>' +
        feature.geometry.coordinates+'</br>'+
        feature.properties.picnote +
        '</a></div>';
    marker.bindPopup(popupContent,{
        closeButton: true,
        minWidth: 320
    });

    //change icon
    marker.setIcon(L.icon(feature.properties.icon));
    //populate thumbnail bar
    var link = info.insertBefore(document.createElement('a'),info.firstChild);
    link.className = 'item';
    link.href = '#';
    link.innerHTML ='<img src="' + feature.properties.image + '" class="navthumb"/>';
    link.onclick = function() {
        if (/active/.test(this.className)) {
            this.className = this.className.replace(/active/, '').replace(/\s\s*$/, '');
        } else {
            var siblings = info.getElementsByTagName('a');
            for (var i = 0; i < siblings.length; i++) {
                siblings[i].className = siblings[i].className
                .replace(/active/, '').replace(/\s\s*$/, '');
            };
            this.className += ' active';
            // move to marker and open on thumbnail click
            map.panTo(marker.getLatLng());
            marker.openPopup();
        }
        return false;
    };

});
new L.Control.Zoom({ position: 'topright' }).addTo(map);

Solution

  • I ended up finding some code that parses the URL parameters with js. The url parameter here is passes using index.html?piece=X

    function getURLParameter(name) {
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
    }
    
    pieceID = getURLParameter('piece');
    

    Later, when populating my markers, I run the following code.

    if (marker.feature.properties.pieceID == pieceID) {
        map.panTo(marker.getLatLng());
        marker.openPopup();
    }
    

    I also include a property for each marker in the geojson file that is called pieceID. If the URL is passed with the piece parameter X and a marker has a piece ID equal to X, it will open when the page loads.