问题
I've made a Google Map that show a location at the beginning with 1 marker. From there you have the possibility to switch location. It will then show the new location with 1 marker.
Aside from the location switching it's possible to select sub locations for each of the 2 main locations.
I thought that making 2 vars ( for each location 1) would be the best thing [example]:
var locationsBerlin = [
['Berlin 1', 52.519433,13.406746, 1],
['Berlin 2', 52.522606,13.40366, 2],
['Berlin 3', 52.52113,13.409411, 3],
['Berlin 4', 52.517043,13.402394, 4],
['Berlin 5', 52.51703,13.412801, 5],
['Berlin 6', 52.525086,13.399798, 6],
['Berlin 7', 52.525151,13.410741, 7]
];
This is how I select the "main" location.
markerMain = new google.maps.Marker({
position: new google.maps.LatLng(locationsBerlin[0][1], locationsBerlin[0][2]),
map: map,
icon: customPin
});
The rest of the array are sublocations. Now I want the user to be able to press a link and show the rest of the locations in the var (the amount of locations will be dynamic).
So I tried to make a function that will be called after clicking the toggle link.
function subLocationBerlin(){
alert("berlin sub");
for (i = 1; i < locationsBerlin.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locationsBerlin[i][1], locationsBerlin[i][2]),
map: map
});
markers.push(marker);
}
}
But now I'm stuck. For some reason it's not adding the extra markers to the map and I don't know what's wrong.
Over here you can find the fiddle: http://jsfiddle.net/gvMSX/3/
回答1:
Your map variable (the one that is initialized and is displaying the map) is local to the initialize function:
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
Remove the "var" from in front of it to initialize the global version.
Note also that javascript arrays are 0 based, you will be missing the first marker when you initialize i to 1 in your for loops
function subLocationBerlin(){
console.log('Berlin Sub Called');
for (i = 1; i < locationsBerlin.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locationsBerlin[i][1], locationsBerlin[i][2]),
map: map
});
markers.push(marker);
console.log(marker);
}
}
来源:https://stackoverflow.com/questions/17581802/toggle-inside-toggle-for-google-maps