我正在尝试使用Leaflet在地图上显示标记。点击每个标记时,我试图在弹出窗口中显示变量,但我无法这样做。但是,如果在alert
方法内完成相同的操作,则会显示变量。我做错了什么?
var map = L.map('map').setView([51.505, -0.09], 12);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
var latlngs = [[51.49,-0.11],[51.51,-0.13],[51.505,-0.09],[51.507,-0.08], [51.509,-0.07]];
var speed = [1,2,3,4,5]
var time = [12,14,15,16]
var test = 1
customMarker = L.CircleMarker.extend({
options: {
}
});
for (var i = 0, len = latlngs.length; i < len; i++) {
var m = new customMarker(latlngs[i], {
speed: speed[i],
time: time[i]
});
m.on('mouseover', function() {
//alert('Speed at this point' + this.options.speed)
this.bindPopup(this.options.speed).openPopup()
})
m.addTo(map);
}
var polyline = L.polyline(latlngs,{});
polyline.addTo(map);
答案 0 :(得分:2)
bindPopup
为其content
参数接受多种类型:
bindPopup(<String|HTMLElement|Function|Popup>content, <Popup options> options?)
您传递的是一个整数,而不是字符串,这会使Leaflet混淆为寻找名为1的DOM节点。将您的值转换为字符串,您的问题就会消失:
this.bindPopup(this.options.speed+"").openPopup()
和演示
var map = L.map('map').setView([51.505, -0.09], 12);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
var latlngs = [[51.49,-0.11],[51.51,-0.13],[51.505,-0.09],[51.507,-0.08], [51.509,-0.07]];
var speed = [1,2,3,4,5]
var time = [12,14,15,16]
var test = 1
customMarker = L.CircleMarker.extend({
options: {
}
});
for (var i = 0, len = latlngs.length; i < len; i++) {
var m = new customMarker(latlngs[i], {
speed: speed[i],
time: time[i]
});
m.on('mouseover', function() {
this.bindPopup(this.options.speed+"").openPopup()
})
m.addTo(map);
}
var polyline = L.polyline(latlngs,{});
polyline.addTo(map);
html, body {
height: 100%;
margin: 0;
}
#map {
width: 100%;
height: 100%;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
<div id='map'></div>