将群集添加到我的Google Maps脚本中

时间:2015-09-26 04:16:57

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

我正在尝试将Map Clustering添加到现有脚本中。

我想添加此代码,并将其混合到我现有的代码中。

代码 - 下面脚本的工作示例。 https://googlemaps.github.io/js-marker-clusterer/examples/advanced_example.html

<script>
      var script = '<script type="text/javascript" src="../src/markerclusterer';
      if (document.location.search.indexOf('compiled') !== -1) {
        script += '_compiled';
      }
      script += '.js"><' + '/script>';
      document.write(script);
    </script>

    <script>
      var styles = [[{
        url: '../images/people35.png',
        height: 35,
        width: 35,
        anchor: [16, 0],
        textColor: '#ff00ff',
        textSize: 10
      }, {
        url: '../images/people45.png',
        height: 45,
        width: 45,
        anchor: [24, 0],
        textColor: '#ff0000',
        textSize: 11
      }, {
        url: '../images/people55.png',
        height: 55,
        width: 55,
        anchor: [32, 0],
        textColor: '#ffffff',
        textSize: 12
      }], [{
        url: '../images/conv30.png',
        height: 27,
        width: 30,
        anchor: [3, 0],
        textColor: '#ff00ff',
        textSize: 10
      }, {
        url: '../images/conv40.png',
        height: 36,
        width: 40,
        anchor: [6, 0],
        textColor: '#ff0000',
        textSize: 11
      }, {
        url: '../images/conv50.png',
        width: 50,
        height: 45,
        anchor: [8, 0],
        textSize: 12
      }], [{
        url: '../images/heart30.png',
        height: 26,
        width: 30,
        anchor: [4, 0],
        textColor: '#ff00ff',
        textSize: 10
      }, {
        url: '../images/heart40.png',
        height: 35,
        width: 40,
        anchor: [8, 0],
        textColor: '#ff0000',
        textSize: 11
      }, {
        url: '../images/heart50.png',
        width: 50,
        height: 44,
        anchor: [12, 0],
        textSize: 12
      }]];

      var markerClusterer = null;
      var map = null;
      var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&' +
          'chco=FFFFFF,008CFF,000000&ext=.png';

      function refreshMap() {
        if (markerClusterer) {
          markerClusterer.clearMarkers();
        }

        var markers = [];

        var markerImage = new google.maps.MarkerImage(imageUrl,
          new google.maps.Size(24, 32));

        for (var i = 0; i < 1000; ++i) {
          var latLng = new google.maps.LatLng(data.photos[i].latitude,
              data.photos[i].longitude)
          var marker = new google.maps.Marker({
            position: latLng,
            draggable: true,
            icon: markerImage
          });
          markers.push(marker);
        }

        var zoom = parseInt(document.getElementById('zoom').value, 10);
        var size = parseInt(document.getElementById('size').value, 10);
        var style = parseInt(document.getElementById('style').value, 10);
        zoom = zoom === -1 ? null : zoom;
        size = size === -1 ? null : size;
        style = style === -1 ? null: style;

        markerClusterer = new MarkerClusterer(map, markers, {
          maxZoom: zoom,
          gridSize: size,
          styles: styles[style]
        });
      }

      function initialize() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 2,
          center: new google.maps.LatLng(39.91, 116.38),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var refresh = document.getElementById('refresh');
        google.maps.event.addDomListener(refresh, 'click', refreshMap);

        var clear = document.getElementById('clear');
        google.maps.event.addDomListener(clear, 'click', clearClusters);

        refreshMap();
      }

      function clearClusters(e) {
        e.preventDefault();
        e.stopPropagation();
        markerClusterer.clearMarkers();
      }

      google.maps.event.addDomListener(window, 'load', initialize);
    </script>

然后我想采用上面的代码并将聚类添加到我现有的代码中。

