I really searched everywhere but I can't find my mistake in my code. I have information that is dynamical loaded into a checkbox (I only have one checkbox on my html) because I do not know at advanced how many checkboxes I will need...
This is my code to check if my checkbox is checked, and what is in it. The value is lat,lng and title
$(".chkbx").on("change", function() {
var selected = new Array();
//marker.setVisible(false);
//map.removeOverlay(marker);
//marker.setMap(null);
$("input:checkbox[name=checkbox]:checked").each(function() {
selected.push($(this).val());
});
console.log(selected);
for(var i=0; i< selected.length ;i++)
{
var current = selected[i].split(';');
var blueIcon = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&' + 'chco=FFFFFF,008CFF,000000&ext=.png';
var siteLatLng = new google.maps.LatLng(current[0], current[1]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
icon: blueIcon,
animation: google.maps.Animation.DROP,
title: current[2],
//zIndex: sites[3],
html: current[2]
});
marker.setMap(map);
}
}
});
My markers show on my google map but it is impossible to remove them ... can someone please help me or suggest something?
So for each selected checkbox you create a marker. What you need to do is add those markers into an array that you can then reference later.
// global variable
var markers = [];
$(".chkbx").on("change", function() {
var selected = [];
// loop through all the markers, removing them from the map:
for (var marker in markers) {
marker.setMap(null);
}
// then you probably want to clear out the array, so you can then re-insert markers to it
markers = [];
$("input:checkbox[name=checkbox]:checked").each(function() {
selected.push($(this).val());
});
for(var i=0; i< selected.length ;i++)
{
var current = selected[i].split(';');
var blueIcon = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&' + 'chco=FFFFFF,008CFF,000000&ext=.png';
var siteLatLng = new google.maps.LatLng(current[0], current[1]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
icon: blueIcon,
animation: google.maps.Animation.DROP,
title: current[2],
html: current[2]
});
// you don't need this setMap here, you already specified map in your mapOptions:
// marker.setMap(map);
markers.push(marker);
}
});
Related
in an app building environment I'm trying to use this code:
var map = new Appery('googlemap').gmap;
var markerLatLng = new google.maps.LatLng(localStorage.getItem("markerLat"), localStorage.getItem("markerLng"));
var Titolo = 'Some Title';
var markers = [];
var marker = new google.maps.Marker({
position: markerLatLng,
map: map,
title: Titolo,
animation: google.maps.Animation.DROP
});
markers.push(marker);
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
google.maps.event.addListener(marker, 'click', function() {markers.pop();
map.refresh();
setAllMap(map);
});
but it doesn't works. Could anyone say me why? I just want to remove the last marker that the user made by clicking on any marker she/he wants.
Thank you
Removing the marker object from the array will not remove the marker from the map. You have to call setMap(null) on the marker to do so. Just do markers[markers.length -1].setMap(null) and then pop() on the array;
I use gmap for geolocation, i.e. to set markers on a google map on specific positions.
Now what I want to achieve is to set markers and as soon as a user clicks on one of these markers, a info window opens and shows specific text. Every marker has its own text.
Now the problem is that I can't determine which marker the user has clicked and therefore can't set the right text.
Here's a code snippet:
//**Global variables**/
var thingsOfInterest = new Array(new Array(), new Array(),new Array());
var map = null;
//End Global variables
//init google map
function initGoogleMaps(){
map = new google.maps.Map(document.getElementById("map_canvas"));
var centerMap = new google.maps.LatLng(48.337881,14.320323);
$('#map_canvas').gmap({'zoom':7,'center': centerMap});
$('#map_canvas').gmap('option', 'zoom', 10);
//This is not working on my ios-simulator, no idea why. Anyway....
forge.geolocation.getCurrentPosition(function(position) {
alert("Your current position is: "+position);
}, function(error) {
});
}
/*End init map*/
/*Set the markers on the map*/
function setMarkers() {
/* thingsOf Interest contains:
* thingsOfInterest[i][0] -> the text that the marker should hold
* thingsOfInterest[i][1] -> the latitude
* thingsOfInterest[i][2] -> the longitude
*/
for (var i = 0; i < thingsOfInterest.length; i++) { //Iterate through all things
var item = thingsOfInterest[i]; //get thing out of array
var itemLatLng = new google.maps.LatLng(item[1], item[2]);
$('#map_canvas').gmap('addMarker', {'position': new google.maps.LatLng(item[1],item[2]) } ).click(function(e) {
$('#map_canvas').gmap('openInfoWindow', {'content': 'dummyContent'}, this); ///////SET REAL CONTENT HERE
});
}
}
Now this works all great, but what I miss is to get the marker the user has clicked on in the function()-eventHandler. If I could get the specific marker, I could set the text on it.
I hope this is clear enough.
Any help is very appreciated.
Thanks,
enne
Assuming your code with dummy text is working, you can pass your text right away..
$('#map_canvas').gmap('addMarker', {'position': new google.maps.LatLng(item[1],item[2])})
.click(function(e) {
$('#map_canvas').gmap('openInfoWindow', {'content': item[0]}, this);
});
Or another approach would be:
function setMarkers() {
for (var i = 0; i < thingsOfInterest.length; i++) {
var item = thingsOfInterest[i];
var itemLatLng = new google.maps.LatLng(item[1], item[2]);
var marker = new google.maps.Marker({ position: itemLatLng, map: map });
google.maps.event.addListener(marker, 'click', function () {
var infowindow = new google.maps.InfoWindow({ content: item[0] });
infowindow.open(map, marker);
});
}
}
I do not know what to do... I just want to close all opened infoBubbles if I'm going to open a new one. I am using the following code. Ideas? I tried a lot and googled a lot but it shouldn't be so complicated, should it? I thought to create an array and save id for the open one, but I think that there must be another, quite easier way to fix this.
$(document).ready(function(){
createmap();
function createmap(lat,lng){
var latlng = new google.maps.LatLng(50, 10);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
bounds = new google.maps.LatLngBounds();
createMarker();
}
function createMarker(){
var markers = [];
var cm = window.cm = new ClusterManager(
map,
{
objClusterIcon: new google.maps.MarkerImage('images/map/flag_cluster.png', false, false, false, new google.maps.Size(20,20)),
objClusterImageSize: new google.maps.Size(20,20)
}
);
var json = [];
var x1 = -85;
var x2 = 85;
var y1 = -180;
var y2 = 180;
for (var i=0; i<20; ++i) {
json.push(
'{'+
'"longitude":'+(x1+(Math.random()*(x2-x1)))+','+
'"latitude":'+(y1+(Math.random()*(y2-y1)))+','+
'"title":"test"'+
'}'
);
}
json = '['+json.join()+']';
// eval is ok here.
eval('json = eval(json);');
infos = [];
$.each(json, function(i,item){
var contentString = '<div id="content"><a onclick="createdetailpage('+i+');">'+item.title+'<br /></a></div>';
console.log(item.latitude);
var myLatlng = new google.maps.LatLng(item.latitude,item.longitude);
var marker = new google.maps.Marker({
position: myLatlng,
//map: map,
flat: true,
title:item.title,
//animation: google.maps.Animation.DROP,
//icon: myIcon
});
var infoBubble = new InfoBubble({
content: '<div class="phoneytext">'+contentString+'</div>'
});
google.maps.event.addListener(marker, 'click', function() {
if (!infoBubble.isOpen()) {
infoBubble.open(map, marker);
}
});
cm.addMarker(marker, new google.maps.Size(50, 50));
});
map.fitBounds(bounds);
}
});
The simplest approach to only have one infoBubble open is to only have one infoBubble and open it with different contents depending on the marker that is clicked.
InfoWindow example with custom markers (same concept applies to InfoBubble)
The InfoBubble is an OverlayView. As far as I can see, an overlaycomplete event is emitted when an overlay is added. Maybe all your InfoBubbles could listen to that event and close if the added overlay is a different one than "this".
It's just a thought, though, I haven't tried it myself. Feedback appreciated if you try it out!
This is my html code. I've try anything to add an infowindow on the markers but it don't wanna work. My data is loading from the "Alle_Ortswahlen.page1.xml" file.
Do anyone have an idea how can I add infoWindow to each marker?
<script type="text/javascript">
google.load('maps', '3', {
other_params: 'sensor=false'
});
google.setOnLoadCallback(initialize);
function initialize() {
var stack = [];
var center = new google.maps.LatLng(48.136, 11.586);
var options = {
'zoom': 5,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
}
</script>
Before the for cycle, make an empty infowindow object.
var infowindow = new google.maps.InfoWindow();
Than in the for cycle, after the marker, add an event listener, like this:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("You might put some content here from your XML");
infowindow.open(map, marker);
}
})(marker, i));
There is some closure magic happening when passing the callback argument to the addListener method. If you are not familiar with it, take a look at here:
Mozilla Dev Center: Working with Closures
So, your code should look something like this:
google.load('maps', '3', {
other_params: 'sensor=false'
});
google.setOnLoadCallback(initialize);
function initialize() {
var stack = [];
var center = new google.maps.LatLng(48.136, 11.586);
var options = {
'zoom': 5,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
var infowindow = new google.maps.InfoWindow();
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("You might put some content here from your XML");
infowindow.open(map, marker);
}
})(marker, i));
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
}
So what you need to do is add some code, inside your for-loop, associating an infowindow onclick event handler with each marker. I'm assuming you only want to have 1 infowindow showing at a time, i.e. you click on a marker, the infowindow appears with relevant content. If you then click on another marker, the first infowindow disappears, and a new one reappears attached to the other marker. Rather than having multiple infowindows all visible at the same time.
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
// just create one infowindow without any content in it
var infowindow = new google.maps.InfoWindow({
content: ''
});
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
// add an event listener for this marker
google.maps.event.addListener(marker , 'click', function() {
// assuming you have some content in a field called Field123
infowindow.setContent(markers[i].getAttribute("Field123"));
infowindow.open(map, this);
});
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
I've got this problem when removing a Marker from an array. I click on the map and place markers where i have clicked, the markers are then saved in an array. When removing them it only works in the order i have placed them but backwards, that means i place 1 2 3 but have to remove them like 3 2 1.
If i try to remove the markers in random order, the first one is removed, but then the others just stop working, the listener still works, but it seems like the forloop doesnt find the other markers in the array.
Any ideas? I'm completely lost.
Here is the code:
var map;
var tempLatLng;
var zoomLevel;
var markers = [];
var zoomLevels = [];
var count = -1;
var nullLatlng = new google.maps.LatLng(84.52,45.16);
var nullMarker = new google.maps.Marker({
position: nullLatLng,
});
function initialize() {
var myLatlng = new google.maps.LatLng(55.605629745598904,13.000441789627075);
var myOptions = {
zoom: 17,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel:false
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//Puts a listener on the map, when clicking on the map, it places a marker.
google.maps.event.addListener(map, 'click', function(event) {
zoomLevel = map.getZoom();
document.getElementById("zoom").value = zoomLevel;
tempLatLng = event.latLng;
setTimeout("placeMarker(tempLatLng)", 800); //placeMarker is called with a duration so that //doubleclicking doesn't bother the placement.
});
}
//Function to place markers.
function placeMarker(location) {
if(zoomLevel == map.getZoom()){
if(true){
var marker1 = new google.maps.Marker({
position: location,
map: map,
draggable:true
});
count = count + 1;
markers[count] = marker1;
document.getElementById("count").value = count;
google.maps.event.addListener(marker1,'rightclick', function(event){
document.getElementById("test2").value = "funkar";
for(var i = 0 ;i < markers.length ;i++){
if(markers[i].getTitle() == marker1.getTitle()){
marker1.setMap(null);
document.getElementById("markerpos").value = markers[i].getTitle();
document.getElementById("test1").value = markers[i].getTitle();
count = count - 1;
document.getElementById("count").value = count;
markers[i] = nullMarker;
}
}
});
marker1.setTitle(location.toString());
}
map.setCenter(location);
}
}
Here is the JSFiddle Demo:
Basically, you were using var count to keep track of the number of markers. You can do markers.length for that. Instead of using markers[count] you can use native array's push method to add element into the array. To remove use splice(i, 1); where i is the element's position and remove 1 element from that position. Also, to check if two markers are equal or the "same" instead using getTitle() use === which does:
is exactly equal to (value and type)
The problem is if you create two or more markers on the same position it would remove both markers but in reality you only remove one of the two "clones" and thus leaving a marker un-removable. This is caused by using getTitle which returns lat lng and if you have two markers w/ same lat lng you have an issue. Also, i changed, within your onclick function, marker1 to this which are referring to the same object for readability.
//Function to place markers.
function placeMarker(location) {
if (zoomLevel == map.getZoom()) {
if (true) {
var marker1 = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
count = count + 1;
markers.push(marker1);
document.getElementById("count").value = markers.length;
google.maps.event.addListener(marker1, 'rightclick', function(event) {
document.getElementById("test2").value = "funkar";
for (var i = 0; i < markers.length; i++) {
if (markers[i] === this) {
this.setMap(null);
document.getElementById("markerpos").value = markers[i].getTitle();
document.getElementById("test1").value = markers[i].getTitle();
markers.splice(i, 1);
document.getElementById("count").value = markers.length;
}
}
});
marker1.setTitle(location.toString());
}
map.setCenter(location);
}
}