Google Maps v3 keeps references to markers (zooming issue) - google-maps

I´m placing some markers on a Google Maps holding them in a global array. With a button click the markers should disappear from the map deleting them also from the array.
// clear markers
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
// delete marker from markers array
markers.length = 0;
markers = [];
This works like a charm and the markers disappear from the map. In the next step i´m getting some new data via ajax-call, create markers again and add these markers in the markers array. New markers a visible on the map, but when zooming in/out the map suddenly the 'old' markers are visible again. So i have a mixture of the old and new markers.
Is this a Google Maps caching issue?
How to really remove the old markers from the map - map refreshing?
Thanks in advance.
SOLUTION
After writing this question i found the answer to this issue:
I also have an MarkerClusterer holding an reference to the markers array (and the markers). After clearing the MarkerClusterer all references to the old markers are gone. See this link:
Any change in zoom level causes all my markers to re-appear on my Google map

Try changing :
markers.length = 0;
markers = [];
to:
markers = [];
markers = null;
then just before adding the new markers initialize the array again.

Related

Overlapping Marker Spiderfier Marker Icon When There are Multiple Markers at Same Location

Google Maps doesn't provide a way to break apart multiple markers that are at the same location. This can occur with a people or businesses at a multiple residency location such as an apartment building or professional services building. Depending at zoom level it can also occur at shopping malls, etc.
The way around that is to "spiderfy" them: when clicking on the first it breaks them out with a line to the location. This is done in Google Earth and George MacKerron wrote a package to do that for Google Maps. (https://github.com/jawj/OverlappingMarkerSpiderfier)
It can be integrated with markerclusterer, although it doesn't support marker clusterer's batch creation of markers.
My issue is that the application I'm working on wants to have specific icons for different types of activities. Spiderfier puts one of the markers on top. A person looking at the map has no way of knowing that there can be 10 or more other markers underneath the top marker.
Ideally, there would be a way to put a top marker that displays when there are multiple markers similar to the different icon in markercluster. It isn't a direct 1-to-1 since spiderfier also works when they are close but not exactly at the same location (default is 20 pixels) and markercluster has no provision for accessing multiple markers at the exact same location.
The ideal behavior would be have a special icon for spiders that broke into the spiderfied individual icons when clicked. Similar to markerclusterer, but without the zoom change and handling the same location. The special icon ideally would indicate how many other markers are at the spot, again like markerclusterer. The special icon could be hidden or become part of the spiderfied group.
Without some accommodation users would have no way of knowing multiple activities are at the location. They may even assume that the activity they want is not at that location because another activities marker is shown.
This is a plunker that has the problem: http://plnkr.co/edit/vimZNq?p=info
var markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < 100; ++i) {
var latLng = new google.maps.LatLng(Math.floor(Math.random() * 10) / 10 + 39,
Math.floor(Math.random() * 10) / 10 - 100);
var marker = new google.maps.Marker({
position: latLng,
title: "marker " + i + " pos: " + latLng,
maxZoom: 8,
map: map
});
marker.desc = marker.getTitle();
bounds.extend(latLng);
markers.push(marker);
oms.addMarker(marker);
}
map.fitBounds(bounds);
var markerCluster = new MarkerClusterer(map, markers);
Thanks for your help,
David
Here's how I got it to work. Where map is a Gmap instance and oms is an Overlapping Marker Spiderfier instance. We're also using Marker Clusterer on the initial zoom which buys us a break.
map.addListener('zoom_changed', function() {
map.addListenerOnce('idle', function() {
// change spiderable markers to plus sign markers
// we are lucky here in that initial map is completely clustered
// for there is no init listener in oms :(
// so we swap on the first zoom/idle
// and subsequently any other zoom/idle
var spidered = oms.markersNearAnyOtherMarker();
for (var i = 0; i < spidered.length; i ++) {
// this was set when we created the markers
url = spidered[i].icon.url;
// code to manipulate your spidered icon url
};
});
});
oms.addListener('unspiderfy', function(markers) {
var spidered = markers;
for (var i = 0; i < spidered.length; i ++) {
url = spidered[i].icon.url;
// change it back
};
});
oms.addListener('click', function(marker) {
// put the clicked-on marker on top
// when oms un-spiders
marker.zIndex=999;
// set infowindow, panning etc.
});
I managed to match the following Versions:
MarkerClusterer 2.0.13
OverlappingMarkerSpiderfier 3.27
On every creation of a new Marker, i store the initialIconUrl in the Marker Object
var marker = new google.maps.Marker({
position: //some position
});
marker.setIcon(iconUrl);
marker.initialIconUrl = iconUrl;
When declaring the OverlappingMarkerSpiderfier, set the nearbyDistance to 0.001 (or some other very small value).
this.oms = new OverlappingMarkerSpiderfier(this.map, {
markersWontMove: true,
markersWontHide: true,
nearbyDistance: 0.001 //This will only spiderfy the Markers if they have the exact same position
});
Then, we need a listener on the maps 'idle' Event, to format the Markers manually.
I needed this because my SPIDERFIABLE Marker wouldn't show correctly on the first step, when transferring from the Clustered Marker to the seperate Markers.
var me = this;
google.maps.event.addListener(this.map, 'idle', function () {
me.oms.formatMarkers();
});
Listen to the oms 'format' Event and set the iconURL for Markers that are SPIDERFIABLE.
If the Marker is not spiderfiable, reset the Icon to the initial Url.
var spiderfiableIconUrl = //Whatever you need
this.oms.addListener('format', function (marker, status) {
var iconURL = status == OverlappingMarkerSpiderfier.markerStatus.SPIDERFIABLE
? spiderfiableIconUrl :
marker.initialIconUrl;
marker.setIcon(iconURL);
});
Hope this helps.
Some methods seems to be interesting like markersNearAnyOtherMarker but I cannot get it work.
An interesting way could be to use spiderfy and unspiderfy events and change marker when it's fired
overlappingMarkers = new OverlappingMarkerSpiderfier(map, overlapOptions);
overlappingMarkers.addListener('spiderfy', function (markers) {
markers.forEach(function (marker) {
marker.setLabel('*');
marker.setIcon(myNormalIcon);
})
})
overlappingMarkers.addListener('unspiderfy', function (markers) {
markers.forEach(function (marker) {
marker.setLabel(''+markers.length);
marker.setIcon(myOverlapIcon);
})
})
Unfortunatly, the unspiderfy event isn't fired until we open then close the overlap marker. If I find a conclusion to this solution I will update this post.

