我正在使用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']; ?>"


知道如何实现吗?

最佳答案

如果要将变量设置为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 &copy; <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/[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>

关于javascript - 更改已翻译字符串的传单叠加标题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46769645/

10-12 17:22