我使用Leaflet在地图上隐藏/显示一些多边形,但在我找到的所有示例中,包括the official one,叠加标题都是静态设置的:
var overlayMaps = {
"Cities": cities
};
如果不是"城市"我想要一个翻译过的字符串?在我的其余Javascript代码中,我用以下内容调用已翻译的字符串:
$.ajax({
type: "POST",
url: Settings.base_url
...
}
或
$('#location_length').html(length_meters+' '+Settings.meters);
但如果我尝试将以下内容用于叠加层,则会出现语法错误:
var overlayMaps = {
Settings.show_polygone: cities
};
我的页脚中定义了Settings.show_polygone,例如:
show_polygone: "<?php echo $this->lang->line('main')['show_polygone']; ?>"
知道如何实现这个目标吗?
答案 0 :(得分:1)
如果要将变量设置为JS对象上的键,则必须使用square bracket notation。
尝试
var overlays = {};
overlays[Settings.show_polygone] = cities;
和演示
var cities = L.layerGroup();
L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.').addTo(cities),
L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.').addTo(cities),
L.marker([39.73, -104.8]).bindPopup('This is Aurora, CO.').addTo(cities),
L.marker([39.77, -105.23]).bindPopup('This is Golden, CO.').addTo(cities);
var mbAttr = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
mbUrl = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
var grayscale = L.tileLayer(mbUrl, {id: 'mapbox.light', attribution: mbAttr}),
streets = L.tileLayer(mbUrl, {id: 'mapbox.streets', attribution: mbAttr});
var map = L.map('map', {
center: [39.73, -104.99],
zoom: 10,
layers: [grayscale, cities]
});
var baseLayers = {
"Grayscale": grayscale,
"Streets": streets
};
var Settings = {
show_polygone: "Show polygons"
}
var overlays = {};
overlays[Settings.show_polygone] = cities;
L.control.layers(baseLayers, overlays).addTo(map);
html, body {
height: 100%;
margin: 0;
}
#map {
width: 600px;
height: 400px;
}
<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>