MarkerClusterer not show on map - google-maps

Hi I try to add markerclusterer to my google map but I certainly miss something because the markers are on the map but I can't see the clusters...
here is my script :
//<![CDATA[
function initialize() {
var cluster = [];
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(<?php echo get_post_meta($find_CODGEO, 'latitude', true); ?>, <?php echo get_post_meta($find_CODGEO, 'longitude', true); ?>),
zoom: 14,
mapTypeId: 'roadmap'
});
var mcOptions = {gridSize: 10, maxZoom: 15};
var infoWindow = new google.maps.InfoWindow;
downloadUrl("/wp-content/themes/codium-extend/search/search_equipements.php?lat=<?php echo get_post_meta($find_CODGEO, 'latitude', true); ?>&lng=<?php echo get_post_meta($find_CODGEO, 'longitude', true); ?>&type=<?php echo $thematiquematch ; ?>&codgeo=<?php echo $CODGEO ; ?>&radius=50", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("sous_type");
var type = markers[i].getAttribute("sous_type_img");
var offsetLat = markers[i].getAttribute("lat");
var offsetLng = markers[i].getAttribute("lng");
var point = new google.maps.LatLng(offsetLat, offsetLng);
var html = "<b>" + name + "</b> <br/>" + address;
var icon = 'http://images.commune-mairie.fr/maps/' + type + '.png';
var marker = new google.maps.Marker({
map: map,
position: point,
icon: 'http://images.commune-mairie.fr/maps/' + type + '.png',
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(markers[i].getAttribute("name"));
infowindow.open(map, marker);
}
})(marker, i));
cluster.push(marker);
}
var mc = new MarkerClusterer(map,cluster,mcOptions);
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
A live example here http://www.commune-mairie.fr/equipements/lyon-69123/ thanks for your help!

You do this in your loop:
bindInfoWindow(marker, map, infoWindow, html);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(markers[i].getAttribute("name"));
infowindow.open(map, marker);
}
})(marker, i));
but then your bindInfoWindow function looks like this:
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
So you're duplicating your marker click event listener. I'm not sure this would cause the problem with the MarkerClusterer, but you should tidy it up anyway.

Related

Google API to map nearby properties in Salesforce

