Leaflet: add click event to clustered icons - onclick

I would like to add a click event to (subsequently) clustered icons on a leaflet map (using the Leaflet.markercluster plugin). The event itself works, but the alert always yields the very last element of the array for every icon that is clicked. I don't see the reason. declaring 'marker' as array did not change the result.
map.clearLayers;
var marker = [];
var markers = L.markerClusterGroup({
disableClusteringAtZoom: 10,
spiderfyOnMaxZoom: true,
chunkedLoading: true
});
for (id in reclist) {
var posn = reclist[id]['info'][1];
var pose = reclist[id]['info'][2];
var title = reclist[id]['info'][0];
var mapicon = L.icon({iconUrl: 'url of icon');
marker[id] = new L.marker(new L.LatLng(posn, pose), {icon: mapicon})
.on('click', function(){alert(title)});
markers.addLayer(marker[id]);
}
map.addLayer(markers);

There are special events for that: see documentation
markers.on('clusterclick', function() {});
Note that it is one event for your cluster. So it is NOT defined in your loop.
var markers = L.markerClusterGroup({ ... });
markers.on('clusterclick', function() { ... });
for (id in reclist) { ... }
In case I misunderstood your question and you want to define a click event for each markers: if you want to display title, you cannot use the variable as you do. Should do like this:
var title = reclist[id]['info'][0];
var marker = new L.marker(new L.LatLng(posn, pose), {icon: mapicon});
marker.title = title;
marker.on('click', function(e){alert(e.target.title)});
Here is an example

Related

Google Map: Link to the map according to feature type

I have a google Map with markers on a webpage.
Each marker has a unique feature position and type
This is the scenario I would like to put in place:
On another webpage I have static links to different markers of the map.
If you click on one of those links, you are directed to the map in which, one of these markers is centered (and its info window open).
But the markers latitude and longitude might change while the links will never change.
This means, I need the links not to use latitude and longitude info but markers feature type instead (which are remain the same).
How can I do that?
Here is my sample google Map script so far:
<script>
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {
center: {lat: 48.85639, lng: 2.33625}, // default centering
zoom: 18,
styles:
[
{featureType: 'poi',stylers: [{ visibility: 'off' }]},
{featureType: 'transit.station',stylers: [{ visibility: "off" }]}
]
});
var features = [
{position: new google.maps.LatLng(48.85659, 2.33555),type: 'markerone'},
{position: new google.maps.LatLng(48.85619, 2.33695),type: 'markertwo'}
];
var icons = {
'markerone': {icon: 'icon_one.png'},
'markertwo': {icon: 'icon_two.png'}
};
var contents= {
'markerone': {text: 'Content 1'},
'markertwo': {text: 'Content 2'}
};
for (var i = 0, feature; feature = features[i]; i++)
{
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map
});
var content = contents[feature.type].text;
var infowindow = new google.maps.InfoWindow()
google.maps.event.addListener(marker,'mouseover', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
google.maps.event.addListener(marker,'mouseout', (function(marker,content,infowindow){
return function() {
infowindow.close(map,marker);
};
})(marker,content,infowindow));
}
}
</script>
In this sample, I have to markers.
One has a feature type of "markerone" and the second is "markertwo".
How can I set my links to redirect and center the map around a specific marker in this kind of fashion:
http://www.mywebsite.com/mymap.php?myvariable=markertwo
Thank you.
First you would have to get the parameters. The example below gets all parameters and put them into an array. There you can search for your certain paramater like "markerType" and check if it's given or not. If not you have to perform a default action, otherwise you can handle the certain markerType like finding the correct marker, setting the map center to it and open the corrosponding infoWindow.
You just have to call the focusMarkerType-method onload of your page.
function getSearchParameters() {
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}
function transformToAssocArray( prmstr ) {
var params = {};
var prmarr = prmstr.split("&");
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
function focusMarkerType(){
var params = getSearchParameters();
if(params.markerType!=null){
//Handling the certain marker type
var found = false;
for (var i = 0, feature; feature = features[i]; i++) {
if (feature.type == params.markerType) {
found = true;
map.setCenter(feature.position);
//more...
break;
}
}
if (!found) {
console.log("unknown type")
}
}else{
//Handling default behaviour if no marker type is given
}
}

Google Map API, search box

I have integrated a Google Map on my page and add a search box to it with the following code:
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
});
Currently this give me a search box with autocompletion list, which is good. But I have to click on a item of this list to go to the location. If I just type something in the input an hit enter, nothing happened..
Any help ?
Thanks !
Try changing
var searchBox = new google.maps.places.SearchBox(input);
to
var autocomplete = new google.maps.places.Autocomplete(input);

