Reputation: 89
I'm trying to display markers on a map using Leaflet. On clicking each marker, I'm trying to display a variable inside a popup but I am not able to do so. However, if the same thing is done inside the alert
method, the variable gets displayed. What am I doing wrong?
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);
Upvotes: 2
Views: 1761
Reputation: 33364
bindPopup
accepts multiple types for its content
argument :
bindPopup(<String|HTMLElement|Function|Popup>content, <Popup options> options?)
You're passing an integer, not a string and that confuses Leaflet into looking for a DOM node named 1. Cast your value to a string and your problem disappears :
this.bindPopup(this.options.speed+"").openPopup()
And a demo
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/[email protected]/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
<div id='map'></div>
Upvotes: 4