Reputation: 1367
I have put multiple markers on my map by click event and now I want to delete a single marker by double clicking on a specific marker. But what it is doing is just deleting the last marker of the array. Any help please?
:::::::::::::::::::::EDIT::::::::::::::
Is it possible to delete a single marker based on a button press? It is something like I have a table row where I have put the lat long of that marker and a delete button. If I click delete button it should delete the point associated with that button in that row.
Upvotes: 1
Views: 10625
Reputation: 70075
I started with your code and made some changes and it works for me. Does this do it for you?
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 80% }
html { width: 70% }
body { height: 80%; margin: 0px; padding: 0px }
body { width: 70%; margin: 0px; padding: 0px }
#map_canvas { height: auto }
#map_canvas { width: auto }
</style>
</head>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=true">
</script>
<script type="text/javascript">
var map;
var geocoder;
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var markersArray = [];
function initialize() {
geocoder = new google.maps.Geocoder();
var myLocation = new google.maps.LatLng(52.13206069538749, -106.63635849952698);
var mapOptions = {
zoom: 12,
center: myLocation,
mapTypeControl: true,
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
document.getElementById("latbox").value=event.latLng.lat();
document.getElementById("lngbox").value=event.latLng.lng();
// google.maps.event.addListener(marker, 'click', function() {
// document.getElementById("latbox").value=event.latLng.lat();
// document.getElementById("lngbox").value=event.latLng.lng();
// });
google.maps.event.addListener(marker, 'dblclick', function(event) {
deleteMarker(marker);
});
});
}
// code for search address
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var search_marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
// function to create marker
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
markersArray.push(marker);
}
//function to remove a single marker
function deleteMarker(marker){
marker.setMap(null);
}
// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
infowindow.close();
document.getElementById("latbox").value="";
document.getElementById("lngbox").value="";
}
// Shows any overlays currently in the array
function showOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(map);
}
}
}
// Deletes all markers in the array by removing references to them
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
infowindow.close();
document.getElementById("latbox").value="";
document.getElementById("lngbox").value="";
/**
document.getElementById('street').value="";
document.getElementById('area').value="";
document.getElementById('pass').value="";
document.getElementById('descr').value="";
document.getElementById('hintimage').value="";
document.getElementById('showimage').value="";
document.getElementById('hint').value="";
document.getElementById('char').value="";
document.getElementById('icon').value="";
document.getElementById('zid').value="";*/
}
//document.write("3");
</script>
<body onload="initialize()">
<!--------------------------------------------------HTML FORM-------------------------------------------------------------->
<div id="map_canvas" style="width:100%; height:100%"></div>
<div id= "map_form" style="display:visible" action="">
<br />
<br /> Write address for POIs in you desired location: <input id="address" type="text" value="Saskatoon, SK"/>
<input id="searhButton" type="button" value="Search Location" onclick="codeAddress()"/> <br />
<br />
Latitude: <input name="latitude" type="text" id="latbox" ReadOnly="True"/><br />
<br />
Longitude: <input id="lngbox" type="text" ReadOnly="True"/><br />
<br />
Zone ID: <input id="zid" type="text" /> [numbers only]
<input type="hidden" id=zid2>
<br />
<br />
Street: <input id="street" type="text" /><br />
<br />
Area: <input id="area" type="text" /><br />
<br />
Password: <input id="pass" type="text" /><br />
<br />
Description: <input id="description" type="text" /><br />
<br />
Image for hint: <input id ="hintimage" type="file" /><br />
<br />
<br />
Image to show: <input id ="showimage" type="file" /><br />
<br />
Hint: <input id="hint" type="text" /><br />
<br />
<br />
3D Character: <input id="char" type="file" /><br />
<br />
<br />
Icon: <input id="icon" type="file" /><br />
<br />
<!--<input type="button" onclick="alertfunction()" value="show alert"/>-->
<input type="reset" value="Reset" onclick="deleteOverlays()"/>
<input onclick="showOverlays();" type=button value="Show All POIs"/>
<input type="button" onclick="alertfunction()" value="Save Data" />
</div>
<!----------------------------Database Connection code---------------------------------------------------------------------->
<script language="javascript" type="text/javascript">
function alertfunction(){
if (validateFormOnSubmit(map_form) == false){
alert("Some fields need correction:\n" + reason);
}
else{
// alert("else in....");
var req;
try{
// Opera 8.0+, Firefox, Safari
req = new XMLHttpRequest();
//document.write("2");
}catch (e){
// Internet Explorer Browsers
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
req.onreadystatechange = function() {
//Is request finished? Does the requested page exist?
if(req.readyState==4 && req.status==200) {
//Your HTML arrives here
//document.write("state is 4");
alert(req.responseText);
document.getElementById('ajaxDiv').innerHTML = req.responseText;
}
/*
else if (req.readyState==0){
document.write("state is 0");
}
else if (req.readyState==1){
document.write("state is 1");
}
else if (req.readyState==2){
document.write("state is 2");
}
else if (req.readyState==3){
document.write("state is 3");
}*/
}
var latitude=document.getElementById('latbox').value;
var longitude=document.getElementById('lngbox').value;
var zid=document.getElementById('zid').value;
var zid2=document.getElementById('zid').value;
var street=document.getElementById('street').value;
var area=document.getElementById('area').value;
var pass=document.getElementById('pass').value;
var description=document.getElementById('description').value;
var hintimage=document.getElementById('hintimage').value;
var showimage=document.getElementById('showimage').value;
var hint=document.getElementById('hint').value;
var char=document.getElementById('char').value;
var icon=document.getElementById('icon').value;
// MIGHT NEED SOME MODIFICATION ON PATH
var queryString= "?latitude="+latitude;
//var queryString= "?latitude="+latitude;
queryString+="&longitude="+longitude+"&zid="+zid+"&zid2="+zid2+1+"&street="+street+"&area="+area+"&pass="+pass+"&description="+description+"&hintimage="+"http://aiworker2.usask.ca/passimagemodels/"+hintimage+"&hint="+hint+"&char="+char+"&icon="+icon+"&showimage="+showimage;
//porpoise/image/
//req.open("GET","http://aiworker2.usask.ca/dbload/db_server2.php"+ queryString,true) //true indicates ASYNCHRONOUS
req.send(null);
}
}
<!--------------------------------------Validation Code---------------------------------------------------------->
function validateNum(fld) {
//alert("validateNum");
var val = fld.value;
var numericExpression = /^[0-9]+$/;
if(val.match(numericExpression)){
//alert("true");
return true;
}else{
fld.style.background = "Yellow";
alert("POI id must be numeric");
return false;
}
}
// checking of an empty field
function validateEmpty() {
var error = "";
var latVal = document.getElementById('latbox').value;
var longVal=document.getElementById('lngbox').value;
var idVal=document.getElementById('zid').value;
var hint=document.getElementById('hint').value;
var char=document.getElementById('char').value;
var pass=document.getElementById('pass').value;
if (latVal.length == 0) {
error += "latitude";
document.getElementById('latbox').style.background = 'Yellow';
}
if (longVal.length == 0) {
error += " longitude";
document.getElementById('lngbox').style.background = 'Yellow';
}
if (idVal.length == 0) {
error += " POI id";
document.getElementById('zid').style.background = 'Yellow';
}
if (hint.length == 0) {
error += " Hint";
document.getElementById('hint').style.background = 'Yellow';
}
if (char.length == 0) {
error += " 3D Character";
document.getElementById('hint').style.background = 'Yellow';
}
if (pass.length == 0) {
error += " Password";
document.getElementById('pass').style.background = 'Yellow';
}
if(error.length != 0){
error += " should not be empty";
}
return error;
//return "something";
}
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmpty();
if (reason != "") {
alert(reason);
return false;
}
//return true;
return validateNum(document.getElementById('zid'));
}
</script>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
Basically, I got rid of the deleteMarker()
callback and replaced it with an anonymous function. The anonymous callback uses this
rather than marker
to make sure it is removing the correct marker. You could do the same in the deleteMarker()
callback or just use the anonymous callback the way I did.
I also commented out the callback for the markers on the single click event, but you can put that back in without any adverse effects, I think. (Just note that the click event also triggers when the dblclick event triggers, or at least that's what the documentation leads me to believe.)
Upvotes: 1
Reputation: 81167
The easy way: assign added marker's index (in markersArray) to the button and invoke deleteMarker upon click event on that button:
function createRow(markerIndex){ // add your args like lat, lng etc
// do the magic and create table row with button having onclick=deleteMarker(markerIndex)
}
function deleteMarker(markerIndex){
markersArray[markerIndex].setMap(null);
}
// invoke createRow when adding new marker
function addMarker(position){
marker = new google.maps.Marker({
position: location,
map: map
});
var markerIndex = markersArray.push(marker) - 1; // push() returns new array length
createRow(markerIndex);
}
This will work for new markers as well as for the ones loaded from eg. db. Mind that you will have to check which markers are going to be put in db if you want to save them, since setMap(null) doesn't deletes them from the markersArray.
Upvotes: 2
Reputation: 1601
try the following which should work. I only kept the relevant part.
<script type="text/javascript">
var map;
function initialize() {
var myLocation = new google.maps.LatLng(52.13206069538749, -106.63635849952698);
var mapOptions = {
zoom: 12,
center: myLocation,
mapTypeControl: true,
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
addClickEvent(marker);
});
}
function addClickEvent(marker){
google.maps.event.addListener(marker, 'dblclick', function(event) {
marker.setMap(null);
});
}
</script>
Upvotes: 0
Reputation: 458
Try this. Change
function deleteMarker(marker){
marker.setMap(null);
}
To
function deleteMarker(marker){
return function() {
reallyDelete(marker);
};
}
function reallyDelete(marker) {
marker.setMap(null);
}
Upvotes: 0