边栏标记列表按类别不起作用

时间:2014-06-22 13:40:16

标签: javascript google-maps google-maps-api-3

我使用谷歌地图api v3制作地图。我想制作侧边栏,列出标记除以类别。单击侧栏中的标记列表时,地图上的标记将显示其信息,如此示例http://www.geocodezip.com/v3_MW_example_categories.html。这是map.html

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      #category_panel {
    background-color : white;
    padding : 5px;
    font-size : 13px;
    margin-top : 5px;
    border : 1px solid #aaa;
      }
      #map {
    width: 800px;
    height: 400px;
    padding : 0;
    left : 3%;
    top : 10%;
      }
      #side_bar {
    position: absolute;
    width: 300px;
    height: 400px;
    top: 3%;
    left: 70%;
    border : 1px solid #aaa;
      }
    </style>
    <script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&amp;key=AIzaSyDKXwzDz8D96-bipZjRwkW97gcdHkOHt2M">
    </script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js"></script> 
    <script type="text/javascript">
    var map;

function initialize() {
    var mapOptions = {
      center: new google.maps.LatLng(-6.9667, 110.41677),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
map = new google.maps.Map(document.getElementById("map"),
        mapOptions);

var selectDiv = $("#category_panel")[0];
map.controls[google.maps.ControlPosition.TOP_LEFT].push(selectDiv);
}

$(document).ready(function() {
    $.getJSON("data.txt", function(json) {
        $.each(json, function(key, data) {

        var clusterer;

        var infoWindow = new google.maps.InfoWindow();

        // Marker Clusterer setup
        var mcOptions = {
        gridSize : 1,
        maxZoom : 15
        };
    clusterer = new MarkerClusterer(map, [], mcOptions);

    var markers = {};
    var side_bar_html = "";

    // Looping JSON data
    for (var i = 0, length = json.length; i < length; i++) {
        var data = json[i],
            latLng = new google.maps.LatLng(data.lat, data.lng),
            category = data.category;

        if (category in markers == false) {
            markers[category] = [];
        }

        var marker = new google.maps.Marker({
            position : latLng,
            title : data.title,
        });
        markers[category].push(marker);

//      document.getElementById("side_bar").innerHTML = side_bar_html;
//      side_bar_html += '<a href="javascript:(marker, data)(' + (markers.length-1) + ')">' + data.title + '<\/a><br><br>';

        (function (marker, data) {

            google.maps.event.addListener(marker, "click", function(e) {
            infoWindow.setContent(data.description);
            infoWindow.open(map, marker);
            });

        })(marker, data);

    function makeSidebar() {
    //var html = "";
        for (var i = 0, length = json.length; i < length; i++) {
        var data = json[i],
            latLng = new google.maps.LatLng(data.lat, data.lng),
            category = data.category;

        if (category in markers == false) {
            markers[category] = [];
        }
            {
                side_bar_html += '<a href="javascript:(marker, data)(' + i + ')">' + data.title + '<\/a><br>';
            }
        }
        document.getElementById("side_bar").innerHTML = side_bar_html;
    }


    }// loop ends


    $("#category").change(function()
        {
        var selected = $(this).val();
        clusterer.clearMarkers();
        clusterer.addMarkers(markers[selected]);
        });
    $("#category").change();
    makeSidebar();


        });
    });
});
    </script>   
  </head>
  <body onload="initialize()">

    <div id="map"></div>

    <div id="side_bar"></div> 

      <div lang="en" id="category_panel">
    Category:<select id="category">
      <option value="category1">category 1</option>
      <option value="category2">category 2</option>
    </select>
      </div>

  </body>
</html>

这是data.txt

[
    {
    "title": "1A",
    "lat": -6.984,
    "lng": 110.41,
    "description": "1B",
    "category": "category1"
    },
    {
    "title": "1B",
    "lat": -6.9963,
    "lng": 110.398,
    "description": "1B",
    "category": "category1"
    },
    {
    "title": "2A",
    "lat": -6.9904,
    "lng": 110.42307,
    "description": "2B",
    "category": "category2"
    },
    {
    "title": "2B",
    "lat": -7.003,
    "lng": 110.4247,
    "description": "2B",
    "category": "category2"
    }
]

问题是:首先,侧栏中的标记链接在单击时不起作用。 其次,所有标记数据始终显示,仅在选择类别时才会出现。 有人可以帮帮我吗?在此先感谢您的任何帮助

1 个答案:

答案 0 :(得分:1)

Working example of what I think you want

从引用的示例开始。

  1. 添加了getJSON(带有JSON格式的修改版本)
  2. 添加了mycategoryclick功能
  3. 更改了复选框功能以选择(下拉列表)

    function createMarker(latlng,name,html,category) {
      var contentString = html;
      var marker = new google.maps.Marker({
        position: latlng,
        icon: getMarkerImage(category2color(category)), // 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);
      });
      return marker;
    }
    
      function select(category) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory == category) {
            gmarkers[i].setVisible(true);
          } else {
            gmarkers[i].setVisible(false);
          }
        }
        // == close the info window, in case its open on a marker that we just hid
        infowindow.close();
        // == rebuild the side bar
        makeSidebar();
      }
    
      function createCategoryDropdown(category) {
        var select_holder = document.getElementById('select_holder');
        var option = document.createElement("option");
        option.setAttribute("name",category);
        option.setAttribute("value",category);
        option.innerHTML = category;
        select_holder.appendChild(option);
      }
    
    
      function mycategoryclick(category,i) {
        google.maps.event.trigger(markers[category][i],"click");
      }
    
      // == rebuilds the sidebar to match the markers currently displayed ==
      function makeSidebar() {
        var html = "";
        for (category in markers) {
          // html += "<b>"+category+"</b><br>";
          for (var i=0; i<markers[category].length; i++) {
            if (markers[category][i].getVisible()) {
              html += '<a href="javascript:mycategoryclick(&quot;'+category+'&quot;,' + i + ')">' + markers[category][i].myname + '<\/a><br>';
            }
          }
        }
        document.getElementById("side_bar").innerHTML = html;
      }
    
    function initialize() {
      var myOptions = {
        zoom: 11,
        center: new google.maps.LatLng(53.8363,-3.0377),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      map = new google.maps.Map(document.getElementById("map"), myOptions);
    
    
      google.maps.event.addListener(map, 'click', function() {
        infowindow.close();
      });
    
    // Read the data
    $.getJSON("SO_20140622_data.txt", function(json) {
        var firstcat = null;
    var bounds = new google.maps.LatLngBounds();
        for (var i = 0; i < json.length; i++) {
          // obtain the attribues of each marker
          var lat = parseFloat(json[i].lat);
          var lng = parseFloat(json[i].lng);
          var point = new google.maps.LatLng(lat,lng);
      bounds.extend(point);
          var name = json[i].title;
          var category = json[i].category;
          var html = "<b>"+name+"<\/b><p>"+json[i].description+"</p>category:"+category;
          // create the marker
          var marker = createMarker(point,name,html,category);
          if (category in markers == false) {
        if (firstcat == null) firstcat = category;
            markers[category] = [];
          }
          markers[category].push(marker);
        }
    
        // == create the categories dropdowns ==
        for (category in markers) {
      createCategoryDropdown(category);
        }
        // == show the first category
        select(firstcat);
    
        // == create the initial sidebar ==
        makeSidebar();
    
        // == fit the viewport to _all_ the markers ==
        map.fitBounds(bounds);
      });
    }