Remove markers from map (Google Maps API v3) - javascript

I'm developing an app with Google maps that should display several categories on a map. Now I would like to have the possibility to add markers from several categories and delete them as well if necessary.
I've managed to figure out the whole thing. At least, almost... I'm having troubles with the removal of the markers of a category. I've created a live demo on jsfiddle to make this clear.
So here's how I attempt to do this:
CODE
First I initialize the map, etc. (but that is not relevant here). Then I add the markers on the map:
for(i in markers){
var marker = new google.maps.Marker({
map: map,
draggable: false,
position: new google.maps.LatLng(markers[i].latitude, markers[i].longitude),
visible: true,
data: category
});
newMarkers.push(marker);
}
As you can see I have 'data: category' in the object. This is something that's not google maps api, but it gives me no errors and gives me the possibility to search the array when I want to remove the markers. Here the removeMarker function:
function removeMarkers(category)
{
for(i in newMarkers) {
if(newMarkers[i]['data'] == category){
count ++;
newMarkers[i].setMap(null);
newMarkers.splice(i, 1);
}
}
}
It does remove markers, but not all of them...
Does anyone have solution to my problem?
LIVE DEMO
Thanks in advance,
Helena S.

Seems like the problem is that you are iterating the newMarkers array and at the same time removing elements from it.
Try this instead. It only sets the removed marker values in the array to null then, after the loop, filters those null values:
for(i in newMarkers) {
if(newMarkers[i]['data'] == category){
count ++
newMarkers[i].setMap(null);
newMarkers[i] = null;
}
}
newMarkers = newMarkers.filter(function(val){ return !!val; });
http://jsfiddle.net/GJUcy/

Related

Add Leaflet Search through a Feature Group

Similar to Search for markers in a markercluster group Leaflet-MarkerCluster
But i am using a Control group ontop of Marker Cluster so they will be displayed upon a radio button click.
var map = L.map("map"),
parentGroup = L.markerClusterGroup(options), // Could be any other Layer Group type.
// arrayOfMarkers refers to layers to be added under the parent group as sub group feature
mySubGroup = L.featureGroup.subGroup(parentGroup, arrayOfMarkers);
parentGroup.addTo( map );
mySubGroup.addTo( map );
I am attempting to implement Leaflet Search - but as per the documentation says it requires a group layer of markers as the second parameter for it work. Trouble is using L.featureGroup.subGroup requires an array of markers.
Attempted to iterate through mySubGroup at run time to get the layers of markers using Leaflet eachLayer but this will duplicate the amount of markers i have on the map for the search to work.
var markersLayer = new L.LayerGroup().addTo( this.map );
forEach( mySubGroup, layers => {
layers.eachLayer( function (layer ) {
console.log ( layer );
markersLayer.addLayer( layer );
})
});
map.addControl( new L.Control.Search({layer: markersLayer}) );
Solved this issue - though it's quite inefficient. If you can find a more elegant solution to avoid duplication then feel free to contribute it as an answer!
var title = layer.options.title;
// iterate through the cluster points
forEach( mySubGroup, layers => {
layers.eachLayer(function (layer) {
var title = layer.options.title; // match the search title to marker title
marker = new L.Circle(new L.LatLng(layer.getLatLng().lat,layer.getLatLng().lng),
{radius: 0, title: title, fill: 'red', fillOpacity: 0, opacity: 0 }); // Create an invisible L circle marker for each cluseter marker
markersLayer.addLayer(marker);
})
});
You then add the markersLayer to the Leaflet Search

GoogleMapsAPI - create markers filter

