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
Related
I work in Laravel project and I have module for displaying and removing all stores on a Google map if I choose only 1 store.
This is a duplicate question, however, why my function is not working setting the function showallmarks as null.
Question: How to remove all the marks displayed in the google maps once a button is clicked?
I have here the codes.
Show all marks:
showallmarks();
function showallmarks() {
$.each(locations, function(index, value) {
var position = new google.maps.LatLng(value.store_lat, value.store_long);
var title = value.branch_name;
var address = value.store_address;
var contentString = "<h5>" + title + "</h5>" + address;
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: position,
icon: google.maps.marker,
map: map,
zoom: 12
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
});
}
Once I click this button the showallmarks must not be shown on the Google map.
var markeronce;
$('button#addresses').click(function() {
//removing all marks
showallmarks(null);
var infowindow = new google.maps.InfoWindow({
content: "<span>Visit us on our store.</span>"
});
var address_href = $(this).val();
var commaPos = address_href.indexOf(',');
var coordinatesLat = parseFloat(address_href.substring(0, commaPos));
var coordinatesLong = parseFloat(address_href.substring(commaPos + 1, address_href.length));
var centerPoint = new google.maps.LatLng(coordinatesLat, coordinatesLong);
if (!markeronce) {
markeronce = new google.maps.Marker({
position: centerPoint,
map: map,
zoom: 8
});
} else {
markeronce.setPosition(centerPoint);
}
map.setCenter(centerPoint);
})
Add Button like
<input type="button" value="Delete" onclick="DeleteMarkers()" />
And try this function
<script type="text/javascript">
var markers = [];
function DeleteMarkers() {
//Loop through all the markers and remove
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
};
</script>
I have been working on this for a while now. I have looked at multiple stack overflow posts on the topic and several tutorials, but I have not been able to get infoWindow.close() to work.
I have even tried using jQuery to click $('#googleMap > div > div > div:nth-child(1) > div:nth-child(4) > div:nth-child(4) > div:nth-child(1) > div:nth-child(3)').click(); which actually seems to work in the browser console, but not when running the click listener.
Any suggestions or directions are much appreciated.
d3.csv('/data/locs.csv', function(locs){
var obj = [];
for(i=0;i<locs.length;i++) {
var country = locs[i].country;
var location = locs[i].location;
var lat = locs[i].lat;
var long = locs[i].long;
var description = locs[i].description;
obj.push({
con: country,
location: location,
lat: lat,
lng: long,
description: description
});
}
console.log(obj);
initMap(obj)
});
function initMap(obj, error) {
if (error){console.log("Error: "+error)}
var openInfoWindow = null;
var mapProp = {
center: {lat: 39.8283, lng: -98.5795},
zoom: 2
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var pointLoc = [];
var labels = [];
var descrip = [];
var locale = [];
for(i=0;i<obj.length;i++) {
pointLoc.push({lat: obj[i].lat, lng: obj[i].lng});
labels.push(obj[i].con);
descrip.push(obj[i].description);
locale.push(obj[i].location);
}
map.data.loadGeoJson();
for (var i = 0; i < pointLoc.length; i++) {
var coords = pointLoc[i];
var latLng = new google.maps.LatLng(coords.lat,coords.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
var contentStr = '<div id="popcontent">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">'+descrip[i]+'</h1>'+
'<p>'+locale[i]+', '+labels[i]+'</p>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({
maxWidth: 300
});
google.maps.event.addListener(marker,'click', (function(marker,contentStr,infowindow){
infowindow.close();
return function() {
infowindow.setContent(contentStr);
infowindow.open(map, marker);
};
})(marker,contentStr,infoWindow));
}
}
Stephen's answer identifies the problem with the infowindow. I want to help you learn to write simpler code.
There is a lot of complication in this code that you don't need; in fact you can get rid of most of the code!
The code first converts the locs array to a very similar obj array that has a couple of fields renamed.
Then it converts this obj array to four individual arrays pointLoc, labels, descrip, and locale.
None of this conversion is needed.
Also, when naming an array, I recommend using a plural name for the array and the singular form of that name for an element of the array. You did this in some places, just not consistently.
There is a map.data.loadGeoJson(); call that doesn't do anything because no URL is provided.
You also don't need the function-that-returns-a-function in the click listener, if you provide a closure in a simpler way as in the code below.
Here's an example of how you could do the whole thing in a much simpler manner:
d3.csv( '/data/locs.csv', function( places ) {
var infoWindow;
var map = new google.maps.Map( document.getElementById('googleMap'), {
center: { lat: 39.8283, lng: -98.5795 },
zoom: 2
});
places.forEach( function( place ) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng( place.lat, place.long ),
map: map
});
google.maps.event.addListener( marker, 'click', function() {
if( infoWindow ) infoWindow.close();
var content =
'<div id="popcontent">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">' + place.description + '</h1>' +
'<p>' + place.location + ', ' + place.country + '</p>' +
'</div>';
infoWindow = new google.maps.InfoWindow({
maxWidth: 300,
content: content
});
infoWindow.open( map, marker );
});
});
});
Your variable infoWindow goes out of scope when returning a function, and you not modifying the outer infoWindow, but the one passed into the function. Try this.
d3.csv('/data/locs.csv', function(locs){
var obj = [];
for(i=0;i<locs.length;i++) {
var country = locs[i].country;
var location = locs[i].location;
var lat = locs[i].lat;
var long = locs[i].long;
var description = locs[i].description;
obj.push({
con: country,
location: location,
lat: lat,
lng: long,
description: description
});
}
console.log(obj);
initMap(obj)
});
function initMap(obj, error) {
if (error){console.log("Error: "+error)}
var openInfoWindow = null;
var mapProp = {
center: {lat: 39.8283, lng: -98.5795},
zoom: 2
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var pointLoc = [];
var labels = [];
var descrip = [];
var locale = [];
for(i=0;i<obj.length;i++) {
pointLoc.push({lat: obj[i].lat, lng: obj[i].lng});
labels.push(obj[i].con);
descrip.push(obj[i].description);
locale.push(obj[i].location);
}
map.data.loadGeoJson();
for (var i = 0; i < pointLoc.length; i++) {
var coords = pointLoc[i];
var latLng = new google.maps.LatLng(coords.lat,coords.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
var contentStr = '<div id="popcontent">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">'+descrip[i]+'</h1>'+
'<p>'+locale[i]+', '+labels[i]+'</p>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({
maxWidth: 300
});
google.maps.event.addListener(marker,'click', (function(marker,contentStr,infowindow){
infowindow.close();
return((function(infowindow) {
infowindow.setContent(contentStr);
infowindow.open(map, marker);
})(infowindow));
})(marker,contentStr,infoWindow));
}
}
I was able to handle it easily with jQuery trigger event.
jQuery('.gm-ui-hover-effect').trigger('click');
Just put above code inside addListener function of marker and don't forget to include jQuery in your script.
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 +"'"+')
i am writing a certain code for showing multiple marker the google map. I Put all the value in a ListBox and trying read value in a loop and put it in map. I also write javascript. But While i am reading through loop some error occours. i am writing windows form application .
Dim lat, lon As String
Dim finalstr As String
Dim latlongroup As String
For i As Integer = 0 To ListBox1.Items.Count - 1
Dim tempstr = ListBox1.Items.Item(i)
If tempstr <> " " Then
tempstr = ListBox1.Items(i)
End If
latlongroup = "{" & "tempstr:" & tempstr & " }"
latlongroup = latlongroup & " , " & "{" & "tempstr:" & tempstr & " }"
finalstr = tb1.Text & vbCrLf & latlongroup
finalstr = finalstr & tb2.Text
Me.WebBrowser1.DocumentText = finalstr
Next
the java script part is
var markers = [
];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var i = 0;
var interval = setInterval(function () {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var icon = "red";
icon = "http://maps.google.com/mapfiles/ms/icons/" + icon + ".png";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title,
animation: google.maps.Animation.DROP,
icon: new google.maps.MarkerImage(icon)
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
latlngbounds.extend(marker.position);
i++;
if (i == markers.length) {
clearInterval(interval);
var bounds = new google.maps.LatLngBounds();
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
}
}, 80);
}
My markers are generated from xml parser. Its working and showing eg 7 markers, but when I added MC then it shows only 1 marker.
Check my js.
Maybe it problem is here? markers.push(marker); ?
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(52.6145, 21.3418);
var mapOptions = {
zoom: 6,
center: chicago
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("db/parse_xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var cover = markers[i].getAttribute("cover");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<div id='infobox'><img src='" + cover + "'/><b>" + name + "</b><br>" + address + " <br/><input type='button' id='end' onClick=calcRoute() name='" + name + "," + address + "' value='Wyznacz trasÄ™'></div>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
document.getElementById('pasekBoczny').innerHTML += '<li class="list-sidebar" ><a href="javascript:myclick(' + i + ')" >' + name + '</a></li>';
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
});
}
markers is a DOMNodeList, which doesn't have a method push
Create an array and populate the array with the google.maps.Marker's
var markers = xml.documentElement.getElementsByTagName("marker"),
markerArray=[];
for (var i = 0; i < markers.length; i++) {
/**
* your code
**/
//markers.push(marker);<--error, remove it, currently the script will stop here
markerArray.push(marker);//add this instead
}
var markerCluster = new MarkerClusterer(map, markerArray);