0

我正在创建一个商店定位器(使用 Google Maps API v3),其中有 3 个复选框将标记过滤到类别中。我让它们与 if 语句分开工作,但无法弄清楚如何让它们一起工作。例如:如果我取消选中 Bar 但它也是一个 BottleShop(Bottleshop 已选中),则标记仍应显示在地图上。标记数据是从 XML 文件中提取的。三个过滤器类别是酒吧、瓶装商店和在线零售商。每个标记可以属于多个过滤器。例如:它可以是一家酒吧和酒瓶店。

我的 XML 示例

<marker name="John's Pizzeria" bar="TRUE" bottleshop="TRUE" onlineretailer="FALSE" address="260 W 44th St, New York, NY" lat="40.758072" lng="-73.987740" type=""/>   

我的 HTML

<div id="location"></div>
<div id="map" class="map" style="height:400px; width:600px;"></div>
<input id="addressInput" value="Enter location" />
<input id="radiusSelect" value="25" />
<input type="button" id="search" value="Search"/>
<form action="#">
    Bar: <input type="checkbox" id="bar" onclick="boxclick(this,'bar')" checked/>
    Bottle Shop: <input type="checkbox" id="bottleshop" onclick="boxclick(this,'bottleshop')" checked/>
    Online Stockist: <input type="checkbox" id="onlineretailer" onclick="boxclick(this,'onlineretailer')" checked/>
</form>  
<select id="locationSelect" class="span12"></select>

我的 JavaScript

var map  = null;
var markers = []; 
var infoWindow;
var True = "TRUE";
var catBar = [];

jQuery(document).ready(function($){
    //Load Google Maps
    load();
    //When user clicks search, fire the search locations function
    $('#search').click(function() {
      searchLocations();
    });
});  

//On page load Create a google map in #map
//Set default cordinates & Map style to roadmap
function load() {

  var location = "Showing default location for map.";
  var locationSelect;
  //Set default Lat Long for when map loads
  var latlng = new google.maps.LatLng(43.907787,-79.359741);
  // If users location is found then overwrite latlng variable and use this location
  if (google.loader.ClientLocation) {
    zoom = 13;
    latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
    location = "Showing IP-based location: <b>" + getFormattedLocation() + "</b>";
    address = getFormattedLocation();
    // Add users location to search input and load local stores
    document.getElementById('addressInput').value=address;
  }
  var myOptions = {
    zoom: 13,
    center: latlng,
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map"), myOptions); 
      document.getElementById("location").innerHTML = location;
  infoWindow = new google.maps.InfoWindow({ 
    size: new google.maps.Size(150,50)
  });
  locationSelect = document.getElementById("locationSelect");
  locationSelect.onchange = function() {
    var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
    if (markerNum != "none") {
      google.maps.event.trigger(markers[markerNum], 'click');
    }
  };
  searchLocations();
}
//Format the location
function getFormattedLocation() {
  if (google.loader.ClientLocation.address.country_code == "US" &&
    google.loader.ClientLocation.address.region) {
    return google.loader.ClientLocation.address.city + ", " 
      + google.loader.ClientLocation.address.region.toUpperCase();
    } else {
      return  google.loader.ClientLocation.address.city + ", "
      + google.loader.ClientLocation.address.country_code;
  }
}
//Search for LAT/LNG of a place using its address using Google Maps Geocoder
function searchLocations() {
  var address = document.getElementById("addressInput").value;

  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({address: address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    //console.log('search worked');
    //console.log(results);
    searchLocationsNear(results[0].geometry.location);
    } else {
      alert(address + ' not found');
    }
  });
}

//Clears Previous location, in info box
function clearLocations() {
 infoWindow.close();
 for (var i = 0; i < markers.length; i++) {
   markers[i].setMap(null);
 }
 markers.length = 0;
 locationSelect.innerHTML = "";
 var option = document.createElement("option");
 option.value = "none";
 option.innerHTML = "See all results:";
 locationSelect.appendChild(option);
}

