0

OK, here is, what I'm doing at the Moment:

when loading the page, I do an Ajax request to get a json-object with location Informations.

with these informations i initialize the google map an set markers. Here is the Code:

    $(document).ready(function()  {

//--- Ajax Request ------------------------------------------------------------------------------------------------------------------------
            $.ajax({
                dataType: "json",
                url: "karte-e.php",
                success: function(msg) {
                    initialize(msg);
                }
            });
//--- Ende Ajax Request ------------------------------------------------------------------------------------------------------------------------                

//--- Funktionen Google Maps API ------------------------------------------------------------------------------------------------------------------------   
            function initialize(json) {
                var mapProp = {
                    center:new google.maps.LatLng(51.508742,-0.120850),
                    zoom:2,
                    mapTypeId:google.maps.MapTypeId.ROADMAP
                };
                map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
                setMarkers(map, json);


            }

            function setMarkers(map, locations) {

                    var image_normal = {
                        url: 'Pins/pin-blau.png',
                        size: new google.maps.Size(32, 32),
                        origin: new google.maps.Point(0,0),
                        anchor: new google.maps.Point(0, 32)
                    };

                    var image_neu = {
                        url: 'Pins/pin-rot.png',
                        size: new google.maps.Size(32, 32),
                        origin: new google.maps.Point(0,0),
                        anchor: new google.maps.Point(0, 32)
                    };

                    var shape = {
                        type: 'rect',
                        coords: [5, 1, 27, 32]
                    };


                    for (var i = 0; i < locations.Standorte.length -1; i++) {

                        var myLatLng = new google.maps.LatLng(locations.Standorte[i].lat, locations.Standorte[i].lng);
                        var marker_normal = new google.maps.Marker({
                            position: myLatLng,
                            map: map,
                            icon: image_normal,
                            shape: shape,
                            title: locations.Standorte[i].Titel,
                            zIndex: i
                        });
                    }

                    var myLatLng = new google.maps.LatLng(locations.Standorte[locations.Standorte.length - 1].lat, locations.Standorte[locations.Standorte.length - 1].lng);
                    var marker_neu = new google.maps.Marker({
                            position: myLatLng,
                            map: map,
                            icon: image_neu,
                            shape: shape,
                            title: locations.Standorte[locations.Standorte.length - 1].Titel,
                            zIndex: locations.Standorte.length - 1
                        });


                }
//--- Ende Funktionen Google Maps API ------------------------------------------------------------------------------------------------------------------------                      

            return false;
//--- Ende $(document).ready() ------------------------------------------------------------------------------------------------------------------------ 
});