I'm doing a dynamic map using the Google Maps API that uses the markers to mark a list of predefined locations, such as:
self.locations = [{
name: 'Foxtrot',
lat: 38.713905,
lng: -9.1518868,
type: 'Bar'
}
It also has a Search field that allows you to filter by the name of the locations (filteredNav). It should also filter the markers, but...that is the problem.
The recommendation that I have is the following:
Try writing console.log(self.location_array());.Because location and
marker data modal is separate, you'll have to loop through
self.location_array() to process and find which one to show, which one
to hide by calling setVisible (or setMap) on the marker object.
This is my code:
// Create observable array
self.nav = ko.observableArray(self.locations);
// Create empty observable string
self.filter = ko.observable('');
// Show nav and filter
self.filteredNav = ko.computed(function() {
var filter = self.filter().toLowerCase();
if (!filter) {
return self.nav();
}
return self.nav().filter(function(i) {
// Check for proper casing or lowercase
return i.name.toLowerCase().indexOf(filter) > -1 || i.name.indexOf(filter) > -1;
});
//THIS IS THE PROBLEM!
for (var i = 0; i < location_array()[i].length; i++) {
//??????
location_array()[i].setVisible(true);
}//?????
}
note: observable array implementation: vm.location_array()[i]
Link to the project
So...the question is...how can I do the loop? I've no idea how to do it....
First of all, the code you have presented has some 'mysterious' parts. For example, what is self, what is ko, what is observableArray etc. One can only guess what each of these are.
So I will simply describe to you the general logic of how to achieve what you want.
The logic is pretty straightforward.
The same way you filter the places in the sidebar, when you type, you should filter the array of markers to call setVisible with true or false
This means, that when you create the markers, you should store them to a separate array.
Also, when you create a marker, e.g.
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(latitude, longitude)
})
Add a name property, or something similar, to it, like so
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(latitude, longitude),
name: 'Foxtrot`
})
so that your created marker has a name property, which you can use to filter your array of markers.
Thus, in order to filter your markers array, you should simply iterate over the array and check the .name property of each marker object, and if the name does not match the search input, simply setVisible(false) on the marker, otherwise do setVisible(true)
Hope this helps.

Markerclusterer customization google maps

