I am working on google maps i am trying to add markers to a google map and then tried to remove it but now as i have done both adding and removing with the code below
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>MapsApi</title>
<style>
#map_canvas {
width: 100%;
height: 500px;
background-color: #CCC;
}
#menu_bar{
width: 100%;
height: 150px;
position:absolute;
bottom:0px;
background-color: #CCC;
border-top:1px solid red;
}
body{
padding:0px;
margin:0px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var markers = [];
function initialize() {
var myLatlng = new google.maps.LatLng(44.5403, -78.5463);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
// add marker to positon
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
google.maps.event.addListener(marker, 'click', function(event) {
this.setMap(null);
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map_canvas"></div>
<div id="menu_bar">
</div>
</body>
</html>
but here is a problem now how should i set the value of markers.push(marker) because as i have removed one marker so its value must be less than its expected stored.. can any one help
The easier answer is that you don't remove the marker from the markers
array. All you do is identify the marker you want to remove from the map and then use setMap(null)
.
markers[indexOfMarker].setMap(null);
This way you can use the following if you want to add the marker back at some point:
markers[indexOfMarker].setMap(map);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With