Event click dynamic variable - javascript

Hi all I have a site where I use google maps.
The problem is: I add some marker into the map adn i want that every marker if clicked, alert me its data.
With my code alert only the last (test9) because the variable is the same. How to add a listener of a dynamic variable?
This is my code:
for (i = 0; i<10; i++){
myLatlng = new google.maps.LatLng((44.900)+(i/10), 11.634521);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"+i,
data:"test"+i
});
google.maps.event.addListener(marker, 'click', function() {
alert(marker.data);
});
}

Ok try adding a new function such as addMarkerFunction(marker)
such as
function addMarkerFunction(marker){
google.maps.event.addListener(marker, 'click', function() {
alert(marker.data);
});
}
Then edit your for loop code to be :
for (i = 0; i<10; i++){
myLatlng = new google.maps.LatLng((44.900)+(i/10), 11.634521);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"+i,
data:"test"+i
});
addMarkerFunction(marker);
}
removing the call to google.maps.event.addListener

Related

Google maps add infowindow to marker

Hi i building a store locator and i found this code online its workind fine
function generateMarkers(points) {
//var iconBase = "https://media.nisbets.com/static/content/banners/";
for (var i = 0; i < points.length; i++) {
var place = points[i];
var myLatLng = new google.maps.LatLng(place[0], place[1]);
var marker = new google.maps.Marker({
position: myLatLng,
name: place[2],
clickable: true,
map: map,
icon: /*iconBase + */"nisbets_storelocator_marker.png",
url: place[3]
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
setMapBounds(marker.getPosition());
markers.push(marker);
}
}
But instead of a link who redirect to a page i want a popup window with the place info inside the popup.
Please i need your help how to add the infoWindow to my code.
Thanks
Define a new InfoWindow
var infowindow = new google.maps.InfoWindow({
content: contentString
});
Add an event listener to each marker to open the InfoWindow.
marker.addListener('click', function() {
infowindow.open(map, marker);
});
Reference: https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple

How to access Google Maps markers after creating them dynamically?

I am creating markers for multiple points like this:
for (i = 0; i < locations.length; i++) {
console.log("Adding marker...");
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
draggable:true,
icon: locations[i][3]
});
google.maps.event.addListener(marker, 'dragend', function(){
console.log(marker.getPosition());
// This doesn't work :(
});
}
I then want to (with getPosition) access the positions (lat & long) of each marker when they are moved. How would I achieve that? There will most likely always be 2 markers on the map, so I would need to access marker 0 and marker 1 and log each of them when they are moved.
UPDATE 1:
I tried adding id: locations[i][0] to the marker and then accessing it with: console.log(marker.id); But that always returns the ID/name of the second marker, even if the first one is moved.
Use this inside the click listener to reference the marker thing that was clicked.
google.maps.event.addListener(marker, 'dragend', function(){
console.log(this.getPosition());
});
You store the markers into an array while creating them
var arr_marker=[];
for (i = 0; i < locations.length; i++) {
console.log("Adding marker...");
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
draggable:true,
icon: locations[i][3]
});
google.maps.event.addListener(marker, 'dragend', function(){
console.log(marker.getPosition());
// This doesn't work :(
});
arr_marker[] = marker;
}

Google Maps V3 Javascript: Event listener not being loaded

