Toggle inside toggle for Google Maps

久未见 提交于 2019-12-12 02:29:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!