cmit cmit - 2 months ago 8
Javascript Question

Getting marker customInfo by marker id in google maps

I need to open info window on map, when I click a link on the map page( not marker it self). Here is my code so far,

var marker = new MarkerWithLabel({
map: resultsMap,
id: label,
position: latlng,
title: "Address",
// radius: int_radius ,
draggable: false,
labelAnchor: new google.maps.Point(10, 35),
labelContent: label,
labelClass: "labels",
labelInBackground: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
icon: image,
customInfo: "dynamic data for each marker"
});


And calling function

function bindInfoWindow(resultsMap, marker, infoWindow) {
google.maps.event.addListener(marker, 'click',
function(){
infoWindow.setContent(marker.customInfo);
infoWindow.open(resultsMap,marker);
});

$(document).on('click','.store-title', function(){
var linkId = $(this).attr('id');
infoWindow.setContent(marker.customInfo);
infoWindow.open(resultsMap,marker);

});
}


In my situation I can't use an array to store markers. Is there way to get marker.customInfo by using condition like below? Please Note When I click on marker it works. I need it for latter onclick function.

infoWindow.setContent(marker.customInfo where marker.id==linkId);

Answer

This might work, keeping it inside your bindInfoWindow as you currently have it:

$(document).on('click','.store-title', marker, function(event) { 
    var linkId = $(this).attr('id');
    if (linkId == event.data.marker.id) {
        google.maps.event.trigger(event.data.marker, 'click');
    }
});

Notice I'm passing the marker as a data parameter to the click event handle, but you maybe don't need to do that.

And then I just trigger the click on that marker, rather than repeat the code that you've already got in the marker's click handler.

I'm assuming the id property you're adding to each marker is the same as the 'id' attribute you're reading on your links. If not, can you have some identical property on the markers and links that you can check.

Comments