I don't seem to be able to make Google Maps click event listeners for markers to work. The only detail is that this is being run in a cycle, meaning that in the first time i include the map and run the add markers and their event listeners, the following times I have a function that only adds the markers and the listeners.
This is my initialize function and datasetRealtime is the array of markers:
function initialize() {
var mapOptions = {
zoom: 14,
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT
},
/* Map Zoom */
center: new google.maps.LatLng(41.186968, -8.697792),
/*Center Coordinate*/
mapTypeId: google.maps.MapTypeId.ROADMAP
}
realtime_map = new google.maps.Map(document.getElementById("map-canvasBig"), mapOptions);
for (var i = 0; i < datasetRealtime.length; i++) {
var latitude = parseFloat(datasetRealtime[i]["latitude"]);
var longitude = parseFloat(datasetRealtime[i]["longitude"]);
var myLatlng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: realtime_map,
title: 'Just some title'
});
google.maps.event.addListener(marker, 'click', function () {
console.log("it worked")
});
}
}
And I am loading it with:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=mykeygoeshere&sensor=false&callback=initialize";
document.body.appendChild(script);
This is the function that adds the markers and listeners if the map is already loaded:
function addMarkers(){
for (var i = 0; i < datasetRealtime.length; i++) {
var latitude = parseFloat(datasetRealtime[i]["latitude"]);
var longitude = parseFloat(datasetRealtime[i]["longitude"]);
var myLatlng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: realtime_map,
title: 'Just some title'
});
google.maps.event.addListener(marker, 'click', function () {
console.log("it worked")
});
}
}
Update
I am cleaning the markers before I add the new ones with:
function clearOverlays(datasetRealtime) {
for (var i = 0; i < datasetRealtime.length; i++) {
datasetRealtime[i].setMap(null);
}
datasetRealtime = [];
}
I've tried so many ways, even with closures and I don't seem to be able to make it work. The markers are added, but there's no handler when I click on them (the little hand stays wide open)
The proble might be you are rewriting marker at each for loop.
You have to store your markes in a markersArray object.
Your code will look something like this:
var markers = [];
function addMarkers(){
for (var i = 0; i < datasetRealtime.length; i++) {
var latitude = parseFloat(datasetRealtime[i]["latitude"]);
var longitude = parseFloat(datasetRealtime[i]["longitude"]);
var myLatlng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: realtime_map,
title: 'Just some title'
});
google.maps.event.addListener(marker, 'click', function () {
console.log("it worked")
});
markers.push(marker);
}
}
That might work!
May I suggest to you a code refactoring: since you have already an addMarkers method it could be simplier to call it in your initialize method than to rewrite the same code there.
Hi the below code will do for marker click also added a small code.. sry could'nt look into ur code fully still provided info that would help in solving..
var marker = new GMarker(location);
GEvent.addListener(marker, "click", function() {
alert('it works');
});
map.addOverlay(marker);

Info bubble always shows up on the last marker [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Google Maps - Multiple markers - 1 InfoWindow problem
I'm making a map where I plot some towns and places.
As you will see, when you click on a marker, you are redirected to the corresponding page. But now I would like to put the link and some other information in an info bubble popover. So, I've edit my code to this:
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var infobulle = new google.maps.InfoWindow({content: beach[4], position: myLatLng});
var marker = new google.maps.Marker({position: myLatLng, map: map, title: beach[0], zIndex: beach[3], clickable: true, icon: beach[5],});
marker[i] = marker;
google.maps.event.addListener(marker[i], 'click', function() {
infobulle.open(map, marker);
});
}
}
But as you can see here the info bubble stays "blocked" on the last location. I really don't know how to sort this.
I have the same result with this :
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var infobulle = new google.maps.InfoWindow({content: beach[4]});
var marker = new google.maps.Marker({position: myLatLng, map: map, title: beach[0], zIndex: beach[3], clickable: true, icon: beach[5]});
google.maps.event.addListener(marker, 'click', function() {
infobulle.open(map, marker);
});
}
Last version :
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
processBeach(locations[i]);
}
}
function processBeach(beach) {
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var infobulle = new google.maps.InfoWindow({content: beach[4]});
var marker = new google.maps.Marker({position: myLatLng, map: map, title: beach[0], zIndex: beach[3], clickable: true, icon: beach[5]});
google.maps.event.addListener(marker, 'click', function() {
infobulle.open(map, marker);
});
}
You are using the marker variable for two different purposes it seems. One is as a single marker, and one as an array of markers. But you don't need an array of markers, if you use closures. Try this:
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
(function(beach) {
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var infobulle = new google.maps.InfoWindow({content: beach[4], position: myLatLng});
var marker = new google.maps.Marker({position: myLatLng, map: map, title: beach[0], zIndex: beach[3], clickable: true, icon: beach[5]}))
google.maps.event.addListener(marker, 'click', function() {
infobulle.open(map, marker);
});
}(locations[i]));
}
}
By the way you also had a spurious comma at the end of the options array for google.maps.Marker which will cause problems in some browsers.
EDIT
If you don't want to use closures, this is equivalent:
function processBeach(beach) {
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var infobulle = new google.maps.InfoWindow({content: beach[4], position: myLatLng});
var marker = new google.maps.Marker({position: myLatLng, map: map, title: beach[0], zIndex: beach[3], clickable: true, icon: beach[5]}))
google.maps.event.addListener(marker, 'click', function() {
infobulle.open(map, marker);
});
}
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
processBeach(locations[i]);
}
}
Have a look at my jSFiddle here. The code you are missing is
On Click you need to fetch the current infoWindow from the map and then update it with new information
If you want to keep windows open and close when people want to close then you have to set a toggle kind of variable so each window will be created on click and then when someone click on close it will go away. But i think you only need to complete first part.
The code you should look in my fiddle is from line 120 to 150 which does check for infowindow if it exists and then do open the same window on new marker so it moves from old marker and go to new. if you keep creating new windows the old ones will not close magically.
var map = $(this).gmap3("get"),
infowindow = $(this).gmap3({get:{name:"infowindow"}}); // Get current info window
if (infowindow){ // if infoWindow is there then use it else create new
infowindow.open(map, marker);
infowindow.setContent(context.data.ht);
jQuery("#customPopup").html(context.data.ht);
jQuery("#customPopup").show(500);
} else {
$(this).gmap3({
infowindow:{
anchor:marker,
options:{content: context.data.ht}
}
});
jQuery("#customPopup").html(context.data.ht);
jQuery("#customPopup").show(500);
}

