Google地图按标记类别加载侧边栏

时间:2014-05-30 15:20:44

标签: javascript google-maps

这是对我之前提出的问题的更新,但从未在此处得到答案previous question。我有一个谷歌地图,当点击相应的复选框时,会从xml文件中创建并加载不同类别的标记,然后更新侧栏上的列表。我想将每个类别加载到它自己单独的侧边栏中,以便我可以将它们拆分或并排堆叠等等。当我单击复选框时,第一个列表(小屋列表)将被加载到两个侧边栏但第二个列表(蒙古包列表)正确加载到相应的侧边栏中。我不明白为什么一个列表被加载到两个侧边栏中,但另一个列表被正确加载到一个列表中。在此先感谢您的帮助。代码全部如下:

的Javascript

      var side_bar_html = ""; 

      //var for kml route layers
      var routes = {
     y: {
        name: "Winter Routes",
        url: "http://www.huts.org/Tests/Maps/GPSTracks/Margys_MacV2.kml"

    },
    z: {
        name: "Summer Routes",
        url: "http://www.huts.org/Tests/Maps/GPSTracks/Telluride_to_Last_Dollar.kml"

    },

};

      var gmarkers = [];
      var gicons = [];
      var map = null;


var infowindow = new google.maps.InfoWindow(
  { 
    size: new google.maps.Size(100,150)
  });


gicons["ltblue"] = new google.maps.MarkerImage("images/marker2_ltblue.png");

  var iconImage = new google.maps.MarkerImage('images/marker2_ltblue.png');



function getMarkerImage(iconColor) {
   if ((typeof(iconColor)=="undefined") || (iconColor==null)) { 
      iconColor = "ltblue"; 
   }
   if (!gicons[iconColor]) {
      gicons[iconColor] = new google.maps.MarkerImage("images/marker2_"+ iconColor +".png");
   } 
   return gicons[iconColor];

}

function category2color(category) {
   var color = "ltblue";
   switch(category) {
     case "huts": color = "ltblue";
                break;
     case "yurts":    color = "orange";
                break;
    case "demohuts":    color = "red";
                break;
     default:   color = "ltblue";
                break;
   }
   return color;
}

      gicons["huts"] = getMarkerImage(category2color("huts"));
      gicons["yurts"] = getMarkerImage(category2color("yurts"));
      gicons["demohuts"] = getMarkerImage(category2color("demohuts"));


      // A function to create the marker and set up the event window
function createMarker(latlng,name,html,category) {
    var contentString = html;
    var marker = new google.maps.Marker({
        position: latlng,
        icon: gicons[category],

        map: map,
        title: name,
        zIndex: Math.round(latlng.lat()*-100000)<<5
        });
        // === Store the category and name info as a marker properties ===
        marker.mycategory = category;                                 
        marker.myname = name;
        gmarkers.push(marker);

  //google.maps.event.addListener(marker, 'click', function() {
      // infowindow.setContent(contentString); 
      // infowindow.open(map,marker);
      // });

    google.maps.event.addListener(marker, 'click', function() {
     var testimonial = document.getElementById('hutMapinfo');
        testimonial.innerHTML = contentString;
       });

}


      // == shows all markers of a particular category, and ensures the checkbox is checked ==
      function show(category) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory == category) {
            gmarkers[i].setVisible(true);
          }
        }
        // == check the checkbox ==
        document.getElementById(category+"box").checked = true;
      }

      // == hides all markers of a particular category, and ensures the checkbox is cleared ==
      function hide(category) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory == category) {
            gmarkers[i].setVisible(false);
          }
        }
        // == clear the checkbox ==
        document.getElementById(category+"box").checked = false;
        // == close the info window, in case its open on a marker that we just hid
        infowindow.close();
      }

      // == a checkbox has been clicked ==
      function boxclick(box,category) {
        if (box.checked) {
          show(category);
        } else {
          hide(category);
        }
        // == rebuild the side bar
        makeSidebar();
      }

      function myclick(i) {
        google.maps.event.trigger(gmarkers[i],"click");
      } 

      // == rebuilds the sidebar to match the markers currently displayed ==
      function makeSidebar() {
        var html = "";
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].getVisible()) {
            html += '<a href="javascript:myclick(' + i + ')" onmouseover="gmarkers['+ i +'].setAnimation(google.maps.Animation.BOUNCE)" onmouseout="gmarkers['+ i +'].setAnimation(null)">' + gmarkers[i].myname + '<\/a><br>';
          }
          document.getElementById(gmarkers[i].mycategory+"side_bar").innerHTML = html;
        }

      }

  function initialize() {
    var myOptions = {
      zoom: 7,
      center: new google.maps.LatLng(39.192948, -105.089823),
      mapTypeId: google.maps.MapTypeId.TERRAIN
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);



    //google.maps.event.addListener(map, 'click', function() {
       // infowindow.close();
       // });



      // Read the data
      downloadUrl("coloradoYurtsToggleTest.xml", function(doc) {
  var xml = xmlParse(doc);
  var markers = xml.documentElement.getElementsByTagName("marker");

        for (var i = 0; i < markers.length; i++) {
          // obtain the attribues of each marker
          var lat = parseFloat(markers[i].getAttribute("lat"));
          var lng = parseFloat(markers[i].getAttribute("lng"));
          var point = new google.maps.LatLng(lat,lng);
          var name = markers[i].getAttribute("label");
          var html = GXml.value(markers[i].getElementsByTagName("infowindow")[0]);
          var category = markers[i].getAttribute("category");
          var season = markers[i].getAttribute("season");
          // create the marker
          var marker = createMarker(point,name,html,category);
        }

        // == show or hide the categories initially ==
        show("huts");

        hide("yurts");

        // == create the initial sidebar ==
        makeSidebar();
      });
      createRouteTogglers();
    }