what i want to do, is to create an event listener, which is triggered by a Mouse Click on a Marker. My Problem is, that i'm very new to jQuery and I don't know, where to put my google.maps.event.addListener(marker, 'click', function(){}. All my trys failed. Hope,you can help me.

der_Didi
  • 5
  • 3

1 Answers1

3

You would need to do something like this:

google.maps.event.addListener(marker, 'click', function() {
    alert("Hello World");
});

Where marker is the reference to the marker you created (of type google.maps.Marker).

So, you do it whenever you want, but you'll need a valid google.maps.Marker object, ideally you'll want to do it promptly after creating your marker.

So, updating your code to the following should work:

    $(document).ready(function()  {

//--- Ajax Request ------------------------------------------------------------------------------------------------------------------------
            $.ajax({
                dataType: "json",
                url: "karte-e.php",
                success: function(msg) {
                    initialize(msg);
                }
            });
//--- Ende Ajax Request ------------------------------------------------------------------------------------------------------------------------                

//--- Funktionen Google Maps API ------------------------------------------------------------------------------------------------------------------------   
            function initialize(json) {
                var mapProp = {
                    center:new google.maps.LatLng(51.508742,-0.120850),
                    zoom:2,
                    mapTypeId:google.maps.MapTypeId.ROADMAP
                };
                map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
                setMarkers(map, json);


            }

            function setMarkers(map, locations) {

                    var image_normal = {
                        url: 'Pins/pin-blau.png',
                        size: new google.maps.Size(32, 32),
                        origin: new google.maps.Point(0,0),
                        anchor: new google.maps.Point(0, 32)
                    };

                    var image_neu = {
                        url: 'Pins/pin-rot.png',
                        size: new google.maps.Size(32, 32),
                        origin: new google.maps.Point(0,0),
                        anchor: new google.maps.Point(0, 32)
                    };

                    var shape = {
                        type: 'rect',
                        coords: [5, 1, 27, 32]
                    };


                    for (var i = 0; i < locations.Standorte.length -1; i++) {

                        var myLatLng = new google.maps.LatLng(locations.Standorte[i].lat, locations.Standorte[i].lng);
                        var marker_normal = new google.maps.Marker({
                            position: myLatLng,
                            map: map,
                            icon: image_normal,
                            shape: shape,
                            title: locations.Standorte[i].Titel,
                            zIndex: i
                        });
                        (function(marker){
                            google.maps.event.addListener(marker, 'click', function(){
                                // you can use the variable marker here to access the marker.
                            }); 
                        })(marker_normal);
                    }

                    var myLatLng = new google.maps.LatLng(locations.Standorte[locations.Standorte.length - 1].lat, locations.Standorte[locations.Standorte.length - 1].lng);
                    var marker_neu = new google.maps.Marker({
                            position: myLatLng,
                            map: map,
                            icon: image_neu,
                            shape: shape,
                            title: locations.Standorte[locations.Standorte.length - 1].Titel,
                            zIndex: locations.Standorte.length - 1
                        });
                        (function(marker){
                            google.maps.event.addListener(marker, 'click', function(){
                                // you can use the variable marker here to access the marker.
                            }); 
                        })(marker_neu);


                }
//--- Ende Funktionen Google Maps API ------------------------------------------------------------------------------------------------------------------------                      

            return false;
//--- Ende $(document).ready() ------------------------------------------------------------------------------------------------------------------------ 
});
Diogo Raminhos
  • 2,023
  • 16
  • 24
  • Great, that works fine. To define the Listener right after creating the Marker is that easy. Thank you. – der_Didi Jan 20 '15 at 13:36
  • @whiteagle can you please have a look at the Question from the answer below? It would be nice, if you could help me again. – der_Didi Jan 20 '15 at 15:56
  • @der_Didi - please remove the answer (note that stackoverflow doesn't work like a forum :) ). And to achieve what you are trying you'll need to use an inline function :) So, instead of using the `onMarkerClick` function use an anonymous function like `function(){ /*your code here*/ }` – Diogo Raminhos Jan 20 '15 at 17:39
  • @whiteagle: thank you for your answer. Question: Am i not able to give variables to a function? – der_Didi Jan 21 '15 at 10:47
  • @der_Didi, why did you removed the selection from my answer? lol! The question above is answered! Either way, you'll always need to use an inline function - I just updated the code in the answer. You can then call another function in the anonymous one - for instance, you create a function with a signature like `function onMarkerClick(marker)` and the on your anonymous function call it (something like `function(){ onMarkerClick(marker_variable_name); }` or using `.call(this, marker_variable_name)`, whatever you prefer/makes sense in your context. – Diogo Raminhos Jan 21 '15 at 10:55
  • @whiteagle: Ok, i hope, i used stackoverflow correct this time. I'll try your code and give feedback soon. – der_Didi Jan 21 '15 at 11:17
  • @whiteagle: Sorry, that i have to disturb you again. I've tried to access the clicked markers information from the marker, which have been created in that for()-part. It seems, that i only get the results of the last marker, that was created. I've also tried to look for a reason in [Google API Documentation](https://developers.google.com/maps/documentation/javascript/examples/event-closure?hl=de) but for me, it looks like they do it the same way. It seems, that don't get the triggering marker. – der_Didi Jan 21 '15 at 13:21
  • @der_Didi - sorry my bad! The problem is that you're loosing the context - since the var is "overridden" it only gets the last value when you get to your event - check the code above, you just needed to add an anonymous function calling itself on the form, to keep the correct marker in place for the event! (P.S.: You now have to access your marker as `marker` - or whatever name you set on the first anonymous function signature). Cheers! Diogo – Diogo Raminhos Jan 21 '15 at 17:34
  • @whiteagle: Works great, that is, what i expected. Thank you very much. But I don't realy understand, why it has to be this way. I also tried to push the marker into an array, but it didn't work. Is that a special behavior of the Google Maps API or is it something typical jQuery or JavaScript? Do you have a link for me, where i can read about the reasons and relationships? So that i can find the solution by myself next time. – der_Didi Jan 22 '15 at 08:45
  • Hello @der_Didi, sorry for the delay - it's a typical javascript problem, basically you were loosing your context (aka your scope) - check http://stackoverflow.com/a/13977142/1337431 it's well explained, what is explained with the setTimeout on that answer, happens with any function that is not promptly executed - so any anonymous function that is defined - inside a loop. Glad I could help :) – Diogo Raminhos Jan 23 '15 at 10:50