Select Link or Checkbox to Display Category Markers

I am somewhat stuck at trying to tell Javascript to do what I want it to do.
I have an example map http://calwestcultural.com/sgs/backup/example-map.html and I have categories in my spry menu to the left. I would like those categories to be clickable and reveal only markers for that category.
I'd like to:
1. Hide Markers on load
2. When you click on a category (for example "eat" "banks" etc) I'd like ONLY for the markers within that category to show
*if creating a checkbox within the menu makes this easier, i am willing to do that. I am just hung up on this part of my map and need to move on.
CAN ANYONE PLEASE HELP? Something tells me this is an easy fix.
If you would like to keep markers in separate categories, create an array for each category of marker and use them to store each set of markers. Then do the following:
To hide markers on load, create the markers but leave the marker map property set to null:
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: null,
title:"Hello World!"
});
To show only the markers in a given category, listen for the event that should trigger display of the markers and then set the markers' map property:
for ( var i = 0; i < markerCategoryArray.length; i++ ) {
markerCategoryArray[i].setMap( map );
}
I got a clue on how to do this from this answer without multiple category arrays. More so, google maps v3 example linked there showed the following.
var gmarkers = [];
var marker = new google.maps.Marker({
position: latlng,
icon: gicons[category],
shadow: iconShadow,
map: map,
title: name,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
// === Store the category and name info as a marker properties ===
marker.mycategory = category;
marker.myname = name;
gmarkers.push(marker);
Then just filter by the category on the marker as depicted in the exmaple.
// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(true);
}
}
// == check the checkbox ==
document.getElementById(category+"box").checked = true;
}
// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(false);
}
}
// == clear the checkbox ==
document.getElementById(category+"box").checked = false;
// == close the info window, in case its open on a marker that we just hid
infowindow.close();
}

Google Maps Api 3 Remove Selected Marker Only

I've 2 function as below:
function addMarker() {
marker = new google.maps.Marker({
position: Gpoint,
map: map,
draggable: true,
animation: google.maps.Animation.DROP
});
map.panTo(Gpoint);
google.maps.event.addListener(marker, "rightclick",
function (point) {
showContextMarker(point.latLng); } );
$('.contextmenu').remove();
};
function delMarker() { marker.setMap(null); $('.contextmenu').remove(); };
So, as may understand I have a Context Menu having "Delete Marker" option on it.
I am binding a "rightclick" listener during adding a marker, to show this menu.
Everything is working without any problem till this moment.
But when I try to click on a marker to delete; it is effecting only the last added marker.
When I try again; nothing happens.
So my idea is to get the clicked marker's id (or something that may well be useful) and run this deleting function according to this.
Briefly; I want to delete the marker that I clicked on, from a map having multiple markers.
Do you have any approach to solve this problem ?
Thanks in advance!
SOLVED!
Here is the solution. Thank you Fatih. it was impossible without your guidance:
var id;
var markers = {};
var addMarker = function () {
marker = new google.maps.Marker({
position: Gpoint,
map: map,
draggable: true,
animation: google.maps.Animation.DROP
});
map.panTo(Gpoint);
id = marker.__gm_id
markers[id] = marker;
google.maps.event.addListener(marker, "rightclick", function (point) { id = this.__gm_id; delMarker(id) });
}
var delMarker = function (id) {
marker = markers[id];
marker.setMap(null);
}
Calling delete function by: delMarker(id)
Ps: "Right clicking is enough on this case"
Thank you!
Working Sample on jsFiddle
Google Maps doesn't manage your markers. So all your markers should be managed by yourself.
Make a global marker object and push all markers to this object. And give unique id to each marker when getting a marker instance. Then when you want to delete a marker take its id and find this marker in global marker object and finally call this marker instance's setMap method with passing null argument.
Also I've added a demo that works on jsFiddle. Code is heavily documented.
Your psuedo code should be like this. For more detailed code please look the demo.
var currentId = 0;
var uniqueId = function() {
return ++currentId;
}
var markers = {};
var createMarker = function() {
var id = uniqueId(); // get new id
var marker = new google.maps.Marker({ // create a marker and set id
id: id,
position: Gpoint,
map: map,
draggable: true,
animation: google.maps.Animation.DROP
});
markers[id] = marker; // cache created marker to markers object with id as its key
return marker;
}
var deleteMarker = function(id) {
var marker = markers[id]; // find the marker by given id
marker.setMap(null);
}
Complementing the #Fatih answer you should manage the markers. For example you could add each marker in a array and then to remove, you could find this marker into the array and set the val in the map null.
Just pass your marker in the rightclick function. For example:
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: true,
title: 'Hello World!'
});
google.maps.event.addListener(marker, "rightclick", function (point) {delMarker(marker)});
And make the function look this:
var delMarker = function (markerPar) {
markerPar.setMap(null);
}
Your markers will be removeable on the rightclicks.
this worked for me:
a second currentId, if you have a better idea, let me know
var actualMarkerId = 0;
var currentId = 0;
if (actualMarkerId>0) {
deleteMarker(actualMarkerId);
console.log(actualMarkerId);
}
var id = uniqueId(); // get new id
actualMarkerId = id;
For minimal changes
var newid=0;
for (var index in results){
var marker = new google.maps.Marker({
map: map,
icon: image,
__gm_id: = newid+1,
});
}
Now marker['__gm_id'] still has a value
Simple,Use Global array for marker Objects.
Push marker object in that array on plotting marker.
Yes,We can use Id in Marker Object for Unique Reference.
Code As Below
MarkerArray = []
marker = new google.maps.Marker({
Id: 1,
position: new google.maps.LatLng(Lat,Long),
type: 'info'
});
MarkerArray.push(marker);
To remove particular Marker,Find that Element Index using Unique Id for Each Marker.
var MarkerIndex = MarkerArray.findIndex(function GetIndex(element) {
return element.Id == 1;
});
MarkerArray[MarkerIndex].setMap(null);
MarkerArray.splice(MarkerIndex, 1); // to remove element from global array