I asked this question originally in the Salesforce StackExchange, but was redirected here, since it's more of a Google API question than a Salesforce question.
Right now I have the following code, which creates a marker at the location of the property on a visualforce page that has an embedded Google Map. When the user clicks on the marker, an info window appears with information on the property.
<apex:page standardController="Property__c">
<head>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});
</script>
<style>
#map {
font-family: Arial;
font-size: 12px;
line-height: normal !important;
height: 800px;
background: transparent;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</apex:page>
This is working just fine. But I am trying to modify it to also show properties nearby to this property. I have gotten as far as using an SOQL query to find these properties, pass their addresses into an array, geocode these addresses and set a marker at each geocoordinate. All of that works just swell.
Where I've been stuck, is in displaying the infowindow that appears when the user clicks one of these markers. Not only can I not create an infowindow for the NEW markers, but the infowindow for the OLD "main" marker is breaking as well. In fact, even if I comment the infowindow and listener events for the new markers, the original is still broken. These infowindows need to display different information than the infowindow for the "main" marker. Here is my modified code:
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var marker2;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
//several markers
//Get Geos
var geos = [];
var idy = 0; <
apex: repeat value = "{!getgeoList}"
var = "m" >
geos[idy++] = "{!m}"; <
/apex:repeat>
for (var i = 0; i < geos.length; ++i) {
console.log('geo' + geos[i] + 'out of' + geos.length);
geocodeAddress(geos[i]);
}
function geocodeAddress(location) {
geocoder.geocode({
'address': location
}, function(results, status) {
// alert(status);
if (status == google.maps.GeocoderStatus.OK) {
// alert(results[0].geometry.location+location);
createMarker(results[0].geometry.location, location);
} else {
alert("some problem in geocode" + status);
}
});
}
function createMarker(latlng, html) {
marker2 = new google.maps.Marker({
position: latlng,
map: map
});
addIinfo(marker2, html);
}
function addInfo(marker2, html) {
var infowindow2 = new google.maps.InfoWindow({
content: html
});
marker2.addListener(marker2, 'click', function() {
infowindow2.open(marker2.get('map'), marker2);
});
}
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});
I changed marker2.addListener to google.maps.event.addListener. This worked, except that my original marker was showing the same information as the marker2 markers. When I changed the marker2 icon to blue, I realized that this was because it was putting a marker2 marker over the original marker. So I changed i = 0 to i=1 in my for loop, and now my code works just great! :)
Here is my new code:
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var marker2;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
//several markers
//Get Geos
var geos = [];
var idy=0;
<apex:repeat value="{!getgeoList}" var="m">
geos[idy++]="{!m}";
</apex:repeat>
for (var i = 1; i < geos.length; ++i) {
console.log('geo' + geos[i] + 'out of' + geos.length);
geocodeAddress(geos[i]);
}
function geocodeAddress(location) {
geocoder.geocode({
'address': location
}, function(results, status) {
// alert(status);
if (status == google.maps.GeocoderStatus.OK) {
// alert(results[0].geometry.location+location);
createMarker(results[0].geometry.location, location);
} else {
alert("some problem in geocode" + status);
}
});
}
function createMarker(latlng, html) {
marker2 = new google.maps.Marker({
position: latlng,
map: map,
icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
addInfo(marker2,html);
}
function addInfo(marker2,html) {
var infowindow2 = new google.maps.InfoWindow({
content: html });
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map, marker2);
});
}
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});

Google Maps 2 InfoWindows Auto-Opening infoWindow, 1 infoWindow after click