// the important function... routes[id].xxxxx refers back to the top 
function toggleRoute(checked, id) {

    if (checked) {

        var layer = new google.maps.KmlLayer(routes[id].url, {
            preserveViewport: true,
            suppressInfoWindows: false 
        });
        // store kml as obj
        routes[id].obj = layer;
        routes[id].obj.setMap(map);
    }
    else {
        routes[id].obj.setMap(null);
        delete routes[id].obj;
    }

};

// create the Routes controls
function createRouteTogglers() {

    var html = "<form><ul>";
    for (var prop in routes) {
        html += "<li id=\"selector-" + prop + "\"><input type='checkbox' id='" + prop + "'" +
        " onclick='highlight(this,\"selector-" + prop + "\"); toggleRoute(this.checked, this.id)' \/>" +
        routes[prop].name + "<\/li>";
    }
    html += "<\/ul><\/form>";

    document.getElementById("routeLayers").innerHTML = html;
};

// Append Class on Select
function highlight(box, listitem) {
    var selected = 'selected';
    var normal = 'normal';
    document.getElementById(listitem).className = (box.checked ? selected: normal);
};

HTML

<!DOCTYPE html>
<html>
<head>
    <title>10th Mountain Division Hut Association</title>
    <meta charset="UTF-8"> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> 

    <title>Google Maps Javascript API v3 Example: Marker Categories</title> 
    <link rel="stylesheet" href="css/foundation.css" />
  <link rel="stylesheet" href="css/10thMtn2.css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript" src="GXml.js"></script>
<script type="text/javascript" src="downloadxml.js"></script>
<script type="text/javascript" src="xmlToggle2.js"></script>
    <title>Google Maps</title>


  </head>
<body onload="initialize()"> 

<?php include('includes/header3.php'); ?>


<div id="map_canvas" style="width:65%; height:625px;"></div>
<div id="toggle_box">


    <div id="routeLayers"></div>
    <form action="#">
      <img src="images/marker2_ltblue.png"> Huts: <input type="checkbox" id="hutsbox" onclick="boxclick(this,'huts')" />
      <img src="images/marker2_orange.png"> Yurts: <input type="checkbox" id="yurtsbox" onclick="boxclick(this,'yurts')" />
      </form>
    <div id="hutsside_bar">
    </div>
    <div id="yurtsside_bar">
    </div>



</div>

<div id="hutMapinfo"></div>


<?php include('includes/footer.php'); ?>

    <noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> 
      However, it seems JavaScript is either disabled or not supported by your browser. 
      To view Google Maps, enable JavaScript by changing your browser options, and then 
      try again.
    </noscript>

  </body>

</html>

xml代码段

<?xml version="1.0" encoding="UTF-8"?>
<markers>
<marker lat="39.369804" lng="-106.388725" label="10th Mountain Division Hut" category="huts" season="winter">
 <infowindow>