bing map pushpin

when my bing map loads push pin is not visilble.
When i move or click on map it suddenly display pushpin.
i am using custum pushpin with correct path.
Got to the link click on launch satellite on right sidebar green button.A map load.
http://tinyurl.com/3z25amr
my code
function geocodeCallback(result) {
document.getElementById('post-satellite-map-address').firstChild.nodeValue = result.resourceSets[0].resources[0].address.addressLine;
}
jQuery('#post-gallery a[rel="post-gallery-photo"]').colorbox();
(function() {
var icon;
var map = new VEMap('post-satellite-map');
var mapDiv = document.getElementById('post-satellite-map');
var interval = setInterval(function() {
if(mapDiv.attachEvent != undefined) {
clearInterval(interval);
var lat = document.getElementById('post-satellite-map-lat').value, long = document.getElementById('post-satellite-map-long').value;
var position = new VELatLong(lat, long);
map.LoadMap();
map.SetZoomLevel(19);
map.SetCenter(position);
map.SetMapStyle(VEMapStyle.Birdseye);
icon = new VEShape(VEShapeType.Pushpin, position);
icon.SetCustomIcon(document.getElementById('post-satellite-map-icon').value);
map.AddShape(icon);
/*var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', ['http://dev.virtualearth.net/REST/v1/Locations/point?output=json&jsonp=geocodeCallback&includeEntityTypes=Address&point=', lat, ',', long].join(''));
document.body.appendChild(script);*/
}
}, 10);
document.getElementById('post-gallery-satellite').onclick = document.getElementById('sidebar-map-launch').onclick = function() {
jQuery.colorbox({inline: true, href: '#post-satellite-map-overlay'});
map.Resize();
icon.Hide();
icon.Show();
return false;
};
jQuery.get(
WPAjaxURL,
{ action: 'osm_postviews', postID: document.getElementById('post-id').value },
function(views) {
document.getElementById('post-views-count').firstChild.nodeValue = document.getElementById('post-satellite-map-views-count').firstChild.nodeValue = views;
},
'json'
);
})();
Please help me in this issue.
thanks in advance
This is a known issue when in Birdseye view in Bing Maps V6.3. Two options to get around this is to either move the map programmatically a small amount to trigger the redraw of the map, or upgrade to the Bing Maps v7 control

Resources