使用$ .each迭代,setMap(Null)的Google地图更新标记不起作用

时间:2016-02-23 11:59:42

标签: json google-maps

您好我已经尝试了一段时间来更新我的标记来自JSON外出但没有运气。 我无法用gMarkers.setMap(null)删除我的标记,即使我可以看到数据存储在数组中。我假设我存储数据错误?

我的想法是使用间隔

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Alarms in a Map</title>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
    <script type="text/javascript">
        var gmap;
        var gMarkers = [];

        $(document).on('pageshow', '#map_index', function() {

            var myLatlng = new google.maps.LatLng(58.990738, 16.210006);
            var mapOptions = {
                zoom: 10,
                center: myLatlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var gmap = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

            loadData(); // init with active alarms
        });

        var loadData = function() { <!-- ---------------------------------- getActiveAlarms ------------------------------- -->

                setCenter(); <!-- set map to center -->

                //$('#map_canvas').gmap('clear', 'markers');  //first clear all markers 


                $.getJSON('map/map_json.php', function(data) {
                    $.each(data.markers, function(j, marker) {

                        if (j == data.markers.length - 1) {
                            ANIMATION = google.maps.Animation.BOUNCE;
                        } else {
                            ANIMATION = google.maps.Animation.DROP;
                        }

                        if (marker.Status == '7') {
                            tmpIcon = Larm_active;
                        } else if (marker.Status == '5') {
                            tmpIcon = Larm_returned;
                        } else if (marker.Status == '3') {
                            tmpIcon = Larm_acknow;
                        } else if (marker.Status == '2') {
                            tmpIcon = Larm_blocked;
                        }

                        $('#map_canvas').gmap('addMarker', {
                            'position': new google.maps.LatLng(marker.Latitude, marker.Longitude),
                            'bounds': false,
                            'icon': tmpIcon,
                            'animation': ANIMATION
                        }).click(function() {
                            $('#map_canvas').gmap('openInfoWindow', {
                                'content': '<div id="locTime">' + 'Tid:&nbsp;' + marker.AlarmTime + '</b>' + '</div>' + '<div id="LocArea">Area: ' + marker.Area + '</div>' + '<div id="locText">' + '<p>Larmtext: ' + marker.AlarmText + '</p>' + '</div>' + '<div id="locPos">Position av Objekt' + '<br />Longitude: ' + marker.Longitude + '<br />Latitude: ' + marker.Latitude + '</div>'



                            }, this);

                        });

                        gMarkers.push(data.markers);
                        console.log("load Markers");
                        console.log(gMarkers);
                    });
                });

            } <!-- getActiveAlarms -->

        var eraseMarkers = function() {
            console.log("enter removeMarkers");
            while (gMarkers[0]) {
                gMarkers.setMap(null);
            }

            gMarkers.length = 0;

        }


        var setCenter = function() {

            $('#map_canvas').gmap('option', 'center', new google.maps.LatLng(58.990738, 16.210006));
            $('#map_canvas').gmap('option', 'zoom', 12);



        }
    </script>
    <link href="_css/customStyles.css" rel="stylesheet" type="text/css">

    <!-- Javascript outside jquery Mobile -->
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
    <!-- Map Javascript -->
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false"></script>
    <script type="text/javascript" src="jquery_map/jquery.ui.map.js"></script>
    <script type="text/javascript">
        var tmpIcon;
        var Larm_unreachable = new google.maps.MarkerImage('map/icons/Larm_unreachable.png');
        var Larm_active = new google.maps.MarkerImage('map/icons/Larm_active.png');
        var Larm_blocked = new google.maps.MarkerImage('map/icons/Larm_blocked.png');
        var Larm_acknow = new google.maps.MarkerImage('map/icons/Larm_acknow.png');
        var Larm_returned = new google.maps.MarkerImage('icons/Larm_returned.png');
        var User = new google.maps.MarkerImage('map/icons/User.png');
    </script>
</head>

<body>
    <div data-role="page" id="map_index">
        <div data-role="header"> <a href="menu.php" class="ui-btn ui-shadow ui-corner-all ui-icon-home ui-btn-icon-notext ui-btn-inline" rel="external">Home</a>
            <div class="ui-btn-right">
                <!-- <a href="#" id="user" class="ui-btn ui-shadow ui-corner-all ui-icon-user ui-btn-icon-notext ui-btn-inline">Where am I?</a>-->
                <a href="#" id="unreachable" class="ui-btn ui-shadow ui-corner-all ui-icon-alert ui-btn-icon-notext ui-btn-inline">Unreachable</a> <a href="#" id="locations" class="ui-btn ui-shadow ui-corner-all ui-icon-location ui-btn-icon-notext ui-btn-inline">Locations</a><a href="#" id="editLocations" class="ui-btn ui-shadow ui-corner-all ui-icon-edit ui-btn-icon-notext ui-btn-inline">editLocations</a> </div>
            <h1>Karta</h1>
        </div>
        <div data-role="content" id="content">
            <div id="map_canvas" style="height:100%"></div>
        </div>
        <script type="text/javascript">
            <!-- Functions for buttons in navbar -->
            $("#unreachable").click(function() {
                getUnreachableAlarms();
            });
            $("#locations").click(function() {
                getActiveAlarms();
            });
            $("#editLocations").click(function() {
                eraseMarkers();
            })
        </script>
    </body>
</html>

好的,我已经更新了我的脚本现在我至少可以看到我的标记数组正在使用正确数量的标记对象进行更新。但是,没有可见的标记。

map_Markers[i].setMap(null); //remove if not exist

如果我删除这一行它们是可见的,但是如果JSON输出在下一次迭代中给我少一点,我该如何更新地图? 对小提琴中的一个例子的进一步帮助很有帮助。

    <!DOCTYPE html>
<html>
<head>
<style>
      #map_canvas {
        width: 500px;
        height: 400px;
      }
    </style>


