JQuery Googlemap V3 添加标记

发布于 2024-12-23 09:42:41 字数 8998 浏览 1 评论 0原文

我很困惑为什么会发生这种情况。

我正在尝试向地图添加标记,当我在其中一个功能中收到警报时,它工作正常。我对它的工作感到满意,取出警报并再次测试它,但标记无法加载。当我将警报放回到函数中的同一位置时,标记再次正确加载。有谁知道为什么会发生这种情况,我的代码是否存在某种我不明白的计时问题? Firebug 没有报告任何问题,并且 XML 文件正在正确加载。

我发布了我一直在处理的整个代码页,因为我不知道代码的哪一部分包含问题。

然而,我所说的警报位于 get_locations.. 函数内部: alert("THIS HERE");

<style type="text/css" >

  html { height: 100% }

  body { height: 100%; margin: 0; padding: 0 }

</style>



<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>


<script type="text/javascript"> 

$(document).ready(function() 
{
    var alerted = false;

    function MYMAP() 
    {
        //internal
        var map = '';
        var center = '';
        var centerImage = 'http://maps.google.com/mapfiles/arrow.png';
        var infoWindow = '';
        var last_ne_lat; //Check previous map corner
        var locations = [];

        var customIcons = {
              yes: {
                icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
                shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
              },
              no: {
                icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
                shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
              }
        };

        var get_locations = function(neLat, neLng, swLat, swLng, map, infoWindow)
        {
            //testMap.removeAllMarkers();
            var xmlArray = [];
            var tags = '';
            var tagCheck = false;
            /*if($("#tags").val())
            {
                tags = $.trim($("#tags").val());
                tagCheck = true;
                //alert(tags);              
            }
            var coupons= $('#coupons').attr('checked'); 
            //if(coupons == 'checked')
                //alert("Checking for coups");
            //$("div:contains('John')").css("text-decoration", "underline"); //For checking XML
            */
            $.get('Scripts/googlemap_ajax.php', {neLat: neLat, neLng: neLng, swLat: swLat, swLng: swLng}, 
            function(xml)
            {
                $(xml).find("marker").each(function()
                {
                    var id = $(this).attr("locationID");
                    var name = $(this).attr("name");
                    var tags = $(this).attr('tags');
                    var coupon = $(this).attr('coupon');
                    var point = new google.maps.LatLng(
                                $(this).attr('latitude'),
                                $(this).attr('longitude'));
                    xmlArray.push({"id": id, "marker": "empty", "name": name, "point": point, "tags": tags, "coupon": coupon});
                });
            }, "xml");

            var addElements = [];
            var removeElements = [];

            alert("THIS HERE");

            $.each(locations, function(i, v1)
            {
                var inLoop = false;
                loc=this;
                $.each(xmlArray, function(j,v)
                {
                    if(loc.id == this.id)
                    {
                        inLoop = true;
                        return false;
                    }
                }); 
                if(!inLoop)
                {
                    removeElements.push(i);
                } 
            });

            for(var i=removeElements.length-1; i>=0; i = i-1)
            {
                locations[removeElements[i]][marker].setMap(null);
                locations.splice(removeElements[i],1);
            }   

            $.each(xmlArray, function(i, v1)
            {
                var inLoop = false;
                xml=this;
                $.each(locations, function(j,v)
                {
                    if(xml.id == this.id)
                    {
                        inLoop = true;
                        return false;
                    }
                }); 
                if(!inLoop)
                {
                    addElements.push(i);
                } 
            });


            $.each(addElements, function()
            {
                var icon = customIcons[xmlArray[this].coupon] || {};
                var marker = new google.maps.Marker({
                    position: xmlArray[this].point,
                    map: map,
                    icon: icon.icon
                    });
                var html = "<h3>"+xmlArray[this].name+"</h3><p>"+xmlArray[this].tags+"</p>";

                google.maps.event.addListener(marker, 'click', function() {
                    infoWindow.setContent(html);
                    infoWindow.open(map, marker);
                });

                xmlArray[this].marker = marker;
                locations.push(xmlArray[this]);
            });                     

        };


    //external:
    return {
            init: function(selector, latLng, zoom) 
            {
                var myOptions = {
                        zoom:zoom,
                        center: latLng,
                    streetViewControl: false,
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                }
                this.map = new google.maps.Map($(selector)[0], myOptions);
            },

            centerMarker: function(latlng) 
            {
                this.center = new google.maps.Marker({

                position: latlng,

                map: this.map,

                icon: centerImage,

                title: "You are here"

                });
            },

            removeAllMarkers: function() 
            {
                $.each(locations, function() 
                {
                    this.marker.setMap(null);
                });
                locations=[];
            },


            addBoundChange: function() 
            {
                this.infoWindow = new google.maps.InfoWindow;
                test = this.map;
                test2 = this.infoWindow;
                // Add listener to map
                google.maps.event.addListener(this.map, 'bounds_changed', function() {
                    var zoom_level = this.getZoom();
                    if(zoom_level > 12)
                    {
                        var bounds = this.getBounds();
                        var ne = bounds.getNorthEast();
                        var neLat = bounds.getNorthEast().lat();
                        var neLng = bounds.getNorthEast().lng();
                                var sw = bounds.getSouthWest();
                        var swLat = bounds.getSouthWest().lat();
                        var swLng = bounds.getSouthWest().lng();
                        if( neLat != last_ne_lat)
                        {
                            last_ne_lat = neLat;    
                            get_locations(neLat, neLng, swLat, swLng, test, test2);

                        }
                    }
                    else //Alerts the user only once- removes markers everytime
                    {
                        testMap.removeAllMarkers();
                        if(!alerted)    
                        { 
                            alerted=true;
                            alert("Please zoom in to continue displaying the location markers");
                        }
                    }
                });
            }

        };
    }
    var testMap = new MYMAP();
    var latlng = new google.maps.LatLng(<?php echo $lat; ?>,<?php echo $long; ?>);
    testMap.init('#map_canvas', latlng, 16);
    testMap.centerMarker(latlng);
    testMap.addBoundChange();

    $('#tagSearch').submit(function(e)
    {   
        e.preventDefault();
    });



});
</script>


