I have a map where I want to add a marker (with info window) via a checkbox. It also works quite well, but I just can not get it deleted again when I uncheck the checkbox. Can anyone help?
See also here: http://jsfiddle.net/x8D7y/
function clearOverlays() {
google.maps.event.clearListeners(marker300, 'click');
}
function showOverlays() {
var marker300 = new google.maps.Marker({
position: new google.maps.LatLng(45.0, 1.0),
map: map /*,
icon: 'img/bike5.png' */
});
var infowindow300 = new google.maps.InfoWindow({
content: '<div style="width: 200px;">Test 300 - Link</div>'
});
google.maps.event.addListener(marker300, 'click', function() {
infowindow300.open(map, marker300);
});
}
You have to use an external Array which holds the extra markers you use with the map. In your case I have added the following array:
var extraMarkers = [];
Then when I click the checkbox, I am getting the ID of that checkbox, and send it in both showOverlays() and clearOverlays() as function argument.
Then, in showOverlays(), I am using the checkbox ID as extraMarkers key and the marker as value.
Finally, in clearOverlays() I use again the checkbox ID to get the element with this ID from the extraMarkers array and I see the map to null, in order to remove the marker.
See here the working example : http://jsfiddle.net/x8D7y/1/
Here is the full code required by you:
var map;
var extraMarkers = [];
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(45.0, 1.0)
};
map = new google.maps.Map($('#map')[0], myOptions);
var marker1 = new google.maps.Marker(
{
position: new google.maps.LatLng(45.5, 1.5),
map: map /*,
icon: 'img/bike5.png' */
}
);
var infowindow1 = new google.maps.InfoWindow(
{
content: '<div style="width: 200px;">Test 1 - Link</div>'
}
);
google.maps.event.addListener(
marker1,
'click',
function()
{
infowindow1.open(map, marker1);
}
);
function clearOverlays(myID)
{
google.maps.event.clearListeners(extraMarkers[myID], 'click');
extraMarkers[myID].setMap(null);
}
function showOverlays(myID)
{
var marker300 = new google.maps.Marker(
{
position: new google.maps.LatLng(45.0, 1.0),
map: map /*,
icon: 'img/bike5.png' */
}
);
extraMarkers[myID] = marker300;
var infowindow300 = new google.maps.InfoWindow(
{
content: '<div style="width: 200px;">Test 300 - Link</div>'
}
);
google.maps.event.addListener(
marker300,
'click',
function()
{
infowindow300.open(map, marker300);
}
);
}
$('#mapall').change(
function()
{
var myID = $(this).attr('id');
if($('#mapall').attr('checked'))
{
showOverlays(myID);
}
else
{
clearOverlays(myID);
}
}
);
if you have single marker on map then use marker.setMap(null);
if Multiple marker make an array for marker
markersArray.push(marker);
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
Try this:
marker300.setMap(null);
Your marker was not visible outside of showOverlays() function. Error was reported in console:
Uncaught ReferenceError: marker300 is not defined
Minimum change is to define marker300 as global:
var map;
var marker300;
and delete marker in
function clearOverlays() {
google.maps.event.clearListeners(marker300, 'click');
marker300.setMap(null);
}
and remove var in front of variable marker300 in function showOverlays()
See example in fiddle
If you want to have several markers than you will have to follow solution from user Merianos Nikos
Related
I have a simple Google Maps feat I'm trying and failing to accomplish.
Presently, I can display my map, then cycle through a list of Projects via PHP (I'm using ExpressionEngine), and add each project's latitude/longitude to a JavaScript array.
Once the values are in the JavaScript array, I use jQuery to cycle through each one, and add a marker to the map.
I'm able to click the map and have it respond appropriately; however, when I attempt to click one of the markers, nothing happens at all.
I have tried moving code, renaming, changing, editing, and tweaking endlessly... I cannot figure this out. Any help at all would be hugely appreciated. My code is as follows:
<script>
// Create the new map_locations array
var map_locations = [];
</script>
<!-- The following ExpressionEngine script loops through all the 'projects' on the site,
then pushes each project to the map_locations array. -->
{exp:channel:entries channel="projects"}
<script>
map_locations.push( ['{url_title}', '{project_latitude}', '{project_longitude}', '{categories}{category_name}{/categories}', '{title}'] );
</script>
{/exp:channel:entries}
<script>
var marker;
function initialize() {
// To add the marker to the map, use the 'map' property
var mapOptions = {
center: { lat: 51.884 , lng: -95.147 },
zoom: 4
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Create a new location lat/long var, newLatLng
var newLatLng;
var contentString = "<div id='info_window'>this is the info window</div>"
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var iconBase = '/images/map_icon_';
$.each( map_locations, function()
{
newLatLng = new google.maps.LatLng( this[1] , this[2] );
marker = new google.maps.Marker({
position: newLatLng,
map: map,
title: this[4],
icon: iconBase + this[3]
});
});
google.maps.event.addListener(marker, 'click', function() {
console.log( "This marker's url_title is: " + this[0] );
});
google.maps.event.addListener(map, 'click', function() {
console.log( "Testing map click" );
});
}
// Initialize the map
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You are trying to add event listener for markers after the loop where marker gets defined rather than in the loop
Try:
$.each( map_locations, function(){
var newLatLng = new google.maps.LatLng( this[1] , this[2] );
var marker = new google.maps.Marker({
position: newLatLng,
map: map,
title: this[4],
icon: iconBase + this[3]
});
google.maps.event.addListener(marker, 'click', function(marker) {
console.log( "This marker's url_title is: " + marker.title );
});
});
I am building a search form using Google Maps Javascript V3 API. I would like to add some filters that will hide certain types of markers on the map when clicked. The markers to hide are represented with
locations[i][11] == 'Other'
HTML:
Hide Other Markers
JavaScript:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
};
var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var locations = <?php echo json_encode($locations_array); ?>;
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var content = '';
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addDomListener(document.getElementsByClassName('hideOtherMarkers')[0], 'click', function() {
if (locations[i][11] == 'Other') {
marker.setVisible(false); // maps API hide call
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
When I click the link nothing fires, verified with alerts. I also tried google.maps.event.addListener (without Dom) with no success.
As commented by geocodezip this approach will not work, because i will always point behind the end of locations. Additionally this would hide at best 1 marker (the last marker that has been created).
Possible approach:
Store the visible-state of the markers in a MVCObject:
map-options:
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
//that's the property where we store the state
visibility:new google.maps.MVCObject
};
inside the loop, after the creation of marker:
//when the state is not set yet, set it
if(typeof map.get('visibility').get(locations[i][11])==='undefined'){
map.get('visibility').set(locations[i][11],true);
}
//bind the visible-property of the marker to the state
marker.bindTo('visible',map.get('visibility'),locations[i][11]);
add the listener(outside of the loop):
google.maps.event.addDomListener(
document.getElementsByClassName('hideOtherMarkers')[0],
'click',
function() {
//simply set the desired property of the MVCObject to false
map.get('visibility').set('Other',false);
});
Demo: http://jsfiddle.net/doktormolle/5L2392mL/
I have add the following code to a Google Map on a site of mine. The map contains many points pulling from coordinates set in the WordPress backend.
I also want to include some static points which will always stay on the map and am hardcoding their coordinates.
The following is the code I am using and what happens is that the code displays the first marker but not the infobox. Because of this, the code stops and does not continue through the for loop. The issue is at the return function() bit, but I am not sure how to get it working.
var infowindow = new google.maps.InfoWindow({maxWidth: 185});
var setMarker;
var setMarkers = new Array();
var setLocations = [
['<h4>Location1</h4>', 53.4264,-6.2499, '/wp-content/themes/path/to/airport_icon.png'],
['<h4>Location2</h4>', 53.3461,-6.2969, '/wp-content/themes/path/to/train_icon.png'],
['<h4>Location3</h4>', 53.3532,-6.2468, '/wp-content/themes/path/to/train_icon.png'],
['<h4>Location4</h4>', 53.4264,-6.2499, '/wp-content/themes/path/to/dvc_icon.png'],
['<h4>Location5</h4>', 53.4264,-6.2499, '/wp-content/themes/path/to/dvc_icon.png'],
];
for (var i = 0; i < setLocations.length; i++) {
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(setLocations[i][1], setLocations[i][2]),
icon : setLocations[i][3],
});
setMarkers.push(setMarker);
google.maps.event.addListener(setMarker, 'click', (function(setMarker, i) {
return function() {
infowindow.setContent(setLocations[i][0]);
infowindow.open(map, setMarker);
}
})(setMarker, i));
}
Define your setMarker variable inside the for loop and push it to your markers array:
for (var i = 0; i < setLocations.length; i++) {
var setMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(setLocations[i][1], setLocations[i][2])
});
google.maps.event.addListener(setMarker, 'click', (function (setMarker, i) {
return function () {
infowindow.setContent(setLocations[i][0]);
infowindow.open(map, setMarker);
}
})(setMarker, i));
setMarkers.push(setMarker);
}
JSFiddle demo
I'm trying to make a map-based application, but I'm having bit of difficulty. The original code I had been working with added a separate InfoWindow for each marker, but I'd like to get it using a single InfoWindow for which I can set the content on the fly.
However, I still seem to be a little fuzzy on how JavaScript behaves, because each time any marker is clicked the InfoWindow pops up over the last marker and the alert indicates the ID of the last entry in locations.
Short snippet, problem highlighted:
function plotLocations(my_locations) {
locations = my_locations;
for(var i=0; i<locations.length; i++) {
var pos = new google.maps.LatLng(locations[i].loc_lat, locations[i].loc_lng);
var icon = new google.maps.MarkerImage(
"http://goo.gl/TQpwU",
new google.maps.Size(20,32),
new google.maps.Point(0,0),
new google.maps.Point(0,32)
);
var marker = new google.maps.Marker({
map: map,
position: pos,
animation: google.maps.Animation.DROP,
icon: icon
});
// ! -- trouble right here -- ! //
google.maps.event.addListener(marker, 'click', function() {
setPopInfo(pos, i);
});
// ! -- ------------------ -- ! //
}
}
function setPopInfo(pos, index) {
pop_info.setPosition(pos);
pop_info.open(map);
window.alert(pos+"::"+index);
}
Most of the rest of my code:
var map;
var mapBounds;
var locations;
var pop_info;
$(document).ready(init);
function init() {
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
pop_info = new google.maps.InfoWindow({
content: "I'm not populated!",
size: new google.maps.Size(100,25)
});
google.maps.event.addListener(map, 'bounds_changed', function() {
queryLocations(map.getBounds());
});
prepareGeolocation();
doGeolocation();
}
function queryLocations(bounds) {
jQuery.ajax({
url: 'http://mydomain.com/myapp/test2.php',
data: bounds.toString(),
dataType: 'json',
success: addLocations
});
}
function addLocations(new_locations) {
document.getElementById('footer').innerHTML = new_locations;
plotLocations(new_locations);
}
My reasoning for the single InfoWindow is that once a few hundred Markers and InfoWindows have been created the performance might take a nosedive. Is what I'm trying to do feasible/advisable?
The problem occurs because you're defining your event listener callback function inside the loop. Closures refer to their context dynamically rather than binding to a copy of the data at the time of definition, so you have effectively created locations.length number of functions that are all bound to the same values of marker, pos and i, which are whatever they happened to be when the loop terminated.
To work round this, you could create a function that calls addListener outside the body of the loop, like so:
function plotLocations (my_locations) {
locations = my_locations;
for(var i=0; i<locations.length; i++) {
var pos = new google.maps.LatLng(locations[i].loc_lat, locations[i].loc_lng);
var icon = new google.maps.MarkerImage(
"http://goo.gl/TQpwU",
new google.maps.Size(20,32),
new google.maps.Point(0,0),
new google.maps.Point(0,32)
);
var marker = new google.maps.Marker({
map: map,
position: pos,
animation: google.maps.Animation.DROP,
icon: icon
});
bindEvent(marker, pos, i);
}
}
function bindEvent (marker, pos, i) {
google.maps.event.addListener(marker, 'click', function() {
setPopInfo(pos, i);
});
}
I've seen the other posts, but they dont have the markers being looped through dynamically like mine. How do I create an event that will close the infowindow when another marker is clicked on using the following code?
$(function(){
var latlng = new google.maps.LatLng(45.522015,-122.683811);
var settings = {
zoom: 10,
center: latlng,
disableDefaultUI:false,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var map = new google.maps.Map(document.getElementById("map_canvas"), settings);
$.getJSON('api',function(json){
for (var property in json) {
if (json.hasOwnProperty(property)) {
var json_data = json[property];
var the_marker = new google.maps.Marker({
title:json_data.item.headline,
map:map,
clickable:true,
position:new google.maps.LatLng(
parseFloat(json_data.item.geoarray[0].latitude),
parseFloat(json_data.item.geoarray[0].longitude)
)
});
function buildHandler(map, marker, content) {
return function() {
var infowindow = new google.maps.InfoWindow({
content: '<div class="marker"><h1>'+content.headline+'</h1><p>'+content.full_content+'</p></div>'
});
infowindow.open(map, marker);
};
}
new google.maps.event.addListener(the_marker, 'click',buildHandler(map, the_marker, {'headline':json_data.item.headline,'full_content':json_data.item.full_content}));
}
}
});
});
I finally figured it out... no thanks to anyone here... It was actually fairly easy:
First, set up some vars to store the infowindow:
var infowindow;
Then add this to wherever your onClick function is that triggers the other infowindow.open(). Put it above the open though:
if(infowindow) {infowindow.close()}
Inside your loop or however else you are adding markers.
E.g. in full action:
At the very top of my script:
var infowindow;
Inside my loop of adding markers:
function buildHandler(map, marker, content) {
return function() {
if(infowindow) {infowindow.close()}
infowindow = new google.maps.InfoWindow({
content: 'My Content here'
});
infowindow.open(map, marker);
};
}