javascript - Google Maps JS api v3 延迟地一一删除标记

标签 javascript google-maps-api-3 google-maps-markers google-places-api

我知道已经有几个关于此主题的问题,例如 Google maps api v3 drop markers animation with delay ,但经过无数个小时的尝试,我自己却走进了死胡同。

我正在对用户位置附近的公园进行附近搜索,并希望一次放入 20 个结果。如果我对数组中每个结果的位置进行硬编码,我就可以使用它,但是在调用返回附近搜索的函数时,我的 setTimeout 似乎不起作用。

这是我当前的代码:

var map;
var infowindow;
var service;

function initialize() {

    // Create an array of styles.
    var styles = [{
        stylers: [{
            hue: '#0091ff'
        }, {
            saturation: 5
        }, {
            "gamma": 0.5
        }, {
            "lightness": 30
        }]
    }];

    // Create a new StyledMapType object, passing it the array of styles,
    // as well as the name to be displayed on the map type control.
    var styledMap = new google.maps.StyledMapType(styles, {
        name: 'Styled Map'
    });

    // Try HTML5 geolocation
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var pos = new google.maps.LatLng(position.coords.latitude,
            position.coords.longitude);

            var infowindow = new google.maps.InfoWindow({
                map: map,
                position: pos,
                content: 'Found you :)'
            });

            map = new google.maps.Map(document.getElementById('map-canvas'), {
                center: pos,
                zoom: 12,
                mapTypeControl: false,
                zoomControl: false,
                streetViewControl: false
            });

            var request = {
                location: pos,
                radius: 20000,
                keyword: ['Dog parks']
            };
            infowindow = new google.maps.InfoWindow();
            service = new google.maps.places.PlacesService(map);
            service.nearbySearch(request, callback);
            service.getDetails(request, callback);

            function callback(results, status) {
                if (status == google.maps.places.PlacesServiceStatus.OK) {
                    for (var i = 0; i < results.length; i++) {
                        //setTimeout(function() {
                        createMarker(results[i]);
                        //}, i * 200);
                    }
                }
            }

            function createMarker(place) {
                var image = 'img/marker.png';
                var marker = new google.maps.Marker({
                    map: map,
                    animation: google.maps.Animation.DROP,
                    icon: image,
                    position: place.geometry.location
                });
                var request = {
                    reference: place.reference
                };

                service.getDetails(request, function (details, status) {
                    google.maps.event.addListener(marker, 'click', function () {

                        if (status == google.maps.places.PlacesServiceStatus.OK) {

                            // Replace empty spaces in navigation link with + symbols
                            var navLink = details.formatted_address;
                            navLink = navLink.replace(/\s/g, "+");
                            $('.navLink').html(navLink);

                            // Match Rating bar width to rating number
                            var ratingWidth = (details.rating * 20) + "px";
                            $('.rating-bar > span').css('width', "'" + ratingWidth + "'");

                            var contentStr = '<h5 class="info-window-title">' + details.name + '</h5><ul class="info-window">';
                            if ( !! details.rating) contentStr += '<li>Rating:&nbsp;<div class="rating-bar"><span style=width:' + ratingWidth + '></span></div><strong>' + details.rating + '</strong></li>';
                            if ( !! details.open_now) contentStr += '<li class="open-now">' + details.open_now + '</li>';
                            contentStr += '<li>' + details.formatted_address + '</li>';
                            contentStr += '<li class=gray>' + details.types + '</li>';
                            // Check for platform to send appropriate app link
                            if ((navigator.platform.indexOf("iPhone") != -1)) {
                                contentStr += '<li class="link"><a class=navLink href=http://maps.apple.com/?daddr=Current+Location&saddr=' + navLink + '><i class="fa fa-automobile"></i> Get Directions</a></li>';
                            } else {
                                contentStr += '<li class="link"><a class=navLink href=https://www.google.com/maps/dir/Current+Location/' + navLink + '><i class="fa fa-automobile"></i> Get Directions</a></li>';
                            }

                            if ( !! details.formatted_phone_number) contentStr += '<li class="link"><a href="tel:' + details.formatted_phone_number + '"><i class="fa fa-phone"></i> ' + details.formatted_phone_number + '</a></li>';
                            contentStr += '</ul>';
                            infowindow.setContent(contentStr);
                            infowindow.open(map, marker);
                        } else {
                            var contentStr = "<h5>No Result, status=" + status + "</h5>";
                            infowindow.setContent(contentStr);
                            infowindow.open(map, marker);
                        }
                    });
                });
            }

            //Associate the styled map with the MapTypeId and set it to display.
            map.mapTypes.set('map_style', styledMap);
            map.setMapTypeId('map_style');

            map.setCenter(pos);
        }, function () {
            handleNoGeolocation(true);
        });
    } else {
        // Browser doesn't support Geolocation
        handleNoGeolocation(false);
    }

}
google.maps.event.addDomListener(window, 'load', initialize);

错误:“地点”未定义。引用:位置:place.geometry.location

最佳答案

您可以使用setInterval来做到这一点 - 请参阅WindowTimers.setInterval()

var map;
var infowindow = new google.maps.InfoWindow();

function initialize() {

    var center = new google.maps.LatLng(59.32522, 18.07002);

    var mapOptions = {
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: center
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var request = {
        location: center,
        radius: '5000',
        types: ["store", "bank"]
    };

    service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, callback);
}

function callback(results, status) {

    if (status == google.maps.places.PlacesServiceStatus.OK) {

        var i = 0;
        var interval = setInterval(function () {

            setMarker(results[i]);
            i++;

            if (i === results.length) clearInterval(interval);

        }, 1000);
    }
}

function setMarker(place) {

    var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
    });

    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent(place.name);
        infowindow.open(map, this);
    });
}

initialize();

JSFiddle demo

关于javascript - Google Maps JS api v3 延迟地一一删除标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29739752/

相关文章:

javascript - ionic 2 : Set interval

javascript - 使用 Snap.js 进行内容填充

javascript - 如何将 json 编码的变量从 .php 传递到外部 .js?

javascript - Chrome 29 窗口。触摸

javascript - 一行 XHTML Javascript 代码

javascript - Google map 可在本地使用,但无法实时使用

javascript - 刷新 AngularJS 中的 map

javascript - 鼠标悬停在标记簇对象上

android - 谷歌地图自定义标记内存不足错误(API V2)

javascript - Google Maps API v3 - 带有可拖动备用路线的路线