Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Leafletでpolygonを表示するためのWordpressのショートコードの実装例。
<?php
function enable_bamboo() {
return "<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;
}
}
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.href = 'https://unpkg.com/leaflet@1.3.4/dist/leaflet.css';
link.rel = 'stylesheet';
head.appendChild(link);
var script = document.createElement('script');
script.src = 'https://unpkg.com/leaflet@1.3.4/dist/leaflet.js';
script.async = false;
head.appendChild(script);
</script>
<script type=\"text/javascript\">
function bamboo_polygon(L,id,js,popup,zoom) {
var map = L.map(id);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href=\"http://osm.org/copyright\">OpenStreetMap</a> contributors'
}).addTo(map);
jQuery.getJSON(js,function(json){
var gl = L.geoJSON().addTo(map);
gl.addData(json);
// Get geometric center!!
var i = 0;
var lon = 0.0;
var lat = 0.0;
for (let polygon of json[\"geometries\"][0][\"coordinates\"]) {
for (let pointlist of polygon) {
for (let point of pointlist) {
lon += point[0];
lat += point[1];
i++;
// console.log(point.length+\",\"+point[0]+\",\"+point[1]+\",\"+(lon/i)+\",\"+(lat)/i);
}
}
}
map.setView([lat/i, lon/i], zoom);
if (popup !== \"\") {
L.marker([lat/i, lon/i]).addTo(map)
.bindPopup(popup)
.openPopup();
}
});
}
</script>";
}
add_shortcode('enable-bamboo','enable_bamboo');
function bamboo_polygon($atts) {
$atts = shortcode_atts(array(
"id" => "",
"js" => "",
"popup" => "",
"zoom" => 8
),$atts);
return '<div id="'.$atts["id"].'" style="height:250px"></div>
<script type="text/javascript">
bamboo_'.$atts["id"].'=function(){bamboo_polygon(L,\''.$atts["id"].'\',\''.$atts["js"].'\',\''.$atts["popup"].'\','.$atts["zoom"].')};
addOnloadEvent(bamboo_'.$atts["id"].');
</script>';
}
add_shortcode('bamboo-polygon','bamboo_polygon');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.