How to find all the markers which are currently visible on Google Maps V3?

I have a sidebar on which I want to display all the markers which are placed on the Google Map. and when I change the Veiwport by dragging the map. The marker list should refresh.
To Get all the Markers first you have to find the Bounds of the current Viewport then you have to loop all the markers and see if they are contains in the bound. The following is a example.
var bounds =map.getBounds();
for(var i = 0; i < markers.length; i++){ // looping through my Markers Collection
if(bounds.contains(markers[i].position))
console.log("Marker"+ i +" - matched");
}

Open Google Maps infowindows automatically for all of the markers and markerclusters

I have Google Map created with version of Google Maps api v3. It's "standard" Google Map, filled with markers and clusters. Every marker and cluster have it's own InfoWindow, showed when end user click on it.
What I need is that when map is loaded, to open all of InfoWindows of all markers and clusters showed on map.
Right now, they are showed only when I click on them:
google.maps.event.addListener(markerGreenCluster, 'clusterclick', function(markerGreenCluster) {
var content = '';
var info = new google.maps.MVCObject;
info.set('position', markerGreenCluster.center_);
var infowindow = new google.maps.InfoWindow();
aIWgreen.push(infowindow);
var center = markerGreenCluster.getCenter();
var size = markerGreenCluster.getSize();
var markers = markerGreenCluster.getMarkers();
// more code goes here...
})
I noticed that problem is in cluster definition, and method markerGreenCluster.getSize(); It returns number of grupped markers, and it can return it after whole map is loaded, or something like that.
Can you help me how can I achieve that all of InfoWindows are open (showed) when map is loaded?
the infowindows only open on click because you're only creating them on the click event listener. Move the code creating the infowindows out of the click handler, into a window load event handler instead.
To do this, what I do is create a InfoWindows object and stored it into the marker. Something like this
function CreateMarker(Lat, Lng, Title, Content) {
var aInfoWin = new google.maps.InfoWindow({
content: Content,
position: new google.maps.LatLng(Lat,Lng)
});
var aMarker = new StyledMarker({
title: Title,
position: new google.maps.LatLng(Lat,Lng),
MyInfoWin: aInfoWin
});
aMarker.MyInfoWin.open();
}
You can access to the Marker InfoWindows where you like (events, code,.....) like the other properties.
Code non tested, only to get the idea
Regards