<body>
    <form id="tagSearch">
        <h3>Filter results:</h3>
        Search: <input type="text" id="tags" />&nbsp
        <input type="checkbox" id="coupons" /> deals only<br />
        <input type="submit" value="Submit" />
    </form> 

    <div id="locationSelect" style="width:100%"></div>

    <div id="map_canvas" style="width:70%; height:90%"></div>

</body>

------------ --------------------------------------已解决-------------------- ----------------------

好的,所以问题是 $.get 函数之后的代码块在$.get 请求已完成。

解决方案是将 $.get 之后的所有代码放入 .complete() 链中:

var get_locations = function(neLat, neLng, swLat, swLng, map, infoWindow)
{
    $.get('url', {data: "data"}, 
    function(xml)
    {
        $(xml).find("marker").each(function()
        {
            //Process data
        });
    }, "xml")
    .complete(function()
    {
         //Code that relies on the processed data
    });
};

I am very confused as to why this would happen..

I am trying to add markers to a map, and it was working fine when I had an alert within one of the functions. Satisfied that is was working I took out the alert and tested it again, but the markers would not load. When I put an alert back into the function in the same place that markers are loaded correctly again. Does anybody know why this would happen, is there some sort of timing issue with my code that I don't understand? Firebug reported no issues, and the XML file is being loaded correctly.

I posted my entire page of code that I've been working on because I have no clue which portion of the code contains the problem.

However the alert that I was talking about is inside the get_locations.. function: alert("THIS HERE");

<style type="text/css" >

  html { height: 100% }

  body { height: 100%; margin: 0; padding: 0 }

</style>



<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>


<script type="text/javascript"> 

