Reputation: 3758
I'm using Leaflet to hide/show some polygones on a map but in all examples I've found, including the official one, the overlay title is statically set:
var overlayMaps = {
"Cities": cities
};
What if instead of "Cities" I want to have a translated string? In the rest of my Javascript code, I call the translated strings with:
$.ajax({
type: "POST",
url: Settings.base_url
...
}
or
$('#location_length').html(length_meters+' '+Settings.meters);
But if I try to use the following for the overlay, I get syntax error:
var overlayMaps = {
Settings.show_polygone: cities
};
Settings.show_polygone is defined in my footer, for example:
show_polygone: "<?php echo $this->lang->line('main')['show_polygone']; ?>"
Any idea how to achieve that?
Upvotes: 2
Views: 375
Reputation: 33364
You have to use the square bracket notation if you want to set a variable as a key on a JS object.
Try
var overlays = {};
overlays[Settings.show_polygone] = cities;
And a demo
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/[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: 1