<meta charset="utf-8">
<!-- key=AIzaSyAlC-GSJ207WiUBtAG6zsNLNR5iChJtiSI -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Alarms in a Map</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp" async defer></script>

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script type="text/javascript">

var map;
var map_Markers = [];

function initMap()  {
    console.log("initMap");

    loadMarkers();
};

function CreateMarker(map, lat, lng, markerid) {
    console.log("CreateMarker"); 
        var objLatLng = new google.maps.LatLng(lat, lng);
        var marker = new google.maps.Marker({
            position: objLatLng,
            map: map,
            title: 'my title',
            id: markerid
        });
        map_Markers.push(marker); // add in array
      return marker; 
}


function MarkerLocationUpdate(map, lat, lng, markerid ) {
    console.log("MarkerLocationUpdate");  
    var result = false;  
    for( i=0;i< map_Markers.length ; i++ ) {  
            if ( map_Markers[i].id == markerid ){  
                //update location on existing marker
                map_Markers[i].setPosition( new google.maps.LatLng( lat, lng ) );
            result = true;
            }else{
                map_Markers[i].setMap(null); //remove if not exist

                }
        }
    return result;
}


var loadMarkers = function(){ <!-- ---------------------------------- loadMarkers ------------------------------- -->

    $.getJSON( 'map/map_json.php', function(data) { 
       $.each(data.markers, function(j, marker) {

               if (MarkerLocationUpdate(map,  marker.Latitude, marker.Longitude, marker.ID) == false ){
                 CreateMarker(map, marker.Latitude, marker.Longitude, marker.ID);
              }
     });//each loop
     console.log("Array is holding: "+map_Markers.length+" Object/s");
  }); //getJSON
}   



</script>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>
  <div id="map_canvas"></div>
<script type='text/javascript'>
var mapDiv = document.getElementById('map_canvas');
        var map = new google.maps.Map(mapDiv, {
          center: {lat: 58.990738, lng: 16.210006},
          zoom: 11
        });

 initMap();

 var t=setInterval(loadMarkers, 2000);


</script>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

gMarkers是一个数组,而不是标记。

可能的解决方法:

var eraseMarkers = function(){
  console.log("enter removeMarkers");

  while(gMarkers.length){ 
   gMarkers.shift()//removes the first item from array
                   //and returns the item
     .setMap(null);
  }

}

答案 1 :(得分:0)

通常我会使用对象文字来存储标记,您可以使用for var in ob样式进行进一步的操作,但我认为您应该能够使用forEach方法访问阵列。在删除结束时,确保将数组重置为空。

var eraseMarkers = function(){
    gMarkers.forEach=function( e, i, a ){
        e.setMap( null );
    });
    gMarkers=[];
};