I have an auto-opening infoWindow.
I wish only two were opened automatically, while one did not. The effect Just like in the pictures.
My Code:
<script>
function initialize() {
var openedInfoWindow = [];
var locations = [
['Oddział', 52.846190, 17.723237, 3],
['Oddział', 52.812224, 17.201023, 2],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1]
];
var cityCircle;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2], locations[i][3]),
map: map,
content: locations[i][0]
});
bounds.extend(marker.position);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i, infowindow) {
return function () {
if(openedInfoWindow[i] != null){
openedInfoWindow[i].close();
openedInfoWindow[i] = null;
}else{
infowindow.setContent(this.content);
infowindow.open(map, this);
openedInfoWindow[i] = infowindow;
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow[i] = null;
});
}
}
})(marker, i, infowindow));
google.maps.event.trigger(marker, 'click');
}
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(9);
google.maps.event.removeListener(listener);
});
}
function loadScript() {
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyADTnbl7e9y2o13cXkUFO8RZpXFJI-yzp4&' + 'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>`
Picture 1 = so now
Picture 2 = so it has to be
I would suggest you generalize it, add a member to your array to determine whether to open the marker or not.
var locations = [
// IW content, lat, lng, nowrap, open IW
['Oddział', 52.846190, 17.723237, 3, true],
['Oddział', 52.812224, 17.201023, 2, true],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1, false]
];
Then do this to open the infowindow:
if (locations[i][4]) {
google.maps.event.trigger(marker, 'click');
}
proof of concept fiddle
code snippet:
function initialize() {
var openedInfoWindow = [];
var locations = [
['Oddział', 52.846190, 17.723237, 3, false],
['Oddział', 52.812224, 17.201023, 2, true],
['Zakład Poligraficzny - Siedziba', 52.847942, 17.757889, 1, true]
];
var cityCircle;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2], locations[i][3]),
map: map,
content: locations[i][0]
});
bounds.extend(marker.position);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function(marker, i, infowindow) {
return function() {
if (openedInfoWindow[i] != null) {
openedInfoWindow[i].close();
openedInfoWindow[i] = null;
} else {
infowindow.setContent(this.content);
infowindow.open(map, this);
openedInfoWindow[i] = infowindow;
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow[i] = null;
});
}
}
})(marker, i, infowindow));
if (locations[i][4]) {
google.maps.event.trigger(marker, 'click');
}
}
map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() {
map.setZoom(9);
google.maps.event.removeListener(listener);
});
}
function loadScript() {
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?' + 'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
html,
body,
#map-canvas {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

Make geocoding map zoom on scroll

I am looking at two different geocode examples I found and I am looking to get the best of both features. I have not had much experience with geocoding and I find the google docs hard to follow
This one does everything I want except scroll in when the user uses the mouse wheel. http://jsfiddle.net/Ep7Rr/
I would like this one if I could get the marker to move as the user drags the map like in the first one.http://jsfiddle.net/AjeTc/
I know there are different ways such as new GMap2 and new google.maps.Geocoder
The first one works with this code
<script>
function load() {
if (GBrowserIsCompatible()){
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
var center = new GLatLng(54.18173, -6.35284);
map.setCenter(center, 15);
geocoder = new GClientGeocoder();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(5);
document.getElementById("lng").innerHTML = center.lng().toFixed(5);
GEvent.addListener(marker, "dragend", function(){
var point = marker.getPoint();
map.panTo(point);
document.getElementById("lat").innerHTML = point.lat().toFixed(5);
document.getElementById("lng").innerHTML = point.lng().toFixed(5);
}); /*END GEvent.addListener(marker, "dragend", function(){*/
GEvent.addListener(map, "moveend", function() {
map.clearOverlays();
var center = map.getCenter();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(5);
document.getElementById("lng").innerHTML = center.lng().toFixed(5);
GEvent.addListener(marker, "dragend", function() {
var point =marker.getPoint();
map.panTo(point);
document.getElementById("lat").innerHTML = point.lat().toFixed(5);
document.getElementById("lng").innerHTML = point.lng().toFixed(5);
}); /*END GEvent.addListener(marker, "dragend", function() {*/
}); /*END GEvent.addListener(map, "moveend", function() {*/
} /*END if (GBrowserIsCompatible()){*/
} /*END function load*/
And the second uses this
<script type="text/javascript">
function showAddress() {
var map = new GMap2(document.getElementById("map"));
var address = document.getElementById('fullAddress').value;
return false;
} /*END function showAddress*/
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(54.18173, -6.35284);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Catch the event when the map is dragged.
Update the position of the marker by getting the map center
Geocode the position of the marker
google.maps.event.addListener(map, 'dragend', function() {
updateMarkerStatus('Drag ended');
marker.setPosition(map.getCenter());
geocodePosition(marker.getPosition());
});
like this : http://jsfiddle.net/ZYV9N/

Refresh DownloadUrl on google map v3 and remove old markers

Hi I had a script and a xml file with 10.000 markers in it. I use markercluster to display the markers, but in order to fill the mobile browsers requierement I must begin the map at a certain zoom level (not to display to many markers). So I want to dynamically load the markers when the user change the zoom or viewport.
Here is my script. I thing I can't get the lat and lng of the LatLngBounds of the current viewport :
var customIcons = {
chambrehote: {
icon: '/wp-content/themes/codium-extend/images/chambre.png',
shadow: '/wp-content/themes/codium-extend/images/icon-shadow.png'
}
};
function initialize() {
var cluster = [];
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng('45.7676067','4.8351733'),
scrollwheel: false,
zoom: 12,
mapTypeId: 'roadmap'
});
var mcOptions = {gridSize: 100, styles: [
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m1.png",
width: 90
},
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m2.png",
width: 90
},
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m3.png",
width: 90
}
]};
var infoWindow = new google.maps.InfoWindow;
var bounds = new google.maps.LatLngBounds();
var swPoint = bounds.getSouthWest();
var nePoint = bounds.getNorthEast();
var swLat = swPoint.lat();
var swLng = swPoint.lng();
var neLat = nePoint.lat();
var neLng = nePoint.lng();
downloadUrl("/wp-content/themes/codium-extend/search/search_chambres.php?&type=chambrehote&codgeo=<?php echo $CODGEO ; ?>&radius=200&lat1="+swLat+"&lng1="+swLng+"&lat2="+neLat+"&lng2="+neLng+"", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("ville");
var slug = markers[i].getAttribute("slug");
var stars = markers[i].getAttribute("stars");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> " + "<br/>" + "" + "><a href=" + "/chambre-d-hote/" + slug + "/>lien vers la fiche</a>";
var icon = customIcons[type] || {};
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
//bounds.extend(point);
//map.fitBounds(bounds);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() { infowindow.setContent(markers[i].getAttribute("name"));
infowindow.open(map, marker);
}
})(marker, i));
cluster.push(marker);
}
var mc = new MarkerClusterer(map,cluster,mcOptions);
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
function changePosition() {
var position = document.getElementById('position').value;
adUnit.setPosition(google.maps.ControlPosition[position]);
}
First point :
I think I couldn't get the value of swLat, swLng... for passing them to downloadUrl
And second point I certainly miss a listener somewhere but don't know where !
Thanks for your inputs
---- EDIT ----
Right now I can load dynamically the data when the idle is changed, but (there is a but) now each change a new marker is add even if it's already on the map. Is there a way to clean all the markers when the idle change before loading the new ones?
var cluster = [];
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: new google.maps.LatLng('45.7676067','4.8351733'),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var mcOptions = {gridSize: 100, styles: [
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m1.png",
width: 90
},
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m2.png",
width: 90
},
{
textColor: 'black',
height: 80,
url: "/wp-content/themes/codium-extend/images/cluster-m3.png",
width: 90
}
]};
var infoWindow = new google.maps.InfoWindow;
google.maps.event.addListener(map, 'idle', function() {
var bounds = map.getBounds();
var swPoint = bounds.getSouthWest();
var nePoint = bounds.getNorthEast();
var swLat = swPoint.lat();
var swLng = swPoint.lng();
var neLat = nePoint.lat();
var neLng = nePoint.lng();
// alert(swLng);
downloadUrl("/wp-content/themes/codium-extend/search/search_chambres.php?lat=45.7676067&lng=4.8351733&type=chambrehote&codgeo=<?php echo $CODGEO ; ?>&radius=2000&lat1="+swLat+"&lng1="+swLng+"&lat2="+neLat+"&lng2="+neLng+"", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("ville");
var slug = markers[i].getAttribute("slug");
var stars = markers[i].getAttribute("stars");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> " + "<br/>" + "" + "><a href=" + "/chambre-d-hote/" + slug + "/>lien vers la fiche</a>";
var icon = customIcons[type] || {};
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
//bounds.extend(point);
//map.fitBounds(bounds);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(markers[i].getAttribute("name"));
infowindow.open(map, marker);
}
})(marker, i));
cluster.push(marker);
}
var mc = new MarkerClusterer(map,cluster,mcOptions);
});
});
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
function changeFormat() {
var format = document.getElementById('format').value;
adUnit.setFormat(google.maps.adsense.AdFormat[format]);
}
function changePosition() {
var position = document.getElementById('position').value;
adUnit.setPosition(google.maps.ControlPosition[position]);
}

Trouble clearing overlay when i reload a new set of markers in gmaps

I have a gmap and I only want to display markers in the viewable area. I have added a listener to get the bounds of the map and call gather the markers within the bounds. the problem is that when i bounds change, i want to clear the map and reload with the updated markers. currently the map will just continue to reload the markers on top of each other which makes the map extremely slow. I have tried:
google.maps.event.addListener(map, 'bounds_changed', function () {
clearOverlays();
loadMapFromCurrentBounds(map);
});
And that will not load any markers at all. I have also tried:
function loadMapFromCurrentBounds(map) {
clearOverlays();
And this will not load any markers either. Below is the code that will load all markers and functions as i want it to with the exception of clearing the old markers when the bounds change.
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap'
});
google.maps.event.addListener(map, 'bounds_changed', function () {
loadMapFromCurrentBounds(map);
});
}
function clearOverlays() {
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
}
}
function loadMapFromCurrentBounds(map) {
clearOverlays();
var infoWindow = new google.maps.InfoWindow;
var bounds = map.getBounds(); // First, determine the map bounds
var swPoint = bounds.getSouthWest(); // Then the points
var nePoint = bounds.getNorthEast();
// Change this depending on the name of your PHP file
var searchUrl = 'Viewport_Search.php?west=' + swPoint.lat() + '&east=' + nePoint.lat() + '&south=' + swPoint.lng() + '&north=' + nePoint.lng();
downloadUrl(searchUrl, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: point,
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
Please help... I have been beating my head against the computer all night researching and trying to figure this out. Feel free to email and/or ask for any questions.
You cant remove all markers, but it is possible to setMap to null on every visible marker.
I am doing it like that
add markers array to map object
add clearAllMarkers function to map object
every marker is added to the map is also added to markers array
clearAllMarkers function is something like that:
for (var idx=0;idx<=map.markers.length;idx++){
map.markers[idx].setMap(null);
}
I belive you are adding separate markers object to you're markers array. You're markers array should be full of markers references!!!
var map = []; //elrado's code
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap'
});
map.markers = [];//elrado's code (add narkers.array to map object)
google.maps.event.addListener(map, 'bounds_changed', function () {
loadMapFromCurrentBounds(map);
});
}
function clearOverlays() {
if (map.markers) {
for (i in map.markers) { //Might be you'll need to use map.markers.length
markers[i].setMap(null);
}
map.markers = [];//reinit map.markers.array
}
}
function loadMapFromCurrentBounds(map) {
clearOverlays();
var infoWindow = new google.maps.InfoWindow;
var bounds = map.getBounds(); // First, determine the map bounds
var swPoint = bounds.getSouthWest(); // Then the points
var nePoint = bounds.getNorthEast();
// Change this depending on the name of your PHP file
var searchUrl = 'Viewport_Search.php?west=' + swPoint.lat() + '&east=' + nePoint.lat() + '&south=' + swPoint.lng() + '&north=' + nePoint.lng();
downloadUrl(searchUrl, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: point,
});
map.markers.push(marker);//elrado's code
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
I have to warn you that this was written from the head (no test), but something like that should work. Basicly you are setting setMap(null) on separate markers not on objects you're showing on the map.
Below is the complete code solution to the problem.. Thanks for your help.
var map; //elrado's code
var markersArray = []; //elrados's code create array for markers
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(33.553029,-112.054017),
zoom: 13,
mapTypeId: 'roadmap'
});
google.maps.event.addListener(map, 'tilesloaded', function () {
clearOverlays()
loadMapFromCurrentBounds(map);
});
}
function clearOverlays() { //clear overlays function
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
function loadMapFromCurrentBounds(map) {
var infoWindow = new google.maps.InfoWindow;
var bounds = map.getBounds(); // First, determine the map bounds
var swPoint = bounds.getSouthWest(); // Then the points
var nePoint = bounds.getNorthEast();
// Change this depending on the name of your PHP file
var searchUrl = 'Viewport_Search.php?west=' + swPoint.lat() + '&east=' + nePoint.lat() + '&south=' + swPoint.lng() + '&north=' + nePoint.lng();
downloadUrl(searchUrl, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: point,
});
markersArray.push(marker); //eldorado's code Define the array to put markers in
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}