I have a map with 4 layers, each layer having markers for various shops. What I need to do is this.
- User chooses shop from select
- Script grabs shop name and then finds the correct data for that shop from json.
I have a rough idea of how the script should look but don't know how to write it correctly.
$('#shopselect').change(function() {
$.ajax({
type: "GET",
url: "data.txt",
dataType: "json",
success: function(data) {
var selected = $('#shopselect option:selected').text()
if ($(".layer1:visible").length) {
$("#viewport").mapbox("center", {
x: shops." + selected + ".l1x,
y: shops." + selected + ".l1y
});
} else if ($(".layer2:visible").length) {
$("#viewport").mapbox("center", {
x: shops." + selected + ".l2x,
y: shops." + selected + ".l1y
});
} else if ($(".layer3:visible").length) {
$("#viewport").mapbox("center", {
x: shops." + selected + ".l3x,
y: shops." + selected + ".l1y
});
} else if ($(".layer4:visible").length) {
$("#view开发者_如何学Pythonport").mapbox("center", {
x: shops." + selected + ".l4x,
y: shops." + selected + ".l1y
});
}
}
});
The json looks like so.
{
shops:{
primark:{
l1x:310,
l1y:132,
l2x:388,
l2y:264,
l3x:530,
l3y:355,
l4x:670,
l4y:450
},
boots:{
l1x:310,
l1y:132,
l2x:388,
l2y:264,
l3x:530,
l3y:355,
l4x:670,
l4y:450
}
}
}
Is there anyone who could point me in the right direction.
Instead of using this :
x: shops." + selected + ".l1x,
y: shops." + selected + ".l1y
What about something like that :
x: data.shops[selected].l1x,
y: data.shops[selected].l1y
Assuming the value you get in :
var selected = $('#shopselect option:selected').text()
(by the way you forgot a semicolon here) is either "primark" or "boots", you should be able to access the data this way:
var coords = data.shops[selected];
if ($(".layer1:visible").length) {
$("#viewport").mapbox("center", {
x: coords.l1x,
y: coords.l1y
});
etc.
You can do something like this to get the shops:
var shops = data.shops;
The correct way to get the shop properties is:
shops[selected].l4x
In other words treat shops as an associative array.
精彩评论