Google Maps Marker as a link

I have the following code, but it is not working, the link only is showed on the last point (Argentina), some help?
<div id="map" style="width: 980px; height: 420px;margin:10px 0px 30px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(0,0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var usa = new google.maps.LatLng(37.09024, -95.712891);
var brasil = new google.maps.LatLng(-14.235004, -51.92528);
var argentina = new google.maps.LatLng(-38.416097, -63.616672);
var marker = new google.maps.Marker({
position: usa,
url: '/destinos/exibir/pais_id/3',
title: 'Estados Unidos',
map: map
});
var marker = new google.maps.Marker({
position: brasil,
url: '/destinos/exibir/pais_id/2',
title: 'Brasil',
map: map
});
var marker = new google.maps.Marker({
position: argentina,
url: '/destinos/exibir/pais_id/1',
title: 'Argentina',
map: map
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = marker.url;
});
</script>
jsfiddle demo with modification augmenting #hsz example:
The problem is you have marker declared 3 times, and attach only click event on the one that is declared last. So, you must declare 3 different name for 3 different markers and attach each of them with onclick event. Better if you do it in an array or something
var markers = [];
markers[0] = new google.maps.Marker({
position: usa,
url: '/destinos/exibir/pais_id/3',
title: 'Estados Unidos',
map: map
});
markers[1] = new google.maps.Marker({
position: brasil,
url: '/destinos/exibir/pais_id/2',
title: 'Brasil',
map: map
});
markers[2] = new google.maps.Marker({
position: argentina,
url: '/destinos/exibir/pais_id/1',
title: 'Argentina',
map: map
});
for ( i = 0; i < markers.length; i++ ) {
google.maps.event.addListener(markers[i], 'click', function() {
window.location.href = this.url; //changed from markers[i] to this
});
}
You're giving each marker the same variable name, so I think the reference 'marker' will only point to the last one (Argentina).
You could try giving them separate names and binding the listener to each one separately.
Just adding this answer for future reference for anyone if they need it
Send the details to another createMarker function
createMarker(pos,title,weburl)
{
marker = new google.maps.Marker({
position: pos,
title: title,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = weburl;
});
}
Thanks Tom Elliott for pointing out the issue, i was using a logic similar to kjy112

Categories

Resources