$(document).ready(function() 
{
    var alerted = false;

    function MYMAP() 
    {
        //internal
        var map = '';
        var center = '';
        var centerImage = 'http://maps.google.com/mapfiles/arrow.png';
        var infoWindow = '';
        var last_ne_lat; //Check previous map corner
        var locations = [];

        var customIcons = {
              yes: {
                icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
                shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
              },
              no: {
                icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
                shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
              }
        };

        var get_locations = function(neLat, neLng, swLat, swLng, map, infoWindow)
        {
            //testMap.removeAllMarkers();
            var xmlArray = [];
            var tags = '';
            var tagCheck = false;
            /*if($("#tags").val())
            {
                tags = $.trim($("#tags").val());
                tagCheck = true;
                //alert(tags);              
            }
            var coupons= $('#coupons').attr('checked'); 
            //if(coupons == 'checked')
                //alert("Checking for coups");
            //$("div:contains('John')").css("text-decoration", "underline"); //For checking XML
            */
            $.get('Scripts/googlemap_ajax.php', {neLat: neLat, neLng: neLng, swLat: swLat, swLng: swLng}, 
            function(xml)
            {
                $(xml).find("marker").each(function()
                {
                    var id = $(this).attr("locationID");
                    var name = $(this).attr("name");
                    var tags = $(this).attr('tags');
                    var coupon = $(this).attr('coupon');
                    var point = new google.maps.LatLng(
                                $(this).attr('latitude'),
                                $(this).attr('longitude'));
                    xmlArray.push({"id": id, "marker": "empty", "name": name, "point": point, "tags": tags, "coupon": coupon});
                });
            }, "xml");

            var addElements = [];
            var removeElements = [];

            alert("THIS HERE");

            $.each(locations, function(i, v1)
            {
                var inLoop = false;
                loc=this;
                $.each(xmlArray, function(j,v)
                {
                    if(loc.id == this.id)
                    {
                        inLoop = true;
                        return false;
                    }
                }); 
                if(!inLoop)
                {
                    removeElements.push(i);
                } 
            });

            for(var i=removeElements.length-1; i>=0; i = i-1)
            {
                locations[removeElements[i]][marker].setMap(null);
                locations.splice(removeElements[i],1);
            }   

            $.each(xmlArray, function(i, v1)
            {
                var inLoop = false;
                xml=this;
                $.each(locations, function(j,v)
                {
                    if(xml.id == this.id)
                    {
                        inLoop = true;
                        return false;
                    }
                }); 
                if(!inLoop)
                {
                    addElements.push(i);
                } 
            });


            $.each(addElements, function()
            {
                var icon = customIcons[xmlArray[this].coupon] || {};
                var marker = new google.maps.Marker({
                    position: xmlArray[this].point,
                    map: map,
                    icon: icon.icon
                    });
                var html = "<h3>"+xmlArray[this].name+"</h3><p>"+xmlArray[this].tags+"</p>";

                google.maps.event.addListener(marker, 'click', function() {
                    infoWindow.setContent(html);
                    infoWindow.open(map, marker);
                });

                xmlArray[this].marker = marker;
                locations.push(xmlArray[this]);
            });                     

        };


    //external:
    return {
            init: function(selector, latLng, zoom) 
            {
                var myOptions = {
                        zoom:zoom,
                        center: latLng,
                    streetViewControl: false,
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                }
                this.map = new google.maps.Map($(selector)[0], myOptions);
            },

            centerMarker: function(latlng) 
            {
                this.center = new google.maps.Marker({

                position: latlng,

                map: this.map,

                icon: centerImage,

                title: "You are here"

                });
            },

            removeAllMarkers: function() 
            {
                $.each(locations, function() 
                {
                    this.marker.setMap(null);
                });
                locations=[];
            },


            addBoundChange: function() 
            {
                this.infoWindow = new google.maps.InfoWindow;
                test = this.map;
                test2 = this.infoWindow;
                // Add listener to map
                google.maps.event.addListener(this.map, 'bounds_changed', function() {
                    var zoom_level = this.getZoom();
                    if(zoom_level > 12)
                    {
                        var bounds = this.getBounds();
                        var ne = bounds.getNorthEast();
                        var neLat = bounds.getNorthEast().lat();
                        var neLng = bounds.getNorthEast().lng();
                                var sw = bounds.getSouthWest();
                        var swLat = bounds.getSouthWest().lat();
                        var swLng = bounds.getSouthWest().lng();
                        if( neLat != last_ne_lat)
                        {
                            last_ne_lat = neLat;    
                            get_locations(neLat, neLng, swLat, swLng, test, test2);

                        }
                    }
                    else //Alerts the user only once- removes markers everytime
                    {
                        testMap.removeAllMarkers();
                        if(!alerted)    
                        { 
                            alerted=true;
                            alert("Please zoom in to continue displaying the location markers");
                        }
                    }
                });
            }

        };
    }
    var testMap = new MYMAP();
    var latlng = new google.maps.LatLng(<?php echo $lat; ?>,<?php echo $long; ?>);
    testMap.init('#map_canvas', latlng, 16);
    testMap.centerMarker(latlng);
    testMap.addBoundChange();

    $('#tagSearch').submit(function(e)
    {   
        e.preventDefault();
    });



});
</script>


<body>
    <form id="tagSearch">
        <h3>Filter results:</h3>
        Search: <input type="text" id="tags" /> 
        <input type="checkbox" id="coupons" /> deals only<br />
        <input type="submit" value="Submit" />
    </form> 

    <div id="locationSelect" style="width:100%"></div>

    <div id="map_canvas" style="width:70%; height:90%"></div>

</body>

-----------------------------------------SOLVED------------------------------------------

Ok, so the problem was that the code chunk after the $.get function was being processed before the $.get request was completed.

The solution was to throw all of the code after the $.get into a .complete() chain:

var get_locations = function(neLat, neLng, swLat, swLng, map, infoWindow)
{
    $.get('url', {data: "data"}, 
    function(xml)
    {
        $(xml).find("marker").each(function()
        {
            //Process data
        });
    }, "xml")
    .complete(function()
    {
         //Code that relies on the processed data
    });
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

作死小能手 2024-12-30 09:42:41

好的,所以问题是在 $.get 请求完成之前就已经处理了 $.get 函数之后的代码块。

解决方案是将 $.get 之后的所有代码放入 .complete() 链中:

var get_locations = function(neLat, neLng, swLat, swLng, map, infoWindow)
{
    $.get('url', {data: "data"}, 
    function(xml)
    {
        $(xml).find("marker").each(function()
        {
            //Process data
        });
    }, "xml")
    .complete(function()
    {
         //Code that relies on the processed data
    });
};

Ok, so the problem was that the code chunk after the $.get function was being processed before the $.get request was completed.

The solution was to throw all of the code after the $.get into a .complete() chain:

var get_locations = function(neLat, neLng, swLat, swLng, map, infoWindow)
{
    $.get('url', {data: "data"}, 
    function(xml)
    {
        $(xml).find("marker").each(function()
        {
            //Process data
        });
    }, "xml")
    .complete(function()
    {
         //Code that relies on the processed data
    });
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文