<![CDATA[
    <div class="info">
    <button class="tiny radius" id="closer">X</button>
    <h5>10th Mountain Division Hut</h5>
    <div class="hutMapTitle">
    <img src="http://www.huts.org/images/10thMtn/10thMountainsmall.jpg"/>
    <h6>10th Mountain Hut System</h6>
    <h6>(970)925-5775</h6>
    </div>
    <div class="hutMapList">
    <ul>
        <li><a href="http://www.huts.org/The_Huts/10th_mountain.html" target="_blank">10th Mtn Division Huts Website</a></li>
        <li><a href="http://www.huts.org" target="_blank">Book This Hut</a></li>
        <li><span class="subheading">Seasons:</span> Winter &amp Summer</li>
        <li><span class="subheading">Price:</span> $33 per person</li>
        <li><span class="subheading">Capacity:</span> 16 people</li>
        <li><span class="subheading">Distance:</span> 4.4 miles</li>
        <li><span class="subheading">Elevation Gain:</span> 1200ft
    </ul>   
    </div>
    <p>Nestled at timberline below the majestic peaks of the Colorado Continental Divide, 10th Mountain Division Hut forms a perfect destination for a single hut trip or ski-through using other nearby huts. In summer, dozens of hiking and cycling routes start or end just outside the door.</p></div>]]></infowindow>
    </marker>
<marker lat="37.059971" lng="-106.480865" label="Trujillo Meadows Yurt" category="yurts">
 <infowindow>
  <![CDATA[
    <div class="info">
    <button class="tiny radius" id="closer">X</button>
    <h5>Trujillo Meadows Yurt</h5>
    <div class="hutMapTitle">
    <img src="http://www.huts.org/images/GMaps/trujilloMeadowsYurt.jpg"/>
    <h6>Southwest Nordic Center</h6>
    <h6>(575)758-4761</h6>
    </div>
    <div class="hutMapList">
    <ul>
        <li><a href="http://www.southwestnordiccenter.com/yurtdescriptions.htm#TMyurt" target="_blank">Southwest Nordic Website</a></li>
        <li><a href="http://www.southwestnordiccenter.com/reservationsandratesIII.htm" target="_blank">Book This Hut</a></li>
        <li><span class="subheading">Seasons:</span> Winter &amp Summer</li>
        <li><span class="subheading">Price:</span> $125 per night</li>
        <li><span class="subheading">Capacity:</span> 10 people</li>
        <li><span class="subheading">Distance:</span> 4.1 miles</li>
        <li><span class="subheading">Elevation Gain:</span> 380ft</li>
    </ul>   
    </div>
    <p>Located north Cumbres Pass in south central Colorado, the Trujillo Meadows Yurt is gentle open slopes out the front door of the yurt perfect for beginning and intermediate telemarkers. Advanced skiers will have fun looking for shots on the extensive north facing tree slopes. A full day loop is possible up to the Flat Mtn. ridge and back via the Los Pinos Creek.</p></div>]]></infowindow>
    </marker>
</markers>

1 个答案:

答案 0 :(得分:0)

你的makeSidebar函数有一个问题(它正在做你编码的事情,这是你看到的行为):

function makeSidebar() {
  var html = "";
  for (var i=0; i<gmarkers.length; i++) {
    if (gmarkers[i].getVisible()) {
      html += '<a href="javascript:myclick(' + i + ')" onmouseover="gmarkers['+ i +'].setAnimation(google.maps.Animation.BOUNCE)" onmouseout="gmarkers['+ i +'].setAnimation(null)">' + gmarkers[i].myname + '<\/a><br>';
    }
    document.getElementById(gmarkers[i].mycategory+"side_bar").innerHTML = html;
  }
}

如果你想要每个&#34;侧边栏&#34;的唯一文字,你应该制作一个独特的版本&#34; html&#34;对于每个侧边栏。像这样:

var html = null;
function makeSidebar() {
  // empty any pre-existing sidebar entries
  for (i in html) {
    document.getElementById(i+"side_bar").innerHTML = "";
  }
  html = []; // make html an array
  for (var i=0; i<gmarkers.length; i++) {
    if (gmarkers[i].getVisible()) {
      // make entry for category if it doesn't already exist
      if (!html[gmarkers[i].mycategory])
         html[gmarkers[i].mycategory] = "";
      // add the entry to the sidebar specific to the category
      html[gmarkers[i].mycategory] += '<a href="javascript:myclick(' + i + ')" onmouseover="gmarkers['+ i +'].setAnimation(google.maps.Animation.BOUNCE)" onmouseout="gmarkers['+ i +'].setAnimation(null)">' + gmarkers[i].myname + '<\/a><br>';
     }
   }
   for (i in html) {
      document.getElementById(i+"side_bar").innerHTML = html[i];
   }
}

working fiddle