0

我已经看到了类似查询的答案,但我无法让它工作,所以我希望有人会看到我的代码有问题,或者能够建议我如何解决这个问题

为了简要解释我在做什么 - 用户输入他们的邮政编码并从下拉列表中选择他们希望从他们的邮政编码看到商店的距离(以英里为单位)。在 mvc 中使用 ajax,我将返回带有 Google 地图上标记的商店列表。

当用户做出新的选择时,标记不会被清除。我已经看到我需要将标记放在一个数组中,然后清除它们,但不确定我做错了什么。

以下是我使用的代码片段:

在脚本的顶部:

            var map;
            var markers = [];



            // Deletes all markers in the array by removing references to them.
           function clearMarkers(){
              for(var i=0; i<markers.length; i++){
                markers[i].set_map(null);
              }
              markers.length = 0;
            }; 

单击下拉列表时:

 $("#distanceMiles").change(function () {

                     clearMarkers();

在ajax成功内:

var marker = new google.maps.Marker({
                                            position: new google.maps.LatLng(item.StoreLat, item.StoreLong),
                                            icon: iconurl,
                                            map: map
                                        });
                                        marker.setMap(map);

这是脚本:

<script type="text/javascript">
               //<![CDATA[
               //if the postcode input field is clicked on the dropdown should clear

                            $("#enterPostCode").click(function() {
                                $("#distanceMiles").find('option:first').attr('selected','selected');

                            });

           $("#hiddenPostMsg ").hide();

            $(".divAddress").hide();
            //indicates whether your application is using a sensor, such as a GPS device to determine user's location - we are not
            //  google.load("maps", "2", { "other_params": "sensor=false" });
            //Starts a javascript function named initialize which sets the Google Map display parameters, and is called in the html body upon page load
            var map;
            var markers = [];



            // Deletes all markers in the array by removing references to them.
           function clearMarkers(){
              for(var i=0; i<markers.length; i++){
                markers[i].set_map(null);
              }
              markers.length = 0;
            }; 



            function initialize() {

                var zoomGrade = 10;

                var mapProp = {
                    center: new google.maps.LatLng(51.694031, 0.04505),
                    zoom: zoomGrade,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                map = new google.maps.Map(document.getElementById("gmap_canvas"), mapProp);




                $("#distanceMiles").change(function () {

                     clearMarkers();

                    $(".divAddress").hide();
                    $(".addressscroll ul").html('');
                    //clear the old markers if there are any
                   // gmap.clearOverlays();

                    $("#distanceMiles option:selected").each(function () {

                        var manufacturerId =  <%= Model.Manufacturer.Id%>;

                        var postcodeEntered = $("#enterPostCode").val();

                        var milesEntered = $(this).val();

                        if (postcodeEntered != "" && milesEntered != "") {

                         $("#hiddenPostMsg ").hide();

                            var theUrl = "/Widgets/GetPostcodes/" + manufacturerId + "/" + postcodeEntered + "/" + milesEntered;
                            $.ajax({
                                type: "POST",
                                //contentType: "application/json; charset=utf-8",
                                url: theUrl,
                                data: { 'manufacturerId': manufacturerId, 'postcodeEntered': postcodeEntered, 'milesEntered': milesEntered },
                                dataType: "json",
                                success: function (data) {

                                    for (var i = 0; i < data.length - 1; i++) {



                                        var item = data[i];



                                        //the count goes next to the retailer so we know which marker is for which
                                        var count = i + 1;

                                        //to custom the markers i need to use the number we are on (i)
                                        var iconurl = "https://where-to-buy.co/content/images/marker" + count + ".png";

                                        //Sets the initial map location (latitude, longitude) in decimal degree format, and the zoom level (1 is zoomed out - 21 is farthest zoom in)
                                        map.setZoom(item.ZoomLevel);
                                        map.setCenter(new google.maps.LatLng(item.OriginalLat, item.OriginalLong));


                                        //Close bracket to end the function named initialize !!!very important to not delete this!!!
                                        //javascript that sets up variables that enable the map to draw a custom icon.
                                       var marker = new google.maps.Marker({
                                            position: new google.maps.LatLng(item.StoreLat, item.StoreLong),
                                            icon: iconurl,
                                            map: map
                                        });
                                        marker.setMap(map);

                                        //End of add marker code
                                        var showDistance = item.Distance.toFixed(2);
                                        //now i need to create a list that will display on the right hand side inside .addressscroll
                                        $(".addressscroll ul").append("<li class =\"storeLi\"><div class=singleadddress><p class=\"storeNameP\">" + count + " " + item.StoreName + "</p><p class=\"storeP\">" + item.Address1 + "<br/>" + item.TownCity + " " + item.Postcode + "<br/>" + item.Telephone + "<br/>" + showDistance + " miles</p><p class =\"linksP\" ><a class =\"storeA\" href = \"https://www.google.com/maps?q=" + item.MapsPostcode + "\" target=\"_blank\" >Display Map</a></p><p class =\"linksP\"><a class =\"storeA\" href = \"https://maps.google.co.uk/maps?f=d&hl=en&geocode=&saddr=" + item.OriginalMapsPostcode + "&daddr=" + item.MapsPostcode + "\" target=\"_blank\" >Display Route</a></p></div></li> ");

                                        //Creates a directions object and registers a map and DIV to hold the resulting computed directions
                                        //                                                var directionsPanel;
                                        //                                                var directions;
                                        //                                                directionsPanel = document.getElementById("my_directions_div");
                                        //                                                directions = new GDirections(gmap, directionsPanel);
                                        //                                                //Specify the FROM and TO for your directions: postcode to postcode
                                        //                                                directions.load("from: "+ item.OriginalPostcode +", to: "+ item.Postcode + "");


                                    }

                                    $(".divAddress").show();


                                    $(".upHide").hide();
                                    // get the number of .child elements
                                    var totalitems = $(".addressscroll .storeLi").length;
                                  if(totalitems >= 2) {
                                       $(".downHide").show();
                                  }
                                    // get the height of .w6392597
                                    var scrollval = $('.storeLi').height();
                                    // work out the total height.
                                    var totalheight = (totalitems * scrollval) - ($(".addressscroll").height());
                                    $(document).on("click", ".downHide", function () {
                                        var currentscrollval = $('.addressscroll').scrollTop();

                                        $('.addressscroll').scrollTop(scrollval + currentscrollval);

                                        // hide/show buttons
                                        if (currentscrollval == totalheight) {
                                            $(this).hide();
                                        }
                                        else {
                                            $(".upHide").show();

                                        }
                                    }); $(document).on("click", ".upHide", function () {
                                        var currentscrollval = parseInt($('.addressscroll').scrollTop());

                                        $('.addressscroll').scrollTop(currentscrollval - scrollval);

                                        // hide/show buttons
                                        if ((scrollval + currentscrollval) == scrollval) {
                                            $(this).hide();
                                        }
                                        else {
                                            $(".downHide").show();
                                        }
                                    });


                                    if(totalitems == 0) {
                                        $(".downHide").hide();
                                        $("#hiddenPostMsg ").show();
                                        $("#hiddenPostMsg ").text("Invalid Postcode. Please try again");

                                    }

                                }

                            });

                        }
                        else if (postcodeEntered == "") {

                            //here i want to clear the dropdown aswel
                             $("#hiddenPostMsg ").show();
                            $("#distanceMiles").find('option:first').attr('selected','selected');

                        }


                    });

                });


            }
            google.maps.event.addDomListener(window, 'load', initialize);
               google.maps.event.trigger(map, 'resize');
                        </script>

任何帮助都感激不尽!

4

1 回答 1

1

创建标记时,您没有将标记放入数组中。

 //javascript that sets up variables that enable the map to draw a custom icon.
 var marker = new google.maps.Marker({
   position: new google.maps.LatLng(item.StoreLat, item.StoreLong),
   icon: iconurl,
   map: map
 });
 marker.setMap(map);
 markers.push(marker);

不确定这是否是一个问题,但您对 setMap 的使用不一致:

markers[i].set_map(null);

marker.setMap(map);
于 2013-05-30T13:17:12.137 回答