Javascript Google Maps API v3:组标记?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2039156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:31:35  来源:igfitidea点击:

Google Maps API v3: Group markers?

javascriptgoogle-mapsgoogle-maps-api-3

提问by Johannes

I'm using Google Maps with API v3. I will add many markers, now got question, is there posibility to group markers? For example, by city? I'm using a small snippet to creating sidebar with markers buttons.

我正在使用带有 API v3 的 Google 地图。我将添加许多标记,现在有一个问题,是否可以对标记进行分组?例如,按城市?我正在使用一个小片段来创建带有标记按钮的侧边栏。

Here's the code:

这是代码:

/**
 * map
 */
var mapOpts = {
  mapOpts: new google.maps.LatLng(60.28527,24.84864),
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  scaleControl: true,
  scrollwheel: false
}
var map = new google.maps.Map(document.getElementById("map"), mapOpts);
//  We set zoom and center later by fitBounds()



/**
 * makeMarker() ver 0.2
 * creates Marker and InfoWindow on a Map() named 'map'
 * creates sidebar row in a DIV 'sidebar'
 * saves marker to markerArray and markerBounds
 * @param options object for Marker, InfoWindow and SidebarItem
 * @author Esa 2009
 */
var infoWindow = new google.maps.InfoWindow();
var markerBounds = new google.maps.LatLngBounds();
var markerArray = [];

function makeMarker(options){
  var pushPin = new google.maps.Marker({map:map});
  pushPin.setOptions(options);
  google.maps.event.addListener(pushPin, "click", function(){
    infoWindow.setOptions(options);
    infoWindow.open(map, pushPin);
    if(this.sidebarButton)this.sidebarButton.button.focus();
  });
  var idleIcon = pushPin.getIcon();
  if(options.sidebarItem){
    pushPin.sidebarButton = new SidebarItem(pushPin, options);
    pushPin.sidebarButton.addIn("sidebar");
  }
  markerBounds.extend(options.position);
  markerArray.push(pushPin);
  return pushPin;
}

google.maps.event.addListener(map, "click", function(){
  infoWindow.close();
});


/**
 * Creates a sidebar item 
 * @constructor
 * @author Esa 2009
 * @param marker
 * @param options object Supported properties: sidebarItem, sidebarItemClassName, sidebarItemWidth,
 */
function SidebarItem(marker, opts){
  var tag = opts.sidebarItemType || "button";
  var row = document.createElement(tag);
  row.innerHTML = opts.sidebarItem;
  row.className = opts.sidebarItemClassName || "sidebar_item";  
  row.style.display = "block";
  row.style.width = opts.sidebarItemWidth || "120px";
  row.onclick = function(){
    google.maps.event.trigger(marker, 'click');
  }
  row.onmouseover = function(){
    google.maps.event.trigger(marker, 'mouseover');
  }
  row.onmouseout = function(){
    google.maps.event.trigger(marker, 'mouseout');
  }
  this.button = row;
}
// adds a sidebar item to a <div>
SidebarItem.prototype.addIn = function(block){
  if(block && block.nodeType == 1)this.div = block;
  else
    this.div = document.getElementById(block)
    || document.getElementById("sidebar")
    || document.getElementsByTagName("body")[0];
  this.div.appendChild(this.button);
}
// deletes a sidebar item
SidebarItem.prototype.remove = function(){
  if(!this.div) return false;
  this.div.removeChild(this.button);
  return true;
}

/**
 * markers and info window contents
 */
makeMarker({
  position: new google.maps.LatLng(60.28527,24.84864),
  title: "Vantaankoski",
  sidebarItem: "Vantaankoski",
  content: "Vantaankoski"
});   
makeMarker({
  position: new google.maps.LatLng(60.27805,24.85281),
  title: "Martinlaakso",
  sidebarItem: "Martinlaakso",
  content: "Martinlaakso"
});  
makeMarker({
  position: new google.maps.LatLng(60.27049,24.85366),
  title: "Louhela",
  sidebarItem: "Louhela",
  content: "Louhela"
}); 
makeMarker({
  position: new google.maps.LatLng(60.26139,24.85478),
  title: "Myyrm?ki",
  sidebarItem: "Myyrm?ki",
  content: "Myyrm?ki"
});   
makeMarker({
  position: new google.maps.LatLng(60.24929,24.86128),
  title: "Malminkartano",
  sidebarItem: "Malminkartano",
  content: "Malminkartano"
});  
makeMarker({
  position: new google.maps.LatLng(60.23963,24.87694),
  title: "Kannelm?ki",
  sidebarItem: "Kannelm?ki",
  content: "Kannelm?ki"
}); 
makeMarker({
  position: new google.maps.LatLng(60.23031,24.88353),
  title: "Pohjois-Haaga",
  sidebarItem: "Pohjois<br>Haaga",
  content: "Pohjois-Haaga"
});   
makeMarker({
  position: new google.maps.LatLng(60.21831,24.89354),
  title: "Huopalahti",
  sidebarItem: "Huopalahti",
  content: "Huopalahti"
});   
makeMarker({
  position: new google.maps.LatLng(60.20803,24.92039),
  title: "Ilmala",
  sidebarItem: "Ilmala",
  content: "Ilmala"
});    
makeMarker({
  position: new google.maps.LatLng(60.19899,24.93269),
  title: "Pasila",
  sidebarItem: "Pasila",
  content: "Pasila"
});  
makeMarker({
  position: new google.maps.LatLng(60.17295,24.93981),
  title: "Helsinki",
  sidebarItem: "Helsinki",
  content: "Helsinki"
});    