I have a basic markerclusterer example which works very well.
var center = new google.maps.LatLng(37.4419, -122.1419);
var options = {
'zoom': 13,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), options);
var markers = [];
for (var i = 0; i < 100; i++) {
var latLng = new google.maps.LatLng(data.photos[i].latitude,
data.photos[i].longitude);
var marker = new google.maps.Marker({'position': latLng});
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
What I would like to do is cluster the markers by country and then once you click on it they are still clustered until on3 further click. Currently they are clustered until you are down to one result. I have thousands of markers and would like them visible after one country click and then one more click.
I looked for a solution online and found this http://google-maps-utility-library-v3.googlecode.com/svn/tags/markermanager/1.0/examples/google_northamerica_offices.html
which is produced using this
var officeLayer = [
{
"zoom": [0, 3],
"places": [
{ "name": "US Offices", "icon": ["us", "flag-shadow"], "posn": [40, -97] },
{ "name": "Canadian Offices", "icon": ["ca", "flag-shadow"], "posn": [58, -101] }
]
},
...
};
function setupOfficeMarkers() {
allmarkers.length = 0;
for (var i in officeLayer) {
if (officeLayer.hasOwnProperty(i)) {
var layer = officeLayer[i];
var markers = [];
for (var j in layer["places"]) {
if (layer["places"].hasOwnProperty(j)) {
var place = layer["places"][j];
var icon = getIcon(place["icon"]);
var title = place["name"];
var posn = new google.maps.LatLng(place["posn"][0], place["posn"][1]);
var marker = createMarker(posn, title, getIcon(place["icon"]));
markers.push(marker);
allmarkers.push(marker);
}
}
mgr.addMarkers(markers, layer["zoom"][0], layer["zoom"][1]);
}
}
mgr.refresh();
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
I'm not sure how to implement this into what I've currently got and if i need to include any other scripts/ libraries also.
You are looking at two totally different libraries, there. Your question is about the MarkerClusterer library, but your example solution is about the MarkerManager library.
The MarkerClusterer library automatically clumps markers together based on an algorithm that tries to decide when too markers would be so close together that you can't visibly distinguish one from another. You don't really have a lot of control over when and how it decides to merge markers together this way, so this library is idea when it doesn't matter to you how they get merged, as long as merging happens. Since you want to merge markers together by political boundaries (countries) and not by proximity to each other, this is not the library for you.
The MarkerManager library does not automatically merge markers together at all. What it does do is to selectively hide and reveal markers based on the zoom level of the current map viewport. What you would need to do is do your own merging, and then add to the MarkerManager all of the merged markers, as well as the detail markers, and the zoom levels where you want each marker to be visible. Doing your own merging means you will need an alternate way of determining which country each marker point falls within. Hopefully, you already know (or can get) that information, because it's not automatically provided by any of these libraries.
tl;dr - use the MarkerManager library and not the MarkerClusterer library for grouping by countries, and it's up to you to identify the location for each country and which marker goes with which one.

Google Maps - get values from location array based on the map's current viewpoint

Edit:
Question = "is there a way to loop through the array and check if each location (long/lat) falls within the current viewport directly" (failing that get all markers within the viewport)
Background:
I have an array of locations (lat, long, id).
I want to:
On a Google Map, use the location array to display markers.
The user can scroll/zoom the map.
Have a button underneath the map, so when the user has decided on an area, he can click the button, and the code will return the ids (from the location array) that are contained within the viewport / map bounds.
There is a .contains for Google, so I guess you could potentially use that with something like
map.getBounds().contains and somehow reference each marker.getPosition()
but I wonder if there's a way to loop through the array and check if each location (long/lat) falls within the current viewport directly
You mean something like this (not tested), map is the google.maps.Map object and needs to be in scope. markersArray is the array of markers.
for (var i=0; i< markersArray.length; i++) {
if (map.getBounds().contains(markersArray[i].getPosition())) {
// the marker is in view
} else {
// the marker is not in view
}
}
http://jsfiddle.net/UA2g2/1/
Thanks geocodezip, you gave me the idea on how to solve it via looping through the array. I don't know if this is the most efficient way, but I put together some code that seems to do what I want - if you check the jsfiddle above and view console you can see that it logs when and which points are in the viewport.
$(document).ready(function(){
var myOptions = {
center: new google.maps.LatLng(51, -2),
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var storeArray = new Array(["51.38254", "-2.362804", "ID1"], ["51.235249", "-2.297804","ID2"], ["51.086126", "-2.910767","ID3"]);
google.maps.event.addListener(map, 'idle', function() {
for (i = 0; i < storeArray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(storeArray[i][0], storeArray[i][1]),
map: map
});
}
for (var i=0; i<storeArray.length; i++) {
if (map.getBounds().contains(new google.maps.LatLng(storeArray[i][0], storeArray[i][1]))) {
console.log("marker: " + storeArray[i][2]);
}
}
});
});

check if map markers are within selected bounds

I have a map with various markers and i need to be able to draw a rectangle on the map and select the markers which are within the rectangle bounds.
So far i have found some great info here: How to get markers inside an area selected by mouse drag?
I have implemented the keymapzoom plugin ok. like so
$('#dispatcher').gmap3({action:'get'}).enableKeyDragZoom({
boxStyle: {
border: "dashed black",
//backgroundColor: "red",
opacity: 0.5
},
paneStyle: {
backgroundColor: "gray",
opacity: 0.2
}
});
var dz = $('#dispatcher').gmap3({action:'get'}).getDragZoomObject();
google.maps.event.addListener(dz, 'dragend', function (bnds) {
alert(bnds);
});
This gives me the following
((lat,long),(lat,long)) format from the alert(bnds);
I need to know how i can now check if any markers are within this?
I already have an object that is storing the markers for another reason. like:
markers[name] = {};
markers[name].lat = lati;
markers[name].lng = longi;
which might be useful?
I don't understand how to use the GLatLngBounds and containsLatLng(latlng:GLatLng) as suggested.
Your question is tagged with the v3 version of the Maps API, so I'll assume you are using that version (which you should as v2 is deprecated). Note that some classes and methods are named different than in your question.
Bounds are represented with the LatLngBounds class. You can perform the contains method on an instance of that class to determine if a point lies within those bounds.
If you have an object with all your markers, you can loop through them and check each marker, for example:
var bounds = new google.maps.LatLngBounds(sw, ne);
for (var a in markers) {
if (bounds.contains(new google.maps.LatLng(markers[a].lat, markers[a].lng)) {
// marker is within bounds
}
}
On a side note, I would store the LatLng object in the markers object when creating them. That way you don't have to create them wherever you need.
Box/Rectangle Draw Selection in Google Maps
This was my solution..
google.maps.event.addListener(dz, 'dragend', function(e) { //important listener
for(var i = 0; i < markers.length; i++){ // looping through my Markers Collection
if(e.contains(markers[i].position))
console.log("Marker"+ i +" - matched");
}
});

Categories

Resources