问题
I'm using jVectorMap Plugin to add a map to website. Here is a map where I added markers on page load. Is there a way to do it dynamically? I need to add them on mouse click. I use jVectorMap Plugin
var plants = [
{name: 'VAK', coords: [-25.274398, 133.775136], status: 'mrk'},
{name: 'MZFR', coords: [37.090240, -95.712891], status: 'mrk'},
{name: 'AVR', coords: [50.9030599, 6.4213693], status: 'mrk'}
];
$('#world-map-markers').vectorMap({
map: 'world_mill_en',
normalizeFunction: 'polynomial',
markerStyle: {
initial: {
fill: '#F8E23B',
stroke: '#383f47'
}
},
backgroundColor: '#383f47',
markers: plants.map(function(h) {
return {
name: h.name,
latLng: h.coords
}
}),
series: {
markers: [{
attribute: 'image',
scale: {
'mrk': 'marker.png'
},
values: plants.reduce(function(p, c, i) {
p[i] = c.status;
return p
}, {}),
}]
}
});
});
回答1:
Initialize the map with empty markers and values:
mapObj = new jvm.Map({
container: $('#world-map-markers'),
map: 'world_mill_en',
normalizeFunction: 'polynomial',
markerStyle: {
initial: {
fill: '#F8E23B',
stroke: '#383f47'
}
},
backgroundColor: '#383f47',
markers: [],
series: {
markers: [{
attribute: 'image',
scale: {
'mrk': 'marker.png'
},
values: [],
}]
}
});
Just only to point out that you can also set markers and values separately, declare two arrays:
var mapMarkers = [];
var mapMarkersValues = [];
then, wherever you need the click handler, call a function like this:
function addPlantsMarkers() {
var plants = [
{name: 'VAK', coords: [-25.274398, 133.775136], status: 'mrk'},
{name: 'MZFR', coords: [37.090240, -95.712891], status: 'mrk'},
{name: 'AVR', coords: [50.9030599, 6.4213693], status: 'mrk'}
];
mapMarkers.length = 0;
mapMarkersValues.length = 0;
for (var i = 0, l= plants.length; i < l; i++) {
mapMarkers.push({name: plants[i].name, latLng: plants[i].coords});
mapMarkersValues.push(plants[i].status);
}
mapObj.addMarkers(mapMarkers, []);
mapObj.series.markers[0].setValues(mapMarkersValues);
}
Final result:
来源:https://stackoverflow.com/questions/32788509/jvectormap-how-to-add-marker-dynamically