Skip to content

Instantly share code, notes, and snippets.

@bozdoz
Created April 19, 2019 01:39
Show Gist options
  • Save bozdoz/e61cfa440cfb84dd1cefc5b57e6eb234 to your computer and use it in GitHub Desktop.
Save bozdoz/e61cfa440cfb84dd1cefc5b57e6eb234 to your computer and use it in GitHub Desktop.
Add Sidebar to WordPress Leaflet Map
/* close button is conflicting with my theme */
.leaflet-sidebar .close {
z-index: 1000;
}
function main() {
if (!window.WPLeafletMapPlugin) {
console.log('no plugin found!')
return
}
var markers = window.WPLeafletMapPlugin.markers
var maps = window.WPLeafletMapPlugin.maps
for (var i = 0, len = maps.length; i < len; i++) {
createSidebar(maps[i], i)
}
for (var i = 0, len = markers.length; i < len; i++) {
addMarkerEvent(markers[i])
}
/** create one sidebar for each map */
function createSidebar(map, i) {
var sidebar_elem = document.createElement('div')
var id = 'custom-sidebar-' + i
sidebar_elem.id = id
// needs to be added to body somewhere
document.body.appendChild(sidebar_elem)
var sidebar = L.control.sidebar(id, {
closeButton: true,
position: 'left'
})
map.sidebar = sidebar
map.addControl(sidebar)
}
/** Add click event to markers */
function addMarkerEvent(marker) {
marker._map.whenReady(function() {
var map = this
marker.on('click', function() {
var content = this._custompopup
if (!content) {
var popupContainer = this._popup._container
// popup is about to be visible
content = popupContainer.getElementsByClassName(
'leaflet-popup-content'
)[0].innerHTML
this._custompopup = content
delete this._popup
}
// show or hide the sidebar
map.closePopup()
var identical = map.sidebar.getContainer().innerHTML === content
if (identical && map.sidebar.isVisible()) {
map.sidebar.hide()
} else {
map.sidebar.setContent(content)
map.sidebar.show()
}
})
})
}
}
window.addEventListener('load', main)
<?php
add_action('leaflet_map_loaded', 'custom_leaflet_loaded');
function custom_leaflet_loaded() {
wp_enqueue_script('js_dependency', 'http://turbo87.github.io/leaflet-sidebar/src/L.Control.Sidebar.js', Array('wp_leaflet_map'), '1.0', true);
wp_enqueue_style('css_dependency', 'http://turbo87.github.io/leaflet-sidebar/src/L.Control.Sidebar.css');
// custom js
wp_enqueue_script('custom_js', get_theme_file_uri( 'custom-js.js' ), Array('js_dependency'), '1.0', true);
wp_enqueue_style('custom_css', get_theme_file_uri( 'custom-css.css' ));
}
[leaflet-map]
[leaflet-marker address="bar kismet, halifax"]
<p>Bar Kismet is Top 15 Bar in Canada:</p>
<p><a href="https://canadas100best.com/">100 Best</a></p>
[/leaflet-marker]
[leaflet-marker address="barrington st, halifax"]
<p>Noble is a Top Secret bar in Halifax.</p>
<p>You have to give a password to enter; how ridiculous is that?</p>
<p><img src="https://www.themiddlespoon.com/wp-content/uploads/2015/07/Noble.png" /></p>
[/leaflet-marker]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment