[英]How to use jquery to show pie charts on leaflet when checkbox is checked?
我試圖弄清楚如何使餅圖(我使用傳單創建的)在選中某個復選框時出現和消失。 示例:當第一個帶有 id="data" 的復選框被選中時,餅圖會出現,而當復選框被取消選中時,餅圖將消失。 我在 html 代碼的 head 部分編寫了一個 javascript 代碼,該代碼的功能是在選中/取消選中框時執行某些操作,只是當前其中有警報代碼。 我創建了餅圖,它位於底部的餅圖代碼中。 當 id="data" 被選中時,我無法弄清楚如何激活餅圖。 我嘗試將餅圖代碼放在 if else 語句中,但它不起作用。 如果您碰巧知道解決方案,請告訴我。
// HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Map Testing</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin=""/>
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"
integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
crossorigin=""></script>
<!-- Cdn for jquery -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<!-- Event handling of checking of checkboxes -->
<script>
$(document).ready(function(){
$('input[id="data"]').click(function(){
if($(this).prop("checked") == true){
alert("data checked");
}
else if($(this).prop("checked") == false){
alert("data unchecked");
}
});
$('input[id="imports"]').click(function(){
if($(this).prop("checked") == true){
alert("imports checked");
}
else if($(this).prop("checked") == false){
alert("imports unchecked");
}
});
$('input[id="exports"]').click(function(){
if($(this).prop("checked") == true){
alert("exports checked");
}
else if($(this).prop("checked") == false){
alert("exports unchecked");
}
});
$('input[id="markers"]').click(function(){
if($(this).prop("checked") == true){
alert("markers checked");
}
else if($(this).prop("checked") == false){
alert("markers unchecked");
}
});
});
</script>
<!-- Access style.css file in the same folder -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<nav class="navbar">
<div class="hamburger-menu">
<div class="line line-1"></div>
<div class="line line-2"></div>
<div class="line line-3"></div>
</div>
<ul class="nav-list">
<li class="nav-item">
<a href="#" class="navlink">
<label>
<input type="checkbox" id="data"> Data
</label>
</a>
</li>
<li class="nav-item">
<a href="#" class="navlink">
<label>
<input type="checkbox" id="imports"> Imports
</label>
</a>
</li>
<li class="nav-item">
<a href="#" class="navlink">
<label>
<input type="checkbox" id="exports"> Exports
</label>
</a>
</li>
<li class="nav-item">
<a href="#" class="navlink">
<label>
<input type="checkbox" id="markers"> Markers
</label>
</a>
</li>
</ul>
</nav>
</div>
<div id="map">
<script src="myscripts.js"></script>
</div>
<script src="http://sashakavun.github.io/leaflet-canvasicon/leaflet-canvasicon.js"></script>
<script type="text/javascript" src="leaflet-piechart.js"></script>
<script type="text/javascript">
L.piechartMarker(
L.latLng([20.594, 78.962]), // lat lng for India
{
radius: 40,
data: [
{ name: 'Tobacco', value: 25, style: { fillStyle: 'rgba(0,0,255,1)', strokeStyle: 'rgba(0,0,0,.95)'} },
{ name: 'Whiskey', value: 35, style: { fillStyle: 'rgba(255,0,0,1)', strokeStyle: 'rgba(0,0,0,.95)'} },
{ name: 'Beer', value: 20, style: { fillStyle: 'rgba(0,255,0,1)', strokeStyle: 'rgba(0,0,0,.95)'} },
{ name: 'Cigar', value: 30, style: { fillStyle: 'rgba(255,255,0,1)', strokeStyle: 'rgba(0,0,0,.95)'} },
{ name: 'Others', value: 5, style: { fillStyle: 'rgba(255,228,181,1)', strokeStyle: 'rgba(0,0,0,.95)'} },
]
}
).addTo(mymap);
</script>
</body>
</html>
// leaflet-piechart.js
/*global L */
(function () {
'use strict';
/**
* Piechart Icon
* @type {L.PiechartIcon}
* @extends {L.CanvasIcon}
*/
L.PiechartIcon = L.CanvasIcon.extend({
options: {
iconSize: [48, 48],
iconAnchor: [24, 24],
popupAnchor: [24, 24],
className: 'leaflet-piechart-icon',
valueField: 'value',
nameField: 'name'
/*
data: [
{
name: 'Value',
value: 20, // Percentage or raw value
style: {
fillStyle: 'rgba(255,0,0,.5)',
strokeStyle: 'rgba(255,0,0,.5)',
lineWidth: 1
}
},
...
]
*/
},
/**
* @param {HTMLCanvasElement} icon
* @param {string} type
*/
_setIconStyles: function (icon, type) {
var data = this.options.data;
if ((type == 'icon') && data && L.Util.isArray(data) && icon.getContext) {
var ctx = icon.getContext('2d');
var size = L.point(this.options.iconSize);
var center = size.divideBy(2);
ctx.clearRect(0, 0, size.x, size.y);
var valueField = this.options.valueField;
var total = this._getTotal(data, valueField);
var x = center.x;
var y = center.y;
if (total) {
var radius = Math.min(x, y);
var fraction = Math.PI / total * 2;
var startAngle = -Math.PI / 2;
var stopAngle;
var style;
for (var i = 0, l = data.length; i < l; i++) {
ctx.beginPath();
style = data[i].style || this._getStyle(i, l);
this._applyStyle(ctx, style);
stopAngle = fraction * data[i][valueField] + startAngle;
ctx.arc(x, y, radius - Math.ceil((style.lineWidth || 0) / 2), startAngle, stopAngle);
ctx.stroke();
ctx.lineTo(x, y);
startAngle = stopAngle;
ctx.fill();
ctx.closePath();
}
}
}
L.CanvasIcon.prototype._setIconStyles.apply(this, arguments);
},
/**
* @param {Object[]} data Array of objects
* @param {string} field Field to summarize
* @returns {number}
* @private
*/
_getTotal: function (data, field) {
var total = 0;
for (var i = 0, l = data.length; i < l; i++) {
total += (+data[i][field]);
}
return total;
},
/**
* Applies context style
* @param {CanvasRenderingContext2D} ctx
* @param {Object} props
* @private
*/
_applyStyle: function (ctx, props) {
for (var i in props) {
ctx[i] = props[i];
}
},
/**
* Generates style for chart segment
* @param {number} segment Segment number
* @param {number} total Total segments
* @returns {{fillStyle: string, strokeStyle: string, lineWidth: number}}
* @private
*/
_getStyle: function (segment, total) {
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h, s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
* @url http://axonflux.com/handy-rgb-to-hsl-and-rgb-to-hsv-color-model-c
*
* @param {number} h The hue
* @param {number} s The saturation
* @param {number} l The lightness
* @return {string} The RGB representation
*/
var hslToRgb = function (h, s, l) {
var r, g, b;
if (s == 0) {
r = g = b = l; // achromatic
} else {
var hue2rgb = function (p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
};
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
return Math.round(r * 255) + ',' + Math.round(g * 255) + ',' + Math.round(b * 255);
};
var angle = 360 / (total * 2.5);
var offset = (segment % 2) * total;
var hue = (angle * (offset + (segment - (segment % 2)))) / 360;
var rgb = hslToRgb(hue, 0.7, 0.5);
return {
fillStyle: 'rgba(' + rgb + ',.5)',
strokeStyle: 'rgba(' + rgb + ',.7)',
lineWidth: 1
};
}
});
/**
* Pie char Icon factory
* @param {Object} options
* @returns {L.PiechartIcon}
*/
L.piechartIcon = function (options) {
return new L.PiechartIcon(options);
};
/**
* Pie chart Marker
* @type {L.Marker}
*/
L.PiechartMarker = L.Marker.extend({
options: {
icon: null,
radius: 20,
riseOnHover: true
},
initialize: function (latlng, options) {
var opts = {};
L.Util.extend(opts, options);
if (opts.radius) {
var diameter = opts.radius * 2;
opts.iconSize = [diameter, diameter];
opts.iconAnchor = [opts.radius, opts.radius];
}
opts.icon = L.piechartIcon(opts);
L.Marker.prototype.initialize.apply(this, [latlng, opts]);
}
});
/**
* Pie chart Marker factory
* @param {L.LatLng} latlng
* @param {Object} options
* @returns {L.PiechartMarker}
*/
L.piechartMarker = function (latlng, options) {
return new L.PiechartMarker(latlng, options);
}
}());
試試這個代碼
<!DOCTYPE html>
<html lang="en">
<head>
<title>Map Testing</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
crossorigin=""/>
<!-- Make sure you put this AFTER Leaflet's CSS -->
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"
integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
crossorigin=""></script>
<!-- Cdn for jquery -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<!-- Event handling of checking of checkboxes -->
<script>
$(document).ready(function(){
$('input[id="data"]').click(function(){
if($(this).prop("checked") == true){
$(".leaflet-marker-icon").show();
alert("data checked");
}
else if($(this).prop("checked") == false){
$(".leaflet-marker-icon").hide();
alert("data unchecked");
}
});
$('input[id="imports"]').click(function(){
if($(this).prop("checked") == true){
$(".leaflet-marker-icon").show();
alert("imports checked");
}
else if($(this).prop("checked") == false){
$(".leaflet-marker-icon").hide();
alert("imports unchecked");
}
});
$('input[id="exports"]').click(function(){
if($(this).prop("checked") == true){
$(".leaflet-marker-icon").show();
alert("exports checked");
}
else if($(this).prop("checked") == false){
$(".leaflet-marker-icon").hide();
alert("exports unchecked");
}
});
$('input[id="markers"]').click(function(){
if($(this).prop("checked") == true){
$(".leaflet-marker-icon").show();
alert("markers checked");
}
else if($(this).prop("checked") == false){
$(".leaflet-marker-icon").hide();
alert("markers unchecked");
}
});
});
</script>
<style type="text/css">
#header {
padding:0 1em;
}
body {
padding:0;
margin:0;
}
#description {
line-height:0px;
font-style:italic;
}
#map {
top:120px;
bottom:0;
left:0;
right:0;
position:absolute;
background:#fff;
}
</style>
<!-- Access style.css file in the same folder -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<nav class="navbar">
<div class="hamburger-menu">
<div class="line line-1"></div>
<div class="line line-2"></div>
<div class="line line-3"></div>
</div>
<ul class="nav-list">
<li class="nav-item">
<a href="#" class="navlink">
<label>
<input type="checkbox" id="data"> Data
</label>
</a>
</li>
<li class="nav-item">
<a href="#" class="navlink">
<label>
<input type="checkbox" id="imports"> Imports
</label>
</a>
</li>
<li class="nav-item">
<a href="#" class="navlink">
<label>
<input type="checkbox" id="exports"> Exports
</label>
</a>
</li>
<li class="nav-item">
<a href="#" class="navlink">
<label>
<input type="checkbox" id="markers"> Markers
</label>
</a>
</li>
</ul>
</nav>
</div>
<div id="map">
</div>
<script src="http://sashakavun.github.io/leaflet-canvasicon/leaflet-canvasicon.js"></script>
<script type="text/javascript" src="leaflet-piechart.js"></script>
<script type="text/javascript">
(function () {
var map = L.map('map', {
zoom: 12,
center: [20.594, 78.962]
});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© <a href="http://osm.org/copyright\">OpenStreetMap</a> contributors' }).addTo(map);
L.piechartMarker(
L.latLng([20.594, 78.962]),
{
radius: 40,
data: [
{ name: 'Tobacco', value: 25, style: { fillStyle: 'rgba(0,0,255,1)', strokeStyle: 'rgba(0,0,0,.95)'} },
{ name: 'Whiskey', value: 35, style: { fillStyle: 'rgba(255,0,0,1)', strokeStyle: 'rgba(0,0,0,.95)'} },
{ name: 'Beer', value: 20, style: { fillStyle: 'rgba(0,255,0,1)', strokeStyle: 'rgba(0,0,0,.95)'} },
{ name: 'Cigar', value: 30, style: { fillStyle: 'rgba(255,255,0,1)', strokeStyle: 'rgba(0,0,0,.95)'} },
{ name: 'Others', value: 5, style: { fillStyle: 'rgba(255,228,181,1)', strokeStyle: 'rgba(0,0,0,.95)'} },
]
}
).addTo(map);
}());
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.