//Look for locations near by and loop through all data getting lat & lng of each marker
function searchLocationsNear(center) {
  clearLocations();
  searchLoc = center;
  var radius = document.getElementById('radiusSelect').value;
  //console.log(radius);
  var searchUrl = 'http://localhost:8888/starward/wp-content/themes/starward/map_request.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
  downloadUrl(searchUrl, function(data) {
  var xml = parseXml(data);
  var markerNodes = xml.documentElement.getElementsByTagName("marker");
  var bounds = new google.maps.LatLngBounds();
  // alert(markerNodes.length);
  for (var i = 0; i < markerNodes.length; i++) {
    var name = markerNodes[i].getAttribute("name");
    var barValue = markerNodes[i].getAttribute("bar");
    var bottleshopValue = markerNodes[i].getAttribute("bottleshop");
    var onlineRetailerValue = markerNodes[i].getAttribute("onlineretailer");
    var address = markerNodes[i].getAttribute("address");
    var distance = parseFloat(markerNodes[i].getAttribute("distance"));
    var zoom = 13; //Infowindow Zoom level
    var latlng = new google.maps.LatLng(
    parseFloat(markerNodes[i].getAttribute("lat")),
    parseFloat(markerNodes[i].getAttribute("lng")));
    if (!distance) distance = google.maps.geometry.spherical.computeDistanceBetween(latlng, searchLoc);
    if (!address) address = latlng.toUrlValue(6);
    if (!name) name = "marker "+i;
    createOption(name, distance, i);
    bounds.extend(latlng);
    //Make sure paremeters are in correct order or values will be mixed up
    createMarker(latlng, name, address ,zoom, barValue, bottleshopValue, onlineRetailerValue);
  }
  //map.fitBounds(bounds);
  map.setZoom(13);
  map.setCenter(center);
  locationSelect.style.visibility = "visible";
  locationSelect.onchange = function() {
    var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
    google.maps.event.trigger(markers[markerNum], 'click');
   };
 });
}

//Creates marker on the map
//Adds event for user when they click address info pops up
function createMarker(latlng, name, address, zoom, barValue, bottleshopValue, onlineRetailerValue) {
  // add the zoom links
  var html =  "<b>" + name + "</b> <br/>" + address 
  html += '<br><a  href="javascript: map.setCenter(new google.maps.LatLng('+latlng.toUrlValue(6)+'));map.setZoom('+zoom+');">Zoom To</a>';
  html += ' <a  href="javascript:map.setCenter(new google.maps.LatLng('+latlng.toUrlValue(6)+')); map.setZoom(parseInt(map.getZoom())+1);">[+]</a>';
  html += ' <a  href="javascript:map.setCenter(new google.maps.LatLng('+latlng.toUrlValue(6)+')); map.setZoom(parseInt(map.getZoom())-1);">[-]</a>';
  var marker = new google.maps.Marker({
    position: latlng,
    map: map,
  });
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);
  });
  marker.barValue = barValue;
  marker.bottleshopValue = bottleshopValue;
  marker.onlineRetailerValue = onlineRetailerValue;
  marker.MyZoom = zoom;
  markers.push(marker);
}

function show(category) {
  //console.log(category);
  for (var i=0; i<markers.length; i++) {
    if (markers[i].barValue === 'TRUE' && "bar" === category) {
      markers[i].setVisible(true);
    } else if (markers[i].bottleshopValue === 'TRUE' && "bottleshop" === category) {
      markers[i].setVisible(true);
    } else if (markers[i].onlineRetailerValue === 'TRUE' && "onlineretailer" === category) {
      markers[i].setVisible(true);
    } else {

    }
  }
}

 //Hides markers not in current ticked category 
function hide(category) {
  //console.log('hide function');
  for (var i=0; i<markers.length; i++) {
    //console.log(markers[i].barValue);
    if (markers[i].barValue === "TRUE" && "bar" === category  ) {
      //console.log('hiding markers');
      markers[i].setVisible(false); 
    } else if (markers[i].bottleshopValue === "TRUE" && "bottleshop" === category ) {
       markers[i].setVisible(false); 
    } else if (markers[i].onlineRetailerValue === 'TRUE' && "onlineretailer" === category) {
      markers[i].setVisible(false);
    } else {

    }
  }
}

// == a checkbox has been clicked ==
function boxclick(box,category) {
  if (box.checked) {
    show(category);
  } else {
    hide(category);
  }
    // == rebuild the side bar
    // makeSidebar();
}
function createOption(name, distance, num) {
  var option = document.createElement("option");
  option.value = num;
  option.innerHTML = name + "(" + distance.toFixed(1) + ")";
  locationSelect.appendChild(option);
}
//Look up XML sheet to get data
function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
  new ActiveXObject('Microsoft.XMLHTTP') :
  new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      callback(request.responseText, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}

function parseXml(str) {
  if (window.ActiveXObject) {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  } else if (window.DOMParser) {
    return (new DOMParser).parseFromString(str, 'text/xml');
  }
}
4

1 回答 1

1

有人给了我这个答案,但答案已经消失了。有代码最终工作

function boxclick() {
    //create an array of the checked checkbox-IDs
    var c = j.grep(['onlineretailer','bottleshop','bar'],
        function(i) {
            return (j('#'+i.toLowerCase()+':checked').length);
            //console.log(i); i holds each value in the array in lowercase form
    });
    //console.log(c); // C holds all the checkbox values in an array

    //iterate over the markers and set their visibility
    //to true when at least 1 of the checkbox-values matches
    //otherwise to false
    j.each(markers,function(i,m) {
        this.setVisible(j.grep(c,function(v) {
            console.log(c,v,m); // c = checkboxes checked, v = value , m = marker
            return (m[v+'Value']=='TRUE')
        }).length>0);
    });  
}
于 2013-01-31T01:05:23.140 回答