Google Maps API v3 remove all polylines

Little background. I have a navigation setup for when you click on a certain navigation item, it creates markers on the map. If you click on a different navigation item, it removes the previous markers and sets up new ones.
Well now I am working with polylines and trying to create the same concept here with the polylines, however I am having a difficult time. Here is what I have:
// Global variable for array of lines
var points= [];
Setup my points.
line1 = new google.maps.LatLng(line1Start, line1Finish);
line2 = new google.maps.LatLng(line2Start, line2Finish);
line3 = new google.maps.LatLng(line3Start,line3Finish);
points.push(line1, line2, line3);
Setup my polylines.
var polyline = new google.maps.Polyline({
path:points,
strokeColor:"#FF0000",
strokeOpacity:1.0,
strokeWeight:2
});
Initialize the map with lines.
polyline.setMap(map);
All works well. The lines are created and show up between my markers. Now lets remove them (or not...)
function removeLines() {
if (points) {
points.length = 0;
}
points = [];
}
removeLines() is being called at the beginning of the function to clear them, then new ones are setup. This indeed clears my points in the points array, however on the map itself the polylines still show up and do not disappear like my markers do.
What gives?!
You have to do polyline.setMap(null), that will remove the line from the map. Documentation.
polyline is just an array of LatLng objects, not individual Polylines. I think you probably need a separate array for the polylines, which you can then loop over to remove them all. Create a global array line.
var line = [];
polyline = new google.maps.Polyline({
path: points,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
line.push(polyline);
Now you are pushing all the polyline objects into an array line. You can make it invisible or remove it from the map by looping it like this:
for (i=0; i<line.length; i++)
{
line[i].setMap(null); //or line[i].setVisible(false);
}

Google Maps V3: Marker Images displayed in incorrect position after map drag and zoom

I'm adding a collection of markers to a map in the v3 api. Everything works fine, but when I drag the map (enough so the markers are off the screen), zoom in, and then drag the map back to the original center, the marker images are offset by roughly the distance I dragged the map. They're still arranged in the correct shape, just moved.
A few other notes:
The marker images don't move if I drag and don't zoom in, or if I drag and zoom out.
If I just zoom in on the map until the markers are off the screen, the same thing happens
Polylines do not move (i.e., they retain their correct position no matter what)
In Firefox, marker images move (or rather, stay in their same pixel position and don't move with the coordinates point on the map) whenever i zoom in on a point other than map center
Here's the code I'm using the add markers:
var bounds = new google.maps.LatLngBounds;
for (i=0, len=points.length; i<len; i++) {
var myPoint = points[i];
var myLatLng = new google.maps.LatLng(myPoint.lat, myPoint.lng);
var markerImage = new google.maps.MarkerImage(
'http://www.mysite.com/images/marker.png',
new google.maps.Size(21,21), // size
new google.maps.Point(0,0), // origin
new google.maps.Point(10,10), // anchor
new google.maps.Size(21,21) // scale
);
var markerOptions = {};
markerOptions.map = this.map;
markerOptions.position = myLatLng;
markerOptions.icon = markerImage;
markerOptions.draggable = true;
this.markers[i] = new google.maps.Marker(markerOptions);
bounds.extend(myLatLng);
}
It's like the pane for the markers is disconnected from the pane for the map and polylines. Is there something I can do differently when adding the markers so the images retain their correct display position? This wasn't a problem in V2.
I'm fired.
Just after the block of code in the example, I had
if (init) {
//a bunch of stuff, PLUS
this.map.fitBounds(bounds);
} else {
//a bunch of other stuff, BUT NO fitBounds
}
so, adding
this.map.fitBounds(bounds);
in both logic paths fixed the problem