Handige Harrie
Handige Harrie

Reputation: 149

Button created in javascript can't identify variable

I'm busy with creating a script for the google maps API (v3) almost got it finished, but I ran into a problem which I can't figure out how to solve (might be the hours of non-stop coding :P).

Alright so what I'm attempting to do is creating a html string in which I'm also creating a button which I want to execute a function on click, but it doesn't work and the console throws me this error:

Uncaught ReferenceError: marker_gen is not defined

This is the code that causes the problem:

(the ajax code where also the button is created) (I marked the html string with '->')

$.get("includes/require/gen.php", function (data) {
            $(data).find("marker").each(function () {
                //Get user input values for the marker from the form
                var name      = $(this).attr('name');
                var info   = $(this).attr('address'); //description
                var type      = $(this).attr('type');
                var point     = new google.maps.LatLng(parseFloat($(this).attr('lat')),parseFloat($(this).attr('lng')));
                //call create_marker() function for xml loaded maker
                //create_marker(point, name, address, false, false, false);
                var marker_gen = new google.maps.Marker({
                   position: point,
                   map: map,
                   icon: "img/icons/green_marker.png"
                })

                google.maps.event.addDomListener(marker_gen,"click",function(event){
                    -> contentString = '<div id="div_info"><h2>'+ name+'</h2> <p><b>Type: </b>'+type+'<br/><b>Co&ouml;rdinaten: </b>'+point+'</p><p><b>Omschrijving:</b><br/>'+info+'<br/><br/></span><button name="remove-marker" class="remove-marker" onclick="remove_marker(marker_gen)" title="Remove Marker">Remove Marker</button></div>';
                    IW.content = contentString;
                    IW.open(map,marker_gen);
                });
            });
        }); 

this is the remove_marker function (doubt it's needed though)

function remove_marker(Marker)
{
    /* determine whether marker is draggable 
    new markers are draggable and saved markers are fixed */
    if(Marker.getDraggable()) 
    {
        Marker.setMap(null); //just remove new marker
        //marker = null;
    }
    else
    {
        //Remove saved marker from DB and map using jQuery Ajax
        var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
        var myData = {del : 'true', latlang : mLatLang}; //post variables
        $.ajax({
           type: "POST",
          url: "includes/require/gen.php",
          data: myData,
          success:function(data){
                Marker.setMap(null); 
                alert(data);
            },
            error:function (xhr, ajaxOptions, thrownError){
                alert(thrownError); //throw any errors
            }
        });
    }
}

If anyone got a solution for this, I would love to hear it.

Thanks in advance, Remy

Upvotes: 0

Views: 77

Answers (2)

Gonzalo
Gonzalo

Reputation: 4269

The problem is the contentString markup won't be in the same context as your script, so it'll never have access to marker_gen.

You'll need to use event delegation as @Krishna explains:

google.maps.event.addDomListener(marker_gen,"click",function(event){
    var contentString = '<div id="div_info"><h2>'+ name+'</h2> <p><b>Type: </b>'+type+'<br/><b>Co&ouml;rdinaten: </b>'+point+'</p><p><b>Omschrijving:</b><br/>'+info+'<br/><br/></span><button name="remove-marker" class="remove-marker" onclick="remove_marker(marker_gen)" title="Remove Marker">Remove Marker</button></div>';
    IW.content = contentString;
    IW.open(map,marker_gen);
    $('#div_info button').one('click', function() {
        // remove marker code or call here
    });
});

Notice I'm using $.one and not $.on, so when the marker is removed the event handler doesn't remain attached.

Upvotes: 1

Venkata Krishna
Venkata Krishna

Reputation: 15112

contentString = '<div id="div_info"><h2>'+ name+'</h2> <p><b>Type: </b>'+type+'<br/><b>Co&ouml;rdinaten: </b>'+point+'</p><p><b>Omschrijving:</b><br/>'+info+'<br/><br/></span><button name="remove-marker" class="remove-marker" data-marker="' + marker_gen + '" title="Remove Marker">Remove Marker</button></div>';

Don't use onclick.. use on() for event delegation since you're creating this button dynamically. Also, use data-marker="' + marker_gen + '" as an attribute while creating the button as shown above.

$('document').on('click','.remove-marker', function() {
    var Marker = $(this).data('marker');
    //Handle everything else here
});

Upvotes: 2

Related Questions