/**
 *   fit viewport to markers
 */
map.fitBounds(markerBounds);

回答by jeremygerrits

Here's the v3 version:

这是 v3 版本

Marker Clusterer

...The library creates and manages per-zoom-level clusters for large amounts of markers. This is a V3 implementation of the V2 MarkerClusterer.

Browse Released Versionsor Development Versions...

标记聚类器

...该库为大量标记创建和管理每个缩放级别的集群。这是 V2 MarkerClusterer 的 V3 实现。

浏览已发布版本开发版本...

回答by user1469420

Better yet, use MarkerClustererPlus. Many enhancements and it incorporates plenty of bug fixes for problems found in the original MarkerClusterer.

更好的是,使用 MarkerClustererPlus。许多增强功能,并且针对原始 MarkerClusterer 中发现的问题进行了大量错误修复。

回答by conualfy

You should use markerclusterer (http://gmaps-utility-library-dev.googlecode.com/svn/trunk/markerclusterer/docs/examples.html). A working example:

您应该使用 markerclusterer ( http://gmaps-utility-library-dev.googlecode.com/svn/trunk/markerclusterer/docs/examples.html)。一个工作示例:

function drop() {
  for (var i = 0; i < markere.length; i++) {
    //setTimeout(function() {//for maps with few markers works great to add them with delay
    addMarker();
    //}, i * 200);
  }

  //group markers; page loads a lot faster when you have many markers
  var mc = new MarkerClusterer(map, markers);//group with markerclusterer (don't forget to include the js file)

  //make sure they fit screen
  var bounds = new google.maps.LatLngBounds();
  for(var i=0;i<markers.length;i++){
    bounds.extend(markers[i].getPosition());
  }
  map.fitBounds(bounds); 
}


function addMarker() {
    /*before pushing we set some properties */
    var marker = new google.maps.Marker({
        position: markere[i],
        map: map,
        draggable: false,
        animation: google.maps.Animation.DROP,
        flat: false,
        icon: "./wp-content/themes/clear/images/obiectiv.png",
        title: denumire[i]
    })
    /*set infowindow*/
    var content = "<p><strong>"+denumire[i]+"</strong></p>";
    var catStr = '';
    var nrCat = categorii[i].length;
    for (var j = 0; j < nrCat; j++) {
        catStr += categorii[i][j];
    }
    content+= "<p>"+catStr+"</p>";
    nrCatStr = "";
    if (nrCat==1) nrCatStr = "categorie"
    else if (nrCat>1) nrCatStr = "categorii";
    content+= "<p>"+nrCat+" "+nrCatStr+"</p>";        
    /* //I don't use mouseover/mouseout
    google.maps.event.addListener(marker, 'mouseover', function() {
        this.infowindow.open(map, this);
    });
    google.maps.event.addListener(marker, 'mouseout', function() {
        this.infowindow.close(map, this);
    });*/
    //google.maps.event.addListener(marker, 'click', toggleBounce);
    infowindow = null;
    google.maps.event.addListener(marker, 'click', function() {
        if (infowindow) {
            infowindow.close();
        }
        infowindow = new google.maps.InfoWindow({
            content: content
        });
        google.maps.event.addListener(infowindow, 'closeclick', function() {
            stopBounce(markers);
        });
        infowindow.open(map, this);

        toggleBounce(this);
    });

    markers.push(marker);
    i++;
}/**/


drop();//drop the markers

function toggleBounce(obj) {
    if (obj.getAnimation() != null) {
        obj.setAnimation(null);
    } else {
        stopBounce(markers);//stop bouncing markers
        obj.setAnimation(google.maps.Animation.BOUNCE);
    }
}

function stopBounce(markers){
    for (var k = 0; k < markers.length; k++) {
        if (markers[k].getAnimation() != null) { markers[k].setAnimation(null); }
    }        
}

回答by Pragya27

Code snippet below may do the job for you.

下面的代码片段可以为您完成这项工作。

function codeAddress() {
 var address = document.getElementById('address').value;
    geocoder.geocode({
        'address': address
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var myOptions = {
                zoom: 16,
                center: results[0].geometry.location,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            if(!map)    {
            map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);}

            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });

            bounds.extend(marker.position);
            map.fitBounds(bounds);
             google.maps.event.addListener(marker,'mouseover',   ( function(marker) {
            return function() {
               var infowindow = new google.maps.InfoWindow();
              //  alert("hi");
                var content = '<div class="map-content"><h3>' + address + '</h3> </div>';
              infowindow.setContent(content);
              infowindow.open(map, marker);
            }
          })(marker));
        } else {
          alert('Geocode was not successful for the following reason: ' + status);
        }
    });
}

回答by xomena

Google code has been deprecated as per

谷歌代码已被弃用

http://google-opensource.blogspot.com.es/2015/03/farewell-to-google-code.html

http://google-opensource.blogspot.com.es/2015/03/farewell-to-google-code.html

So all libraries mentioned in previous answers migrated to GitHub. You can find them at

所以之前答案中提到的所有库都迁移到了 GitHub。你可以在

https://github.com/googlemaps/v3-utility-library

https://github.com/googlemaps/v3-utility-library