Reload Markers on Google's Maps API

后端 未结 3 728
予麋鹿
予麋鹿 2021-02-02 02:09

Here is my code(most code from Google\'s API page).



        
3条回答
  •  一向
    一向 (楼主)
    2021-02-02 02:25

    Few things you should do / things that I have changed from your original code:

    1. Use valid lat/lng coordinates for your markers (1121.28747820854187 for example is not a valid lng)
    2. Create a global variable for your map (easier to reference in your script)
    3. Create an array to hold your markers
    4. I have added a marker animation animation: google.maps.Animation.DROP, to your markers, so that you can see when they are reloaded, and a reload markers button to call the reload function.

    Basically what you want to do is:

    1. Create each marker within the setMarkers function
    2. Push each marker to the markers array
    3. When reloading your markers, loop through your markers array and call setMap(null) on each marker to remove it from the map
    4. Once done, call setMarkers again to re-draw your markers

    Updated code:

    var map;
    var markers = []; // Create a marker array to hold your markers
    var beaches = [
        ['Bondi Beach', 10, 10, 4],
        ['Coogee Beach', 10, 11, 5],
        ['Cronulla Beach', 10, 12, 3],
        ['Manly Beach', 10, 13, 2],
        ['Maroubra Beach', 10, 14, 1]
    ];
    
    function setMarkers(locations) {
    
        for (var i = 0; i < locations.length; i++) {
            var beach = locations[i];
            var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
            var marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                animation: google.maps.Animation.DROP,
                title: beach[0],
                zIndex: beach[3]
            });
    
            // Push marker to markers array
            markers.push(marker);
        }
    }
    
    function reloadMarkers() {
    
        // Loop through markers and set map to null for each
        for (var i=0; i

    Working example:

    JSFiddle demo

提交回复
热议问题