按类别对标记进行分组以显示和隐藏 [英] Grouping markers by category to show and hide
本文介绍了按类别对标记进行分组以显示和隐藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
function addMarkersToMap(map){
/ /触发在地图上调整大小,以防画布大小不同
google.maps.event.trigger(map,'resize');
//删除现有标记
google.maps.Map.prototype.clearMarkers();
//创建一个新的边界对象(不需要现有的边界)
var bounds = new google.maps.LatLngBounds();
//如果有一个地图中心,用它来居中地图
$('。mapCenter')。这个).find('[itemprop =latitude]')。attr('content');
var lng = $(this).find('[itemprop =longitude]')。attr 'content');
map.setCenter(new google.maps.LatLng(lat,lng));
});
$('[itemtype =http://schema.org/Place],[itemtype =http://schema.org/LocalBusiness] ').each(function(){
var title = $(this).find('[itemprop =name]')。text();
var contentString = $(this)。 html();
var lat = $(this).find('[itemprop =latitude]')。attr('content');
var lng = $(this).find ('data');
var class = $(this)。[ .find('[itemprop ='category']')。attr('content');
var marker = addMarker(map,title,contentString,lat,lng,icon,category);
bounds .extend(marker.position);
});
$ b $ // add kml
$('。MapHolder [data-url]')。each(function(){
var kml = $(this).attr(' data-url');
var kmlLayer = new google.maps.KmlLayer(kml);
kmlLayer.setMap(map);
});
if(!bounds.isEmpty()){
map.fitBounds(bounds);
$ b函数addMarker(map,title,contentString,lat,lng,icon,category){
var image;
var shadow;
var shape;
if(icon){
image = new google.maps.MarkerImage(icon,
new google.maps.Size(31,41),
new google.maps.Point (0,0),
new google.maps.Point(15,40));
var marker = new google.maps.Marker({
position:new google.maps.LatLng(lat,lng),
map:map,
标题:标题,
图标:图像,
形状:形状,
阴影:阴影
});
if(contentString!=''){
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent($(' < div> + contentString +'< / div>').ajaxify()。get(0));
infowindow.open(map,marker);
});
}
return marker;
}
我希望能够为每个标记指定一个类别,以便我可以根据类别切换标记的可见性(例如,显示/隐藏兴趣点或显示/隐藏公共厕所等)。
如何修改现有的代码能够实现我所追求的目标吗?
解决方案
这是一个例子(从Mike Williams的v2教程移植过来)做到这一点:
http://www.geocodezip .com / v3_MW_example_categories.html
程式码片段:
//这个变量将会收集最终放置在side_bar中的html页面var side_bar_html =; var gmarkers = []; var gicons = []; var map = null; va r infowindow = new google.maps.InfoWindow({size:new google.maps.Size(150,50)}); gicons [red] = new google.maps.MarkerImage(http://maps.google。 com / mapfiles / ms / micons / red.png,//这个标记是32像素宽×32像素高。新的google.maps.Size(32,32),//这张图片的原点是0,0。新的google.maps.Point(0,0),//这张图片的锚点位于16,32。新的google.maps.Point(16,32)); //标记大小表示为X,Y的大小//图像的原点(0,0)位于//图像左上角.//标记的起源,锚点位置和坐标//在X方向向右和在Y方向向下增加.var iconImage = new google.maps.MarkerImage('http://maps.google。 com / mapfiles / ms / micons / red.png',//这个标记的宽度是32像素,高度是32像素new google.maps.Size(32,32),//这张图片的原点是0,0。 new google.maps.Point(0,0),//此图片的锚点位于16,32。new google.maps.Point(16,32)); // Shapes定义图标的可点击区域。 /该类型定义了HTML& lt; area& gt;元素'poly'//它将多边形描绘为一系列X,Y点。最后的//坐标通过连接到第一个// coordinate.var来关闭多边形。iconShape = {coord:[9,0,6,1,4,2,2,4,0,8,0,12,1,第14,第21,第16,第18,第19,第23,第8,第26,第9,第30,第9,第34,第11, (typeof(iconColor)= 0);函数getMarkerImage(iconColor){if((typeof(iconColor)= =undefined)||(iconColor == null)){iconColor =red; } if(!gicons [iconColor]){gicons [iconColor] = new google.maps.MarkerImage(http://maps.google.com/mapfiles/ms/micons/+ iconColor +.png,//新的google.maps.Size(32,32),//这张图片的原点是0,0。new google.maps.Point(0,0),//这个标记是20像素宽,34像素高。此图片的锚点位于6,20。new google.maps.Point(16,32)); } return gicons [iconColor];} function category2color(category){var color =red;开关(类别){casetheatre:color =blue;打破;案例高尔夫:color =green;打破; caseinfo:color =yellow;打破;默认值:color =red;打破; } color color;} gicons [theatre] = getMarkerImage(category2color(theatre)); gicons [golf] = getMarkerImage(category2color(golf)); gicons [info] = getMarkerImage(category2color info)); //创建标记并设置事件窗口函数的函数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 }); // ===将类别和名称信息存储为标记属性=== marker.mycategory = category; marker.myname = name; gmarkers.push(标记); google.maps.event.addListener(marker,'click',function(){infowindow.setContent(contentString); infowindow.open(map,marker);});} // ==显示特定类别的所有标记,并确保复选框被选中==功能show(category){for(var i = 0; i< gmarkers.length; i ++){if(gmarkers [i] .mycategory == category){gmarkers [i] .setVisible (真正); }} // ==检查复选框== document.getElementById(category +box)。checked = true;} // ==隐藏特定类别的所有标记,并确保复选框被清除== function hide(类别){for(var i = 0; i< gmarkers.length; i ++){if(gmarkers [i] .mycategory == category){gmarkers [i] .setVisible(false); }} // ==清除复选框== document.getElementById(category +box)。checked = false; // ==关闭信息窗口,以防它在我们刚刚隐藏的标记上打开infowindow.close();} // ==复选框已被点击==功能boxclick(box,category){if(box。选中){show(category); } else {hide(category); } // ==重建侧边栏makeSidebar();} function myclick(i){google.maps.event.trigger(gmarkers [i],click);} // ==重建边栏以匹配标记当前显示==功能makeSidebar(){var html =; for(var i = 0; i html,body {height:100%;}
< script src =http://maps.google.com/maps/api/js>< / script>< table border = 1> < TR> < TD> < div id =mapstyle =width:550px; height:450px>< / div> < / TD> < td valign =topstyle =width:150px; text-decoration:underline; color:#4444ff;> < div id =side_bar>< / div> < / TD> < / tr>< / table>< form action =#>影院:< input type =checkboxid =theatreboxonclick =boxclick(this,'theatre')/>& nbsp;& nbsp;高尔夫球场:< input type =checkboxid =golfboxonclick =boxclick(this,'golf')/>& nbsp;& nbsp;旅游信息:< input type =checkboxid =infoboxonclick =boxclick(this,'info')/> < br />< / form>
I am adding markers to a google map with the following:
function addMarkersToMap(map) {
// trigger resize on map in case canvas size is different
google.maps.event.trigger(map, 'resize');
// remove existing markers
google.maps.Map.prototype.clearMarkers();
// create a new bounds object (don't want existing bounds)
var bounds = new google.maps.LatLngBounds();
// If there is a map center, use it to center the map
$('.mapCenter').each(function() {
var lat = $(this).find('[itemprop="latitude"]').attr('content');
var lng = $(this).find('[itemprop="longitude"]').attr('content');
map.setCenter(new google.maps.LatLng(lat, lng));
});
$('[itemtype="http://schema.org/Place"], [itemtype="http://schema.org/LocalBusiness"]').each(function() {
var title = $(this).find('[itemprop="name"]').text();
var contentString = $(this).html();
var lat = $(this).find('[itemprop="latitude"]').attr('content');
var lng = $(this).find('[itemprop="longitude"]').attr('content');
var icon = $(this).attr('data-class');
var category = $(this).find('[itemprop="category"]').attr('content');
var marker = addMarker(map, title, contentString, lat, lng, icon, category);
bounds.extend(marker.position);
});
// add kml
$('.MapHolder[data-url]').each(function() {
var kml = $(this).attr('data-url');
var kmlLayer = new google.maps.KmlLayer(kml);
kmlLayer.setMap(map);
});
if(!bounds.isEmpty()) {
map.fitBounds(bounds);
}
}
function addMarker(map, title, contentString, lat, lng, icon, category) {
var image;
var shadow;
var shape;
if (icon) {
image = new google.maps.MarkerImage( icon ,
new google.maps.Size(31, 41),
new google.maps.Point(0,0),
new google.maps.Point(15, 40));
}
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: title,
icon: image,
shape: shape,
shadow: shadow
});
if(contentString != '') {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent($('<div>' + contentString + '</div>').ajaxify().get(0));
infowindow.open(map, marker);
});
}
return marker;
}
I want to be able to specify a category for each of these markers so that I can toggle the visibility of the markers based on category (ie, show/hide points of interest or show/hide public toilets etc).
How can I modify my existing code to be able to achieve what I am after?
解决方案
Here is an example (ported from Mike Williams' v2 tutorial) that does that:
http://www.geocodezip.com/v3_MW_example_categories.html
code snippet:
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
var gmarkers = [];
var gicons = [];
var map = null;
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
gicons["red"] = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/red.png",
// This marker is 32 pixels wide by 32 pixels tall.
new google.maps.Size(32, 32),
// The origin for this image is 0,0.
new google.maps.Point(0, 0),
// The anchor for this image is at 16,32.
new google.maps.Point(16, 32));
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var iconImage = new google.maps.MarkerImage('http://maps.google.com/mapfiles/ms/micons/red.png',
// This marker is 32 pixels wide by 32 pixels tall.
new google.maps.Size(32, 32),
// The origin for this image is 0,0.
new google.maps.Point(0, 0),
// The anchor for this image is at 16,32.
new google.maps.Point(16, 32));
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var iconShape = {
coord: [9, 0, 6, 1, 4, 2, 2, 4, 0, 8, 0, 12, 1, 14, 2, 16, 5, 19, 7, 23, 8, 26, 9, 30, 9, 34, 11, 34, 11, 30, 12, 26, 13, 24, 14, 21, 16, 18, 18, 16, 20, 12, 20, 8, 18, 4, 16, 2, 15, 1, 13, 0],
type: 'poly'
};
function getMarkerImage(iconColor) {
if ((typeof(iconColor) == "undefined") || (iconColor == null)) {
iconColor = "red";
}
if (!gicons[iconColor]) {
gicons[iconColor] = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/" + iconColor + ".png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(32, 32),
// The origin for this image is 0,0.
new google.maps.Point(0, 0),
// The anchor for this image is at 6,20.
new google.maps.Point(16, 32));
}
return gicons[iconColor];
}
function category2color(category) {
var color = "red";
switch (category) {
case "theatre":
color = "blue";
break;
case "golf":
color = "green";
break;
case "info":
color = "yellow";
break;
default:
color = "red";
break;
}
return color;
}
gicons["theatre"] = getMarkerImage(category2color("theatre"));
gicons["golf"] = getMarkerImage(category2color("golf"));
gicons["info"] = getMarkerImage(category2color("info"));
// 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);
});
}
// == 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 + ')">' + gmarkers[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
// downloadUrl("categories.xml", function(doc) {
var xml = xmlParse(xmlData);
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 address = markers[i].getAttribute("address");
var name = markers[i].getAttribute("name");
var html = "<b>" + name + "<\/b><p>" + address;
var category = markers[i].getAttribute("category");
// create the marker
var marker = createMarker(point, name, html, category);
}
// == show or hide the categories initially ==
show("theatre");
hide("golf");
hide("info");
// == create the initial sidebar ==
makeSidebar();
// });
}
google.maps.event.addDomListener(window, 'load', initialize);
var xmlData = '<markers> <marker name="Grand Theatre" address="33 Church St, Blackpool, Lancashire, FY1 1HT" lng="-3.053102" lat="53.817260" category="theatre" /> <marker name="Claremont Theatre Club" address="Burwood Dr, Blackpool, Lancashire, FY3 8NS" lng="-3.049690" lat="53.829649" category="theatre" /> <marker name="Pendle Productions" address="249 Hawes Side La, Blackpool, Lancashire, FY4 4AA" lng="-3.030698" lat="53.794399" category="theatre" /> <marker name="Tram Shed Theatre" address="7 Moor Pk Av, Blackpool, Lancashire, FY2 0LT" lng="-3.034974" lat="53.845938" category="theatre" /> <marker name="Thornton Little Theatre" address="Fleetwood Road North, Thornton Cleveleys, FY5 3SZ" lng="-3.010607" lat="53.872058" category="theatre" /> <marker name="Barbara Jackson Arts" address="Rossall La, Fleetwood, Lancashire, FY7 8JP" lng="-3.033960" lat="53.897928" category="theatre" /> <marker name="North Shore Golf Club" address="Devonshire Rd, Blackpool, Lancashire, FY2 0RD" lng="-3.043305" lat="53.839898" category="golf" /> <marker name="St Annes Old Links" address="Highbury Road East, Lytham St. Annes, Lancashire, FY8 2LD" lng="-3.038407" lat="53.762917" category="golf" /> <marker name="Fairhaven Golf Club" address="Oakwood Av, Lytham St. Annes, Lancashire, FY8 4JU" lng="-2.983218" lat="53.742781" category="golf" /> <marker name="Green Drive Golf Club" address="Ballam Rd, Lytham St. Annes, Lancashire, FY8 4LE" lng="-2.959530" lat="53.745971" category="golf" /> <marker name="Fleetwood Golf Club" address="Princes Wy, Fleetwood, Lancashire, FY7 8AF" lng="-3.042973" lat="53.917606" category="golf" /> <marker name="Knott End Golf Club" address="Wyre Side, Knott End-on-Sea, Poulton-le-Fylde, Lancashire, FY6 0AA" lng="-2.997062" lat="53.923200" category="golf" /> <marker name="Tourist Information 1" address="1 Clifton St, Blackpool, Lancashire, FY1 1LY" lng="-3.054529" lat="53.818775" category="info" /> <marker name="Tourist Information 2" address="Thornton-Cleveleys, Lancashire, FY5 1WA" lng="-3.042989" lat="53.876079" category="info" /> <marker name="Tourist Information 3" address="Victoria Rd West, Thornton-Cleveleys, Lancashire, FY5 1AJ" lng="-3.041668" lat="53.877403" category="info" /> <marker name="Tourist Information 4" address="St. Annes Rd West, Lytham St. Annes, Lancashire, FY8 1SA" lng="-3.031074" lat="53.752122" category="info" /> <marker name="Tourist Information 5" address="The Esplanade, Fleetwood, Lancashire, FY7 6DL" lng="-3.006366" lat="53.926970" category="info" /> <marker name="Tourist Information 6" address="10-12 York St, Blackpool, Lancashire, FY1 5AQ" lng="-3.052919" lat="53.810556" category="info" /></markers>';
function xmlParse(str) {
if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
}
if (typeof DOMParser != 'undefined') {
return (new DOMParser()).parseFromString(str, 'text/xml');
}
return createElement('div', null);
}
html,
body {
height: 100%;
}
<script src="http://maps.google.com/maps/api/js"></script>
<table border=1>
<tr>
<td>
<div id="map" style="width: 550px; height: 450px"></div>
</td>
<td valign="top" style="width:150px; text-decoration: underline; color: #4444ff;">
<div id="side_bar"></div>
</td>
</tr>
</table>
<form action="#">
Theatres:
<input type="checkbox" id="theatrebox" onclick="boxclick(this,'theatre')" /> Golf Courses:
<input type="checkbox" id="golfbox" onclick="boxclick(this,'golf')" /> Tourist Information:
<input type="checkbox" id="infobox" onclick="boxclick(this,'info')" />
<br />
</form>
这篇关于按类别对标记进行分组以显示和隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文