<script type="text/javascript">
 $(document).ready(function() {

                    var mapCenter = new google.maps.LatLng(47.701829, -122.179969);
                    var map;

                 map_initialize(); 

        function map_initialize()
        {
                    var googleMapOptions = 
                    { 
                        center: mapCenter, // map center
                        zoom: 13,
                        maxZoom: 22,
                        minZoom: 10,
                            zoomControlOptions: {
                                style: google.maps.ZoomControlStyle.SMALL,
                                position: google.maps.ControlPosition.RIGHT_TOP
                        },

                            mapTypeId: google.maps.MapTypeId.ROADMAP,
                            styles: [{
            stylers: [{
                saturation: -100
            }]
        }, {
            featureType: "water",
            elementType: "geometry.fill",
            stylers: [{
                color: "#0099dd"
            }]
        }, {
            elementType: "labels",
            stylers: [{
                visibility: "off"
            }]
        }, {
            featureType: "poi.park",
            elementType: "geometry.fill",
            stylers: [{
                color: "#aadd55"
            }]
        }, {
            featureType: "road.highway",
            elementType: "labels",
            stylers: [{
                visibility: "on"
            }]
        }, {
            featureType: "road.arterial",
            elementType: "labels.text",
            stylers: [{
                visibility: "on"
            }]
        }, {
            featureType: "road.local",
            elementType: "labels.text",
            stylers: [{
                visibility: "on"
            }]
        }, {}] 
                        };

                    map = new google.maps.Map(document.getElementById("map"), googleMapOptions);            

            $.get("map_process.php", function (data) {
                $(data).find("marker").each(function () {
                    var pin_firstname           = $(this).attr('pin_firstname');
                    var pincore_fulladdress     = '<p>'+ $(this).attr('pincore_fulladdress') +'</p>';
                    var pin_status              = $(this).attr('pin_status');
                    var point                   = new google.maps.LatLng(parseFloat($(this).attr('pincore_lat')),parseFloat($(this).attr('pincore_lng')));
                        create_marker(point, pin_firstname, pincore_fulladdress, false, false, false, "icons/pin_blue.png");
                });


            }); 

            google.maps.event.addListener(map, 'click', function(event) {
                    var EditForm = '<p><div class="marker-edit">'+
                                    '<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker">'+
                                    '<label for="pPinStatus"><span>Status:</span> <select name="pPinStatus" class="save-type"><option value="Sold">SOLD</option><option value="Cancelled">Cancelled</option>'+
                                    '<option value="house">Rejected</option></select></label>'+
                                    '<label for="pFullName"><span>Customer Name:</span><input type="text" name="pFullName" class="save-name" placeholder="Enter Title" maxlength="40" /></label>'+
                                    '<label for="pDesc"><span>Address :</span><textarea name="pDesc" class="save-desc" placeholder="Enter Address" maxlength="150"></textarea></label>'+
                                    '</form>'+
                                    '</div></p><button name="save-marker" class="save-marker">Save Marker</button>';

                create_marker(event.latLng, 'Add New Pin', EditForm, true, true, true, "icons/pin_green.png");
            });

    }

    function create_marker(MapPos, MapTitle, MapDesc,  InfoOpenDefault, DragAble, Removable, iconPath, mType)
    {                 


                    var marker = new google.maps.Marker({
                        position: MapPos,
                        map: map,
                        draggable:DragAble,
                        animation: google.maps.Animation.DROP,
                        icon: iconPath

        });

                    var contentString = $('<div class="marker-info-win">'+
                                            '<div class="marker-inner-win"><span class="info-content">'+
                                            '<h1 class="marker-heading">'+mType+'</h1>'+
                                            MapTitle+
                                            MapDesc+

                                            '</span><button name="remove-marker" class="remove-marker">Remove Marker</button>'+
                                            '</div></div>');    


        var infowindow = new google.maps.InfoWindow();
        infowindow.setContent(contentString[0]);

        var removeBtn   = contentString.find('button.remove-marker')[0];
        var saveBtn     = contentString.find('button.save-marker')[0];

        google.maps.event.addDomListener(removeBtn, "click", function(event) {
            remove_marker(marker);
        });

        if(typeof saveBtn !== 'undefined') 
        {
            //add click listner to save marker button
            google.maps.event.addDomListener(saveBtn, "click", function(event) {
                var mReplace = contentString.find('span.info-content'); 
                var mName = contentString.find('input.save-name')[0].value; 
                var mDesc  = contentString.find('textarea.save-desc')[0].value; 
                var mType = contentString.find('select.save-type')[0].value;

                if(mName =='' || mDesc =='')
                {
                    alert("Please enter the correct information to disposition a new pin!");
                }else{
                    save_marker(marker, mName, mDesc, mType, mReplace); 
                }
            });
        }


        google.maps.event.addListener(marker, 'click', function() {

                var marker = new google.maps.Marker({
                        position: MapPos,
                        map: map,
                        animation: google.maps.Animation.DROP,
                        icon: iconPath


                });
                infowindow.open(map,marker); 
        });

        if(InfoOpenDefault) 
        {
          infowindow.open(map,marker);
        }
    }

    function remove_marker(Marker)
    {


        if(Marker.getDraggable()) 
        {
            Marker.setMap(null);
        }
        else
        {
            var mLatLang = Marker.getPosition().toUrlValue(); 
            var myData = {del : 'true', latlang : mLatLang};
            $.ajax({
              type: "POST",
              url: "map_process.php",
              data: myData,
              success:function(data){
                    Marker.setMap(null); 
                    alert(data);
                },
                error:function (xhr, ajaxOptions, thrownError){
                    alert(thrownError); 
                }
            });
        }

    }

    function save_marker(Marker, mName, mAddress, mType, replaceWin)
            {
                var mLatLang = Marker.getPosition().toUrlValue(); 
                var myData = {pin_firstname : mName, pincore_fulladdress : mAddress, latlang : mLatLang, pin_status : mType }; 
                    console.log(replaceWin);        
                        $.ajax({
                        type: "POST",
                        url: "map_process.php",
                        data: myData,
                    success:function(data){
                        replaceWin.html(data); 
                            Marker.setDraggable(false); 
                            Marker.setIcon('icons/pin_blue.png'); 
            },
            error:function (xhr, ajaxOptions, thrownError){
                alert(thrownError); 
            }
        });
    }

});
</script>

任何帮助都将非常感谢!!!

1 个答案:

答案 0 :(得分:2)

首先定义一个标记数组,将每个创建的标记推送到那里,然后在该数组上调用markerClusterer。这种方法对我有用一次,这正是您列出的googlemaps代码中建议的内容:

var markers = [];
function create_marker(MapPos, MapTitle, MapDesc,  InfoOpenDefault, DragAble, Removable, iconPath, mType)
{                 
    var marker = new google.maps.Marker({
        position: MapPos,
        map: map,
        draggable:DragAble,
        animation: google.maps.Animation.DROP,
        icon: iconPath

    });
    markers.push(marker);
}

运行create_marker函数(在解析ajax数据后的情况下),然后创建像

这样的集群
markerClusterer = new MarkerClusterer(map, markers, {
      maxZoom: zoom,
      gridSize: size,
      styles: styles[style]
    });

使用remove_marker()或save_marker()函数更新markerClusterer对象时,可能需要调用refreshMap()。

一定要包含jQuery,Google maps API和markerclusterer脚本。这是我的codepen的完整输出:

&#13;
&#13;
	var infoWindows = [];
	var markers = [];
	var markerClusterer = null;
	var map = null;
	var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&' + 'chco=FFFFFF,008CFF,000000&ext=.png';
	var pinIcon = "icons/pin_green.png";
	var pinIcon = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&' + 'chco=FFFFFF,00FF8C,000000&ext=.png';

	function refreshMap() {
			if (markerClusterer) {
					markerClusterer.clearMarkers();
					// 				markerClusterer.addMarkers(markers,true)
					markerClusterer.addMarkers(markers)
			}
	}

	function clearClusters(e) {
					e.preventDefault();
					e.stopPropagation();
					markerClusterer.clearMarkers();
			}
			//////////custom code
	var mapCenter = new google.maps.LatLng(47.701829, -122.179969);
	var map;

	function map_initialize() {
			var googleMapOptions = {
					center: mapCenter, // map center
					zoom: 13,
					maxZoom: 22,
					minZoom: 4,
					zoomControlOptions: {
							style: google.maps.ZoomControlStyle.SMALL,
							position: google.maps.ControlPosition.RIGHT_TOP
					},
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					styles: roadmap_styles
			};
			map = new google.maps.Map(document.getElementById("map"), googleMapOptions);
			$.get("map_process.php", function(data) {
					$(data).find("marker").each(function() {
							var pin_firstname = $(this).attr('pin_firstname');
							var pincore_fulladdress = '<p>' + $(this).attr('pincore_fulladdress') + '</p>';
							var pin_status = $(this).attr('pin_status');
							var point = new google.maps.LatLng(parseFloat($(this).attr('pincore_lat')), parseFloat($(this).attr('pincore_lng')));
							create_marker(point, pin_firstname, pincore_fulladdress, false, false, false, "icons/pin_blue.png");
					});
			});
			google.maps.event.addListener(map, 'click', function(event) {
					var EditForm = '<p><div class="marker-edit">' +
							'<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker">' +
							'<label for="pPinStatus"><span>Status:</span> <select name="pPinStatus" class="save-type"><option value="Sold">SOLD</option><option value="Cancelled">Cancelled</option>' +
							'<option value="house">Rejected</option></select></label><br/>' +
							'<label for="pFullName"><span>Customer Name:</span><input type="text" name="pFullName" class="save-name" placeholder="Enter Title" maxlength="40" /></label>' +
							'<label for="pDesc"><span>Address :</span><textarea name="pDesc" class="save-desc" placeholder="Enter Address" maxlength="150"></textarea></label>' +
							'</form>' +
							'</div></p><button name="save-marker" class="save-marker">Save Marker</button>';
					create_marker(event.latLng, 'Add New Pin', EditForm, true, true, true, pinIcon);
			});
			markerClusterer = new MarkerClusterer(map, markers, {
					maxZoom: 15,
					gridSize: 4,
					styles: clusterer_styles
			});
			$('#refresh').click(function() {
					refreshMap()
			})
			$('#clear').click(function() {
					clearClusters()
			})
	}

	function create_marker(MapPos, MapTitle, MapDesc, InfoOpenDefault, DragAble, Removable, iconPath, mType) {
			var marker = new google.maps.Marker({
					position: MapPos,
					map: map,
					draggable: DragAble,
					animation: google.maps.Animation.DROP,
					icon: iconPath
			});
			markers.push(marker);
			console.log(markers)
			refreshMap()
			var contentString = $('<div class="marker-info-win">' +
					'<div class="marker-inner-win"><span class="info-content">' +
					'<h1 class="marker-heading">' + mType + '</h1>' +
					MapTitle +
					MapDesc +
					'</span><button name="remove-marker" class="remove-marker">Remove Marker</button>' +
					'</div></div>');
			var infowindow = new google.maps.InfoWindow();
			infowindow.setContent(contentString[0]);
			var removeBtn = contentString.find('button.remove-marker')[0];
			var saveBtn = contentString.find('button.save-marker')[0];
			google.maps.event.addDomListener(removeBtn, "click", function(event) {
					remove_marker(marker);
			});
			if (typeof saveBtn !== 'undefined') {
					//add click listner to save marker button
					google.maps.event.addDomListener(saveBtn, "click", function(event) {
							var mReplace = contentString.find('span.info-content');
							var mName = contentString.find('input.save-name')[0].value;
							var mDesc = contentString.find('textarea.save-desc')[0].value;
							var mType = contentString.find('select.save-type')[0].value;
							if (mName == '' || mDesc == '') {
									alert("Please enter the correct information to disposition a new pin!");
							} else {
									save_marker(marker, mName, mDesc, mType, mReplace);
							}
					});
			}
			infoWindows.push(infowindow)
			google.maps.event.addListener(marker, 'click', function() {
					for (var a in infoWindows) {
							infoWindows[a].close()
					}
					infowindow.open(map, marker);
			});
			if (InfoOpenDefault) {
					for (var a in infoWindows) {
							infoWindows[a].close()
					}
					infowindow.open(map, marker);
			}
	}

	function remove_marker(Marker) {
			if (Marker.getDraggable()) {
					Marker.setMap(null);
			} else {
					var mLatLang = Marker.getPosition().toUrlValue();
					var myData = {
							del: 'true',
							latlang: mLatLang
					};
					$.ajax({
							type: "POST",
							url: "map_process.php",
							data: myData,
							success: function(data) {
									Marker.setMap(null);
									alert(data);
							},
							error: function(xhr, ajaxOptions, thrownError) {
									alert(thrownError);
							}
					});
			}
	}

	function save_marker(Marker, mName, mAddress, mType, replaceWin) {
			var mLatLang = Marker.getPosition().toUrlValue();
			var myData = {
					pin_firstname: mName,
					pincore_fulladdress: mAddress,
					latlang: mLatLang,
					pin_status: mType
			};
			console.log(replaceWin);
			$.ajax({
					type: "POST",
					url: "map_process.php",
					data: myData,
					success: function(data) {
							replaceWin.html(data);
							Marker.setDraggable(false);
							Marker.setIcon('icons/pin_blue.png');
					},
					error: function(xhr, ajaxOptions, thrownError) {
							alert(thrownError);
					}
			});
	}
	$(document).ready(function() {
			map_initialize();
	});
	var clusterer_styles = [
			[{
					url: imageUrl,
					height: 35,
					width: 35,
					anchor: [16, 0],
					textColor: '#ff00ff',
					textSize: 10
			}, {
					url: imageUrl,
					height: 45,
					width: 45,
					anchor: [24, 0],
					textColor: '#ff0000',
					textSize: 11
			}, {
					url: imageUrl,
					height: 55,
					width: 55,
					anchor: [32, 0],
					textColor: '#ffffff',
					textSize: 12
			}],
			[{
					url: imageUrl,
					height: 27,
					width: 30,
					anchor: [3, 0],
					textColor: '#ff00ff',
					textSize: 10
			}, {
					url: imageUrl,
					height: 36,
					width: 40,
					anchor: [6, 0],
					textColor: '#ff0000',
					textSize: 11
			}, {
					url: imageUrl,
					width: 50,
					height: 45,
					anchor: [8, 0],
					textSize: 12
			}],
			[{
					url: imageUrl,
					height: 26,
					width: 30,
					anchor: [4, 0],
					textColor: '#ff00ff',
					textSize: 10
			}, {
					url: imageUrl,
					height: 35,
					width: 40,
					anchor: [8, 0],
					textColor: '#ff0000',
					textSize: 11
			}, {
					url: imageUrl,
					width: 50,
					height: 44,
					anchor: [12, 0],
					textSize: 12
			}]
	];
	var roadmap_styles = [{
			stylers: [{
					saturation: -100
			}]
	}, {
			featureType: "water",
			elementType: "geometry.fill",
			stylers: [{
					color: "#0099dd"
			}]
	}, {
			elementType: "labels",
			stylers: [{
					visibility: "off"
			}]
	}, {
			featureType: "poi.park",
			elementType: "geometry.fill",
			stylers: [{
					color: "#aadd55"
			}]
	}, {
			featureType: "road.highway",
			elementType: "labels",
			stylers: [{
					visibility: "on"
			}]
	}, {
			featureType: "road.arterial",
			elementType: "labels.text",
			stylers: [{
					visibility: "on"
			}]
	}, {
			featureType: "road.local",
			elementType: "labels.text",
			stylers: [{
					visibility: "on"
			}]
	}, {}]
&#13;
#map{
		width: 100%;
		height: 100%;
		background-color: #aaa;
	}
	html,
	body
	{
		height: 100%;
	}
	
	.button
	{
		width: 10rem;
		height: 3rem;
		background: #b5cdde;
		color: #fff;
		text-align: center;
		position: absolute;
		bottom: 1rem;
		right: 3vw;
		z-index: 50;
		line-height: 3rem;
		font-size: 20px;
		font-family: sans-serif;
		text-transform: uppercase;
		box-shadow: 1px 1px 2px #aac;
		cursor: pointer;
		border-radius: 3px;
		border: 2px solid darken(#b5cdde,10%);
	}
	.button:hover
	{
		background: darken(#b5cdde,10%)
	}
	.button:nth-child(2)
	{
		right: 13vw;
	}
	.marker-edit
	{
		width: 10vw;
	}
&#13;
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/1.0.2/src/markerclusterer.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<div id='map'></div>
<div class='button' id='refresh'>
  Refresh
</div>
<div class='button' id='clear'>
  Clear
</div>
&#13;
&#13;
&#13;