Google Maps Api 3 Remove Selected Marker Only - google-maps-api-3

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

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
}
}

Leaflet: add click event to clustered icons

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

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

Put marker from Google Maps v3 in front of all others

Can somebody help me put the current location in front of all others? I have read about MAX_ZINDEX and setZindex() but I cannot understand it. This is my code:
var latlng = new google.maps.LatLng(lat,lng);
var image = "";
var currentplace = "Ohla Hotel";
var zInd = "";
if( name == currentplace ) {
image = "../img/hotel_icon.png";
}
else {
image = "../img/home_icon.png";
}
//alert();
var maxZindex = google.maps.Marker.MAX_ZINDEX;
if( name == currentplace ) {
zInd = (maxZindex + 1);
}
var locationDescription = this.locationDescription;
var marker = new google.maps.Marker({
map: map,
position: latlng,
title:'pk:'+name,
MAX_ZINDEX: zInd,
icon: image
});
bounds.extend(latlng);
setMarker(map, marker, name, locationDescription);
MAX_ZINDEXis a constant, not an attribute of a marker.
The relevant MarkerOption is zIndex:
var marker = new google.maps.Marker({
map: map,
position: latlng,
title:'pk:'+name,
zIndex: zInd,
icon: image
});
This sets the marker's zIndex attribute to the value you have calculated, which is one more than the API's maximum value.
Most of your code makes sense, but your definition of the MarkerOptionsapi-doc object doesn't make sense. Try changing your marker creation code to this:
var marker = new google.maps.Marker({
map: map,
position: latlng,
title:'pk:'+name,
zIndex: zInd,
icon: image
});
Since you have already set the value of zInd higher than google.maps.Marker.MAX_ZINDEX, making this change should place the marker higher in the zIndex and thus above the other markers on the map.

how to set marker one by one in google map api v3?

I am doing a google map which will read a set of coordinates and put the marker on the map one by one.
Below is my idea:
function A{
for loop(
set marker
call setTimeout('A',2seconds)
)
}
my idea is to set a marker and use setTimeout to wait 2 seconds and then set the next marker.
However, it doesn't work. it show all the markers at the same time and repeat to renew all markers.
How can i achieve my goal?
Thanks for your help!!!!!!!!!!!!!!!
Here is my code:
function marker(){
var marker;
var i=0;
while(i<locations.length){
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
animation: google.maps.Animation.DROP,
map: map
});
i=i+1;
var t=setTimeout("marker()",2000);
}
}
marker();
You need to return after setting the first marker. You also need a parameter to A which specifies which marker to show.
function marker(i){
if (i > locations.length) return;
var marker;
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
animation: google.maps.Animation.DROP,
map: map
});
var t=setTimeout("marker("+(i+1)+")",2000);
}
marker(0);

Resources