Upgrading dual map program from Google Maps apiV2 to apiV3 - google-maps-api-3

I have a Google map API V2 script allowing two maps of different sizes and zoom levels to move together, when one map is panned the other also moves to maintain the same center point. The smaller map has a Xhair in the center that returns to the center after it has been panned, the larger map has multiple markers.
I'm trying to upgrade the code to API V3, but the V3 maps aren't moving each other and the smaller map Xhair isn't functioning. Can someone please tell me what am I missing in the script upgrade from API V2 to API V3?
V2 code:
<script type="text/javascript">
//<![CDATA[
if (GBrowserIsCompatible()) {
function createMarker(point) {
map.addOverlay(new GMarker(point));
}
// ===== Setup The Maps =====
// Display the main map, with some controls and set the initial location
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(54.531283,-125.125537), 12);
// Set up three markers on the main map
createMarker(new GLatLng(54.207882,-125.661621));
createMarker(new GLatLng(49.214790,-124.054399));
createMarker(new GLatLng(49.053632,-122.352859));
// create the crosshair icon, which will indicate where we are on the minimap
// Lets not bother with a shadow
var Icon = new GIcon();
Icon.image = "xhair.png";
Icon.iconSize = new GSize(21, 21);
Icon.shadowSize = new GSize(0,0);
Icon.iconAnchor = new GPoint(11, 11);
Icon.infoWindowAnchor = new GPoint(11, 11);
Icon.infoShadowAnchor = new GPoint(11, 11);
// Create the minimap
var minimap = new GMap2(document.getElementById("minimap"));
minimap.setCenter(new GLatLng(54.531283,-125.125537), 7);
// Add the crosshair marker at the centre of the minimap and keep a reference to it
var xhair = new GMarker(minimap.getCenter(), Icon);
minimap.addOverlay(xhair);
// ====== Handle the Map movements ======
// Variables that log whether we are currently causing the maps to be moved
var map_moving = 0;
var minimap_moving = 0;
// This function handles what happens when the main map moves
// If we arent moving it (i.e. if the user is moving it) move the minimap to match
// and reposition the crosshair back to the centre
function Move(){
minimap_moving = true;
if (map_moving == false) {
minimap.setCenter(map.getCenter());
xhair.setPoint(map.getCenter());
xhair.redraw(true);
}
minimap_moving = false;
}
// This function handles what happens when the mini map moves
// If we arent moving it (i.e. if the user is moving it) move the main map to match
// and reposition the crosshair back to the centre
function MMove(){
map_moving = true;
if (minimap_moving == false) {
map.setCenter(minimap.getCenter());
xhair.setPoint(minimap.getCenter());
xhair.redraw(true);
}
map_moving = false;
}
// Listen for when the user moves either map
GEvent.addListener(map, 'move', Move);
GEvent.addListener(minimap, 'moveend', MMove);
}
// display a warning if the browser was not compatible
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
Non-working V3 code:
<script type="text/javascript">
function createMarker(point) {
map.addOverlay(new google.maps.Marker(point));
}
// ===== Setup The Maps =====
// Display the main map, with some controls and set the initial location function initialize() {
var map = new google.maps.Map(
document.getElementById('map'), {
center: new google.maps.LatLng(54.531283,-125.125537),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Set up three markers on the main map
var marker = new google.maps.Marker({
position: new google.maps.LatLng(54.207882,-125.661621),
map: map
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(49.214790,-124.054399),
map: map
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(49.053632,-122.352859),
map: map
});
// create the crosshair icon, which will indicate where we are on the minimap
// Lets not bother with a shadow
var Icon = new google.maps.MarkerImage();
Icon.image = "xhair.png";
Icon.iconSize = new google.maps.Size(21, 21);
Icon.shadowSize = new google.maps.Size(0,0);
Icon.iconAnchor = new google.maps.Point(11, 11);
Icon.infoWindowAnchor = new google.maps.Point(11, 11);
Icon.infoShadowAnchor = new google.maps.Point(11, 11);
// Create the minimap
var minimap = new google.maps.Map(
document.getElementById('minimap'), {
center: new google.maps.LatLng(54.531283,-125.125537),
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Add the crosshair marker at the centre of the minimap and keep a reference to it
var xhair = new google.maps.Marker(minimap.getCenter(), Icon);
minimap.addOverlay(xhair);
// ====== Handle the Map movements ======
// Variables that log whether we are currently causing the maps to be moved
var map_moving = 0;
var minimap_moving = 0;
// This function handles what happens when the main map moves
// If we arent moving it (i.e. if the user is moving it) move the minimap to match
// and reposition the crosshair back to the centre
function Move(){
minimap_moving = true;
if (map_moving == false) {
minimap.setCenter(map.getCenter());
xhair.setPoint(map.getCenter());
xhair.redraw(true);
}
minimap_moving = false;
}
// This function handles what happens when the mini map moves
// If we arent moving it (i.e. if the user is moving it) move the main map to match
// and reposition the crosshair back to the centre
function MMove(){
map_moving = true;
if (minimap_moving == false) {
map.setCenter(minimap.getCenter());
xhair.setPoint(minimap.getCenter());
xhair.redraw(true);
}
map_moving = false;
}
// Listen for when the user moves either map
google.maps.event.addListener(map, 'move', Move);
google.maps.event.addListener(minimap, 'moveend', MMove);
// google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, 'load', initialize);

The upgrade guide seems to have little information on Events, some obsolete events don't seem to be listed in the obsolete code. The V2 events: "move" and "moveend" are apparently not supported in V3, however there are similar (but not the same) V3 events; dragstart, drag, dragend, and center_changed. Since the drag events aren't compatable with additional selection buttons I'm using: I went with center_changed which works like a charm for my application.
I explored a few options for the center cross hair, but they seemed to have dead spots or jumped around when the maps were panned, so I eliminated the javascript solutions and went with a simple solution from Drew Noakes.
This is what I came up with to fix the non-working V3 code, might help someone out there.
V3 code:
<script type="text/javascript">
// ===== Setup The Maps =====
// Display the main map and set the initial location
var map = new google.maps.Map(
document.getElementById('map'), {
center: new google.maps.LatLng(54.531283,-125.125537),
zoom: 12,
zoomControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Set up the three markers on the main map
var marker = new google.maps.Marker({
position: new google.maps.LatLng(54.207882,-125.661621),
map: map
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(49.214790,-124.054399),
map: map
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(49.053632,-122.352859),
map: map
});
// Create the minimap
var minimap = new google.maps.Map(
document.getElementById('minimap'), {
center: new google.maps.LatLng(54.531283,-125.125537),
zoom: 7,
zoomControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Add the crosshair marker at the centre of the minimap using html and CSS
// ====== Handle the Map movements ======
// Variables that log whether we are currently causing the maps to be moved
var map_moving = 0;
var minimap_moving = 0;
// This function handles what happens when the main map moves
// If we arent moving it (i.e. if the user is moving it) move the minimap to match
google.maps.event.addListener(map, 'center_changed', function(){
minimap_moving = true;
if (map_moving == false) {
minimap.setCenter(map.getCenter());
}
minimap_moving = false;
})
// This function handles what happens when the mini map moves
// If we arent moving it (i.e. if the user is moving it) move the main map to match
google.maps.event.addListener(minimap, 'center_changed', function(){
map_moving = true;
if (minimap_moving == false) {
map.setCenter(minimap.getCenter());
}
map_moving = false;
})
// google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, 'load', initialize);
</script>
//The HTML:
<div id="map" style="width:627px; height: 627px"></div>
<div id="container">
<div id="minimap" style="width:370px; height:370px;"></div>
<div id="xhair"><img src="../images/xhair.png" width="20" height="20" /></div>
</div>
//The CSS:
#container { position:relative; }
#map { height:100%; width:100%; }
#xhair {
position:absolute;
left:47%;
top:47%;
}

Related

Google map showing only some markers but all markers shown in debug mode

A few of my markers are not showing in the map I created and I have drilled down the reason being too many API calls. But the problem is that even after adding setTimout/ delay code all markers are not shown. When i debug the code in chrome though it works fine (even when i remove all the break points and allow the website to load - all markers are loaded without any issues)
www.khojiye.com is the link
function map_marker(ajax_result,address_length)
{
val = ajax_result[counter];
if($.trim(val)!=""){
//alert(i);
//alert(val);
var valA = val.split('###');
setTimeout(geocoder.geocode( { 'address': valA[0]}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK)
{
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
// Set the coordonates of the new point
var latLng = new google.maps.LatLng(lat, lng);
//bounds.extend(latLng);
var marker = new google.maps.Marker(
{
position: latLng,
map: map,
title: valA[0],
animation: google.maps.Animation.DROP,
icon:valA[1]
});
// The HTML that is shown in the window of each item (when the icon it's clicked)
var html = "<div style='width:150px; margin-top: -12px;'><h3 style='font-size:16px; font-weight:500;'>"+valA[2]+"</h3><h4 style='font-size:15px; line-height:21px;'>"+valA[0]+"</h4><a href='"+valA[3]+"'>View Detail</h4></div>";
// Binds the infoWindow to the point
bindInfoWindow(marker, map, infoWindow, html);
// Add the marker to the array
markers.push(marker);
counter++;
a_c++;
if(counter<address_length)
map_marker(ajax_result,address_length);
}
else{
//alert("Geocode was not successful for the following reason: " + status);
//marker = '';
//markers.push(marker);
//console.log(status);
counter++;
b_c++;
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT){
counter--;
console.log(counter);
delay=delay*5;
}
if(counter<address_length)
map_marker(ajax_result,address_length);
}
}),delay);
}
}
I dont know what i did is a hack or not:
1. it seems my use of set timeout was incorrect
2. I removed the setTimeout from top function and added it as
setTimeout(function() {map_marker(ajax_result,address_length);},delay);}

Google map API geolocation after first display of the map

This code takes a big list of (400) markers and adds it to the map, at the end, it shows the whole map including all the markers.
What I have tried to achieve is: when geolocation is available, center the map on location, zoom to level 16 and refresh the map to show it, otherwise, let the whole big map show... I have read and tried many different things, but the geolocation must happen before the map is created. I want to make it happen after. I show you my code here and the temporary link to the working site: http://studioteknik.co/brasseursillimites.com/detaillants/
function initialize()
{
var map = new google.maps.Map(document.getElementById('map-canvas'));
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (var i in locations) {
var p = locations[i];
var latlng = new google.maps.LatLng(p[1], p[2]);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: p[0]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.title);
infowindow.open(map, this);
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
Here is a simple example of geolocation. Just add the geolocation code anywhere after the map object is created. If the user doesn't allow geolocation, the map will be shown at the default location / zoom level.
function initialize() {
var mapOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(0,0)
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// Geolocation code
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
map.setZoom(16);
});
}
}
initialize();
JSFiddle demo

Count and output number of markers bound by circle radius

I have a map thats populated with markers of places from a fusion table. I'm taking the users location and displaying a circle of radius 10 miles from their location. Here is my code - http://connormccarra.com/sandbox/map/. How can I use the api to count the number of markers bound by the circle and output that number in the footer?
Cheers!
Relevant code:
var map;
function Initialize() {
var MapOptions = {
zoom: 7,
center: new google.maps.LatLng(53.4125694, -8.245014),
mapTypeId: google.maps.MapTypeId.ROADMAP,
sensor: true
};
map = new google.maps.Map(document.getElementById("map_canvas"), MapOptions);
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'Address',
from: '1OPU6utSjRYwJSFK-EXdaGmt2KgLTq2loVIjS3AA'
}
});
layer.setMap(map);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
map: map,
position: pos,
content: 'You are here!'
});
// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
map: map,
radius: 16093, // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var count = mgr.getMarkerCount(circle);
document.getElementById("Address").innerHTML += count + "<BR>";
google.maps.event.addDomListener(window, 'load', initialize);
//Maps API loaded, now load customizations
var element = document.createElement('script');
element.src = 'template.js';
element.type = 'text/javascript';
var scripts = document.getElementsByTagName('script')[0];
scripts.parentNode.insertBefore(element, scripts);
}
The markers created by a FusionTableLayer are not real markers, there is no way to get them as a kind of list to filter them(you can't get any details for the markers, except you click them).
But you may request the FusionTableAPI with a spatial condition(via AJAX, jsonp is supported).
The syntax for the query:
SELECT COUNT() from tableId
WHERE ST_INTERSECTS('Address',CIRCLE(LATLNG(lat,lng),10000))
How to send a query : https://developers.google.com/fusiontables/docs/v1/sql-reference
Demo(using data of another FusionTable because your table is protected):
http://jsfiddle.net/doktormolle/bAtgf/
Simplest way: use the geometry library computeDistanceBetween method. If the distance from the user's location is less than 10 miles, the marker is in the circle.
I suggest you first fetch all the coordinates of your FusionTablesLayer.
Here is an example which was used in the sidebar
http://www.geocodezip.com/v3_FusionTables_AfricaMap_kml_sidebar.html
Then using a loop statement you can use the computeDistanceBetween function.
Detect If Marker is Within Circle Overlay

google maps API v3 - zoom after load How

I am trying to get google maps to load, then zoom into my marker, but I have something wrong with my javascript, as the scope of the map is not visible, despite it being defined globally.
Any ideas what I am doing wrong ?
Many thanks
Mark
<!DOCTYPE html>
<html>
<head>
<title>Geolocation</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script src="js/jquery-1.10.1.min.js"></script>
<link href="css/default.css" rel="stylesheet">
<!--
Include the maps javascript with sensor=true because this code is using a
sensor (a GPS locator) to determine the user's location.
See: https://developers.google.com/apis/maps/documentation/javascript/basics#SpecifyingSensor
-->
<script src="https://maps.googleapis.com/maps/api/js?v=3.12&sensor=true"></script>
<script>
//START Global Variables
var geocoder;
var map;
var marker;
var initialZoomLevel = 7;
var endZoomLevel = 16;
var zoomTimeInterval_ms = 1000;
var mapIcon = {
url: "images/im_here.png",
// This marker is 130 pixels wide by 120 pixels tall
size: new google.maps.Size(130,120),
//scale image so it works with retina displays
scaledSize: new google.maps.Size(65,60),
// The origin for this image is 0,0.
origin: new google.maps.Point(0,0),
// The anchor point is be middle of the base
anchor: new google.maps.Point(32.5,60)
};
var mapIcon_shadow = {
url: "images/im_here_shadow.png",
// This shadow is 191 pixels wide by 120 pixels tall
size: new google.maps.Size(191,120),
//scale image so it works with retina displays
scaledSize: new google.maps.Size(95.5,60),
// The origin for this image is 0,0.
origin: new google.maps.Point(0,0),
// The anchor point is be middle of the base
anchor: new google.maps.Point(32.5,60)
};
//Enable the visual refresh
google.maps.visualRefresh = true;
//END Global Variables
/** Initialise function to render the map */
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: initialZoomLevel,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
panControl: false,
streetViewControl: false,
zoomControl: false
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
// set home location
home = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
// the marker where you are
marker = new google.maps.Marker({
map: map,
position: pos,
icon: mapIcon,
shadow: mapIcon_shadow,
draggable: true
});
codeLatLng(pos);
map.panTo(pos);
google.maps.event.addListener(marker, 'dragend', function(a) {
//alert('LatLng is '+a.latLng.lat()+ " "+ a.latLng.lng());
codeLatLng(a.latLng);
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
// Create the DIV to hold the control and
// call the HomeControl() constructor passing
// in this DIV.
//var homeControlDiv = document.createElement('div');
//var homeControl = new HomeControl(homeControlDiv, map);
//homeControlDiv.index = 1;
//map.controls[google.maps.ControlPosition.TOP_CENTER].push(homeControlDiv);
smoothZoom(map, endZoomLevel, map.getZoom()); // call smoothZoom, parameters map, final zoomLevel, and starting zoom level
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function codeLatLng(markerLatLang) {
//var latlng = new google.maps.LatLng(latLng.lat(), latLng.lng());
geocoder.geocode({'latLng': markerLatLang}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
name = results[0].formatted_address;
latlongStr = "LAT = ["+markerLatLang.lat()+"] LNG = ["+markerLatLang.lng()+"]";
//alert("name = "+name);
$('#address').html(name);
$('#latlong').html(latlongStr);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
/**
* The HomeControl adds a control to the map that simply
* returns the user to home. This constructor takes
* the control DIV as an argument.
* #constructor
*/
/** TODO need to rewite this as normal div, not on map **/
function HomeControl(controlDiv, map) {
// Set CSS styles for the DIV containing the control
// Setting padding to 5 px will offset the control
// from the edge of the map
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to set the map to Start Location';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('div');
controlText.style.fontFamily = 'Helvetica,sans-serif';
controlText.style.fontSize = '16px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.style.zIndex = "100";
controlText.innerHTML = '<b>Reset Map</b>';
controlUI.appendChild(controlText);
// Setup the click event listeners: simply set the map back to home
google.maps.event.addDomListener(controlUI, 'click', function() {
marker.setPosition(home);
map.setCenter(home);
});
}
// the smooth zoom function
function smoothZoom (map, max, cnt) {
if (cnt >= max) {
return;
}
else {
z = google.maps.event.addListener(map, 'zoom_changed', function(event){
google.maps.event.removeListener(z);
self.smoothZoom(map, max, cnt + 1);
});
setTimeout(function(){map.setZoom(cnt)}, zoomTimeInterval_ms);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<div id="latlong">No latlong Yet</div>
<div id="address">No Address Yet</div>
</div>
<div id="map-canvas"></div>
</body>
</html>
The fact that your map is defined globally isn't relevant if you don't wait until it is initialized before using it.
It is initialized by the initialize function which runs on the body onload event. You use it inline before that happens. This works for me:
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: initialZoomLevel,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
panControl: false,
streetViewControl: false,
zoomControl: false
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
google.maps.event.addListenerOnce(map,"zoom_changed", function() {
smoothZoom(map, endZoomLevel, map.getZoom()); // call smoothZoom, parameters map, final zoomLevel, and starting zoom level
});
working example
seems the zoom_changed event doesn't fire when the map initializes, using the "idle" event seems to work:
working example with zoom on idle

Any change in zoom level causes all my markers to re-appear on my Google map

Any change in zoom level causes all markers to appear on the map that have been on the map at any time since the last page load. This is true whether the zoom level change is due to a setZoom() call in my code or because I operate the zoom slider.
I have a map control widget with buttons to add markers that correspond to different categories. So you click the button for Groups and the map populates with markers that represent Groups. Then you click on the Individuals button and the Groups markers are cleared and deleted and the Individual markers appear on the map. And so on with other categories. But any change in zoom level brings back any markers that have been on the map since the page was last refreshed.
I'm using MarkerClustererPlus. I don't know whether this would be a bug in MarkerClustererPlus, in Google's code or in my code. Hopefully the latter. I'll include my addMarkers function below. Since I both clear and delete the markers before adding new markers, I don't know how it's possible for the previous markers to come back, nevermind why a zoom change trigger their return:
function addMarkers(map,flag) {
clearOverlays();
deleteOverlays();
if ('event' == flag) {
data = himaps_event_data;
} else if ('story' == flag) {
data = himaps_story_data;
} else if ('group' == flag) {
data = himaps_group_data;
} else {
data = himaps_user_data;
}
for (var k in data) {
var item = data[k];
var latLng = new google.maps.LatLng(item.lat, item.lng);
var marker = new google.maps.Marker({'position': latLng});
markersArray.push(marker);
}
var markerCluster = new MarkerClusterer(map, markersArray);
}
Also, if I change zoom, then the markers don't clear anymore. They just continue to accumulate on the map if I click the buttons to change category. That definitely doesn't happen if I don't change the zoom level.
By request, here's more of the code:
function clearOverlays() {
if (markersArray) {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
}
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
/* map controls */
(function($) {
Drupal.behaviors.himaps = {
attach: function(context, settings) {
$('.map-controls button').click(function() {
flag = this.id.replace('map-','');
addMarkers(map,flag);
});
}
}
})(jQuery);
/* homepage map */
function newMap(clat,clng) {
if (!clat) {
clat = 37.65;
}
if (!clng) {
clng = -97.43;
}
var myOptions = {
scrollwheel: false,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.LEFT_CENTER
},
panControl: false,
panControlOptions: {
position: google.maps.ControlPosition.LEFT_CENTER
},
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.LEFT_CENTER
},
draggable: true,
center: new google.maps.LatLng(clat, clng),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
return new google.maps.Map(document.getElementById("map-canvas"), myOptions);
}
var map;
var markersArray = [];
var geocoder;
var marker;
var listener;
google.maps.event.addDomListener(window, 'load', initmapping);
function initmapping() { //aka initialize()
map = newMap();
addMarkers(map,'group');
geocoder = new google.maps.Geocoder();
}
Last but not least, here is the MarkerClustererPlus library: http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclustererplus/2.0.9/src/
I don't know much about MarkerClusterer but what appears to be happening is every time you call your addMarkers function you are creating a new MarkerClusterer but the old one is never destroyed/removed, hence on zoom change all instances you have created redraw the markers they have. Try the clearMarkers or removerMarkers method of MarkerClusterer and also only create one instance of MarkerClusterer and reuse it instead of creating a new one each time you cal addMarkers.

Resources