Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Leafletの地図上にデータベースから読み出した緯度・経度及びポップアップの文字列を使って、ポップアップを複数表示させるためのWordpress用のショートコード。
<?php
/*
See https://pandanote.info/?p=6619 for details.
*/
function pineleaf($atts) {
global $wpdb;
$atts = shortcode_atts(array(
"lat" => 35.45585,
"lon" => 139.64204,
"zoom" => 16,
"markeridlist" => "",
"popup" => "横浜ハンマーヘッド<br><img src=\"https://pandanote.info/wordpress/wp-content/uploads/2019/11/P_20191117_105315_vHDR_On_HP_a.jpg\"/>"
),$atts);
$str = "";
$_pineleaf_map_number = hash("sha512",json_encode($atts).strval(mt_rand()));
$str .= "<div id=\"mapid".$_pineleaf_map_number."\" style=\"height:250px\"></div>
<script type=\"text/javascript\">
onload_event_".$_pineleaf_map_number." = function(){
var map = L.map('mapid".$_pineleaf_map_number."').setView([".$atts["lat"].", ".$atts["lon"]."], ".$atts["zoom"].");
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href=\"https://osm.org/copyright\">OpenStreetMap</a> contributors'
}).addTo(map);";
$markerlist = array_filter(explode(",",$atts["markeridlist"]),function($v) {
return preg_match("/\d+/",$v) && $v > 0;
});
if (count($markerlist) == 0) {
$str .= "L.marker([".$atts["lat"].", ".$atts["lon"]."]).addTo(map).bindPopup('".$atts["popup"]."').openPopup();";
} else {
$query = "select lat,lon,popup from leaflet_markers where id in (".implode(",",$markerlist).")";
$rows = $wpdb->get_results($query,ARRAY_A);
foreach($rows as $row) {
$str .= "L.marker([".$row["lat"].", ".$row["lon"]."]).addTo(map).bindPopup(L.popup({autoClose:false}).setContent('".$row["popup"]."')).openPopup();";
}
}
$str .= "};
addOnloadEvent(onload_event_".$_pineleaf_map_number.");
</script>";
return $str;
}
function enable_pineleaf() {
?>
<script type="text/javascript">
function addOnloadEvent(f) {
if ( typeof window.addEventListener != "undefined" )
window.addEventListener( "load", f, false );
else if ( typeof window.attachEvent != "undefined" ) {
window.attachEvent( "onload", f );
} else {
window.onload = f;
}
}
</script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""></script>
<?php
}
add_action('wp_head','enable_pineleaf');
add_shortcode('pineleaf','pineleaf');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment