I am trying to delete a marker from google maps through a custom delete button. I have added the button and other information in the infowindow.
I have a function which deletes the marker from the map, the problem is when I press the delete button the function isnt called.
Here is my code:
function initMap() {
var jsonData = {$pointsArray};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
maxzoom: 15,
center: {
lat: 38,
lng: -77
}
});
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
var bounds = new google.maps.LatLngBounds();
for (var i = 0, len = jsonData.length; i < len; ++i) {
var point = jsonData[i];
var uniqueId = 1;
var markers = [];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(point.Lat, point.Lon),
map: map,
title: point.Title
});
bounds.extend(marker.position);
marker.id = uniqueId;
uniqueId++;
var contentString = '<div id="content">'+
'<h4 id="pointId" > ' + point.Title + '</h4>'+
'<h6 >City: ' + point.City + '</h6>'+
'<h6 >Latitude: ' + point.Lat+ '</h6>'+
'<h6 >Longitude: ' + point.Lon + '</h6>'+
'<h6 >Address: ' + point.Address + '</h6>'+
'<p data-placement="top" data-toggle="tooltip" title="Delete"><span class="glyphicon glyphicon-trash"></span></p>'
'</div>';
addInfoWindow(marker, contentString);
markers.push(marker);
}
function DeleteMarker(id) {
for (var i = 0; i < markers.length; i++) {
if (markers[i].id == id) {
markers[i].setMap(null);
markers.splice(i, 1);
return;
}
}
};
map.fitBounds(bounds);
}
Probably there is something wrong with the onclick attribute in the delete button, but I am not sure.
Help!
I think you have to use ' instead of " when you want to give marker.id as parameter because you used ' for the string and " for the attribute value. If you use " you just interrupt the attribute string for the onclick value.
In the rendered html, your function should look like this:
<p><a onclick="DeleteMarker('some id');"</a></p>
In order to achive that, put additional single quotes around the your id parameter:
onclick="deleteMarker('+"'"+ yourId +"'"+')
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm working on a view of the ASP.NET, using mvc. I using google maps with different markers. Each of those markers have their own infowindows that have 3 buttons each. By clicking a specific button I want the marker to change color. How can I do that?
I have already tried using document.getElementById and using the addEventListner. I also tried to program the button by using the onclick function.
var locations = [
["Recusado", "13/02/2019", 38.776816, -9.441833, 335, "foto.jpg", ],
["Aceite", "15/08/2019",38.817562, -8.941728, 36, "foto.jpg"],
["Em avaliação", "20/07/2019",38.487978, -9.004425, 90,"foto.jpg"],
["Concluído", "01/07/2019",37.045804, -8.898041, 12, "foto.jpg"]
];
var infowindow = new google.maps.InfoWindow({});
function setMarkers(map) {
for (var i = 0; i < locations.length; i++) {
var fire = locations[i];
var marker ;
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<div id="bodyContent">' +
'<p><b>Avaliação da Ocorrência:</b></p>' +
'<p>Fotografias:' + fire[5] + '</p>' +
'<p>Avaliação:' + fire[0] + '</p>' +
'<p>Data:' + fire[1] + '</p></br>' +
'<button id="aceite">Aceite</button>' +
'<button>Recusado</button>' +
'<button> Em avaliação</button>' +
'<button> Concluído</button>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({ content: contentString });
marker = new google.maps.Marker({
position: { lat: fire[2], lng: fire[3] },
map: map,
info: contentString,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(this.info);
infoWindow.open(map, this);
});
}
}
The buttons are represented in the variable contentString, and when I click the button with the id "Aceite", I want to change the color of the marker to green.
Attempt to change the marker to green:
<button id="aceite" onclick="state(marker)">Aceite</button>
function state(marker){
marker.setIcon('google.com/mapfiles/marker_green.png');
}
Simplest would be to add the click listener function when you open the InfoWindow (when you know what marker it is associated with).
Add the click listener to the button when the domready event of the InfoWindow fires (and it has been added to the DOM):
google.maps.event.addListener(infoWindow, 'domready', function() {
google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function(e) {
marker.setIcon('http://maps.google.com/mapfiles/marker_green.png');
})
});
Use function closure on the marker in the marker click listener (this references the marker in the click event listener function, but not in the InfoWindow domready event listener, save it so you can use it there):
google.maps.event.addListener(marker, 'click', function() {
var marker = this;
infoWindow.setContent(this.info);
google.maps.event.addListener(infoWindow, 'domready', function() {
google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function(e) {
marker.setIcon('http://maps.google.com/mapfiles/marker_green.png');
})
});
infoWindow.open(map, this);
});
proof of concept fiddle
code snippet:
function initMap() {
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var infowindow = new google.maps.InfoWindow({});
setMarkers(map);
}
var locations = [
["Recusado", "13/02/2019", 38.776816, -9.441833, 335, "foto.jpg", ],
["Aceite", "15/08/2019", 38.817562, -8.941728, 36, "foto.jpg"],
["Em avaliação", "20/07/2019", 38.487978, -9.004425, 90, "foto.jpg"],
["Concluído", "01/07/2019", 37.045804, -8.898041, 12, "foto.jpg"]
];
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var fire = locations[i];
var marker;
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<div id="bodyContent">' +
'<p><b>Avaliação da Ocorrência:</b></p>' +
'<p>Fotografias:' + fire[5] + '</p>' +
'<p>Avaliação:' + fire[0] + '</p>' +
'<p>Data:' + fire[1] + '</p></br>' +
'<button id="aceite">Aceite</button>' +
'<button>Recusado</button>' +
'<button> Em avaliação</button>' +
'<button> Concluído</button>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
marker = new google.maps.Marker({
position: {
lat: fire[2],
lng: fire[3]
},
map: map,
info: contentString,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
bounds.extend(marker.getPosition());
google.maps.event.addListener(marker, 'click', function() {
var marker = this;
infoWindow.setContent(this.info);
google.maps.event.addListener(infoWindow, 'domready', function() {
google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function(e) {
marker.setIcon('http://maps.google.com/mapfiles/marker_green.png');
})
});
infoWindow.open(map, this);
});
}
map.fitBounds(bounds);
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
This question already has answers here:
Google Maps JS API v3 - Simple Multiple Marker Example
(15 answers)
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 7 years ago.
I am trying to get a string from an array of arrays. I want to get the first property [0] into an info window. I am able to use the second and third values to set the placement of markers and I am also able to console.log the first value.
The particular JavaScript code is here:
markers = [
["4841 Bethesda Avenue (Elm Street)", 38.980724, -77.0964],
["7171 Woodmont Avenue", 38.980097, -77.093662],
["921 Wayne Avenue", 38.995740, -77.025652],
["801 Ellsworth Drive",38.997778, -77.025071]
];
infoWindow = new google.maps.InfoWindow()
for (var i = 0; i < markers.length; i++) {
console.log("markers: " + markers[i][0]);
position = new google.maps.LatLng(markers[i][1], markers[i][2]);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
console.log("markers 2: " + markers[i][0]);
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent("<div>Hello, World" + markers[i][0] + "</div>");
infoWindow.open(map, this);
});
};
When I console.log(markers[i][0]) it produces what I want. However, once it enters the addListener event, it loses it and I am not sure why.
Why does it become undefined?
Fiddle here.
HTML:
<h1 style="text-align: center;">Parking Garage Availability</h1>
<div id="map"></div>
<ul id="list"></ul>
<p id="GAR57"></p>
<p id="GAR31"></p>
<p id="GAR60"></p>
<p id="GAR61"></p>
CSS:
#map {
height: 300px;
width: 500px;
margin: 0 auto;
border: 1px solid black;
}
JavaScript:
var map;
var mapProp;
var marker;
var markers;
var url;
var myData;
var time;
var available;
var total;
var facility;
var position;
var infoWindow;
function initialize() {
mapProp = {
center: new google.maps.LatLng(38.994890, -77.063416),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapProp);
}
$(document).ready(function() {
initialize();
url = 'https://data.montgomerycountymd.gov/resource/qahs-fevu.json';
$.getJSON(url, function(data) {
myData = data;
for (i = 0; i < myData.length; i++) {
time = (myData[i].asofdatetime).slice(11);
available = myData[i].space_count;
total = myData[i].total_spaces;
facility = myData[i].facilitynumber;
if (facility === "GAR 57") {
facility = "4841 Bethesda Avenue (Elm Street)";
$('#GAR57').html('As of ' + time + ' there are ' + available +
' of ' + total + ' at ' + facility);
} else if (facility === "GAR 31") {
facility = "7171 Woodmont Avenue";
$('#GAR31').html('As of ' + time + ' there are ' + available +
' of ' + total + ' at ' + facility);
} else if (facility === "GAR 60") {
facility = "921 Wayne Avenue";
$('#GAR60').html('As of ' + time + ' there are ' + available +
' of ' + total + ' at ' + facility);
} else {
facility = "801 Ellsworth Drive";
$('#GAR61').html('As of ' + time + ' there are ' + available +
' of ' + total + ' at ' + facility);
}
}
});
//set markers
markers = [
["4841 Bethesda Avenue (Elm Street)", 38.980724, -77.0964],
["7171 Woodmont Avenue", 38.980097, -77.093662],
["921 Wayne Avenue", 38.995740, -77.025652],
["801 Ellsworth Drive", 38.997778, -77.025071]
];
infoWindow = new google.maps.InfoWindow();
for (var i = 0; i < markers.length; i++) {
console.log("markers: " + markers[i][0]);
position = new google.maps.LatLng(markers[i][1], markers[i][2]);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
console.log("markers 2: " + markers[i][0]);
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent("<div>Hello, World" + markers[i][0] + "</div>");
infoWindow.open(map, this);
});
};
});
Markers[i][0] becomes undefined because it does not exist in the scope of the function within addListener i.e. you're not passing markers into the function.
Instead, you're passing in marker
for (var i = 0; i < markers.length; i++) {
console.log("markers: " + markers[i][0]);
position = new google.maps.LatLng(markers[i][1], markers[i][2]);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
console.log("markers 2: " + marker.title);
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent("<div>Hello, World " + marker.title + "</div>");
infoWindow.open(map, this);
});
};
This shows an example displaying the title when the marker is clicked. Which I'm assuming is what you wanted to achieve.
I have a map that displays markers through a for loop.
function map_view_initialize() {
var properties = <?php echo is_array($properties) ? json_encode($properties) : $properties; ?>;
var index;
var mapOptions = {
center: {lat: 32.752601, lng: 9.801254},
zoom: 12,
};
var map = new google.maps.Map(document.getElementById('map_view_canvas'),
mapOptions);
infowindow = new google.maps.InfoWindow();
for (var index = 0; index < properties.length; index++) {
var latlng = new google.maps.LatLng(properties[index].property_latitude, properties[index].property_longitude);
var agent = properties[index].agent_firstname + ' ' + properties[index].agent_lastname;
var propertyName = properties[index].property_name;
var agentId = properties[index].agent_id;
var propertyLocation = properties[index].location_name;
var owner = properties[index].owner_firstname + ' ' + properties[index].owner_lastname;
var ownerTel = properties[index].owner_telephone_number;
var markerContent = "<div><h4>" + propertyName + "</h4>\n\
<h5>Location: " + propertyLocation + "</h5>\n\
<p>" + owner + " " + ownerTel + "</p>\n\
</div>";
var marker = new MarkerWithLabel({
agent:agentId,
position: latlng,
map: map,
labelContent: agent,
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels",
labelStyle: {opacity: 0.75}
});
marker.content = markerContent;
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(this.content);
infoWindow.open(this.getMap(), this);
});
}
}
I also have a group of buttons which are related with the agentId property of each marker.
#foreach($agents as $agent)
<button id="{{$agent->person_id}}" onclick="filterMarkers(this.id);" type='button' class='btn btn-success btnMargin btn-xs'>{{$agent->agent_lastname}} {{$agent->agent_firstname}}</button>
#endforeach
When i press one of these buttons then this function runs
function filterMarkers(agentId){
var element = document.getElementById(agentId);
var cls = hasClass(element,'notActive');
if(!cls){
element.classList.add("notActive");
element.style.opacity = 0.5;
}
else if(cls){
element.classList.remove("notActive");
element.style.opacity = 1;
}
}
I want to toggle the visibility of each marker by using my buttons (see the second block of code). For example when i press the button with the id=1 i need to hide/show the markers that the agentId property equals to 1.
You need an index of the marker associated to the agentId eg (defined in global area):
var markerIndex=[];
In the loop you must set for every agentId the associated marker
markerInded[agentId]=marker
and for toggle the marker you need functions for hide and show the marker eg
toggleMarkerOff(agentId){
markerIndex[agentId].setMap(null);
}
toggleMarkerOff(agentId){
markerIndex[agentId].setMap(map);
}
then you can call the prpoer function in the related element event
I am working on application in which i want place id for specific name which i am passing in request and want to get all places ID
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var data;
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
data += "The data is " + results[i] + "<br>";
}
document.getElementById('place_name').innerHTML = data.name;
//document.getElementById('place_id').innerHTML = data.place_id;
//document.write(data);
}
}
function createMarker(place) {
// var placeLoc = place.geometry.location;
//document.getElementById('place_name').innerHTML = place.name;
var marker = new google.maps.Marker({
map: map,
// placeId: place.place_id,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address);
// infowindow.setContent(place.address_components);
infowindow.open(map, this);
});
I am able to print name and id in marker but i just want to get all place id.
any help will be appreciated.
thanks in advance
this link from google could help you:
https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder?hl=es
Good look.
I am trying to add sidebar. I am using name variable for links on the sidebar which are fetched from the database and it is available to me as an array. I am not able to loop twice as that puts QUERY_LIMIT to the google database.
Can anybody provide me logic on the way how to work on this functionality?
Here is my script:
<script type="text/javascript">
var markers = [];
var side_html = "";
var icon1 = "prop.png";
var icon2 = "office.png";
var locations = <?php echo $add_js ?>;
var name = <?php echo $name_js ?>
//function that will be used to handle clicks on the links in the sidebar
function myclick(num) {
google.maps.event.trigger(locations[num], "click");
}
function geocodeAddress(i)
{
geocoder.geocode({'address' : locations[i]},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
createMarker(results[0].geometry.location, i);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function createMarker(latlng,i) {
var marker = new google.maps.Marker({
map : map,
icon : icon1,
position : latlng
});
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50),
disableAutoPan: true
});
google.maps.event.addListener(marker, 'mouseover', function() {
marker.setIcon(icon2);
infowindow.setContent(locations[i]);
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
marker.setIcon(icon1);
infowindow.setContent(locations[i]);
infowindow.close(map, marker);
});
return marker;
}
var map = new google.maps.Map(document.getElementById('map'), {
zoom : 10,
center : new google.maps.LatLng(28.6139, 77.2089),
mapTypeId : google.maps.MapTypeId.ROADMAP
});
//var infowindow = new google.maps.InfoWindow({size: new google.maps.Size(150,50)});
var geocoder = new google.maps.Geocoder();
for (var i = 0 ; i < locations.length; i++) {
geocodeAddress(i);
// link to the sidebar HTML that will open the info window for the record being processed
side_html += '' + name + '<br />';
document.getElementById("side_bar").innerHTML = side_html;
}//end of for loop
</script>
I am getting proper markers in the output, but as the sidebar links i am getting whole of the name array each time and the link is not responding even to click events.
if "name" is an array, this should work:
for (var i = 0 ; i < locations.length; i++) {
geocodeAddress(i);
// link to the sidebar HTML that will open the info window for the record being processed
side_html += '' + name[i] + '<br />';
}//end of for loop
document.getElementById("side_bar").innerHTML = side_html;
Solved my problem at last!
I needed to split my array of strings first before using them to display in the sidebar link.
var name = names[i].split(",");
Final Soltion code:
for (var i = 0 ; i < locations.length; i++)
{
geocodeAddress(i);
var name = names[i].split(",");
side_html += '' + name + '<br />';
}
document.getElementById("side_bar").innerHTML = side_html;