views:

43

answers:

2

I have the script below placed in the HEAD of the page. The map should initialize when the page loads. There's two pieces to this puzzle, one is the script within the document.ready which sets all variables and configures the map i am wanting to place on a page. The second piece is the window.onload=initialize_map; that starts the map.

I believe everything is running correctly, however, i don't know for sure. All i know is that the initialize_map function never runs. I even tried to set an onclick on a button with initialize_map(); to try and manually start the map and it still didn't work. Is there something wrong with my code? Any help is greatly appreciated.

Thanks!

CODE IN QUESTION:

    <script src= "http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;key=ABQIAAAAhTrgZ5jvdqcEQouEpPcZ_hS81NmJwGXlxuJr8lEEo4Njw3WRVhT8auzZb55JSMDkwIaCdNkPHL5gNg" type="text/javascript"> </script>

<script type="text/javascript">
$(document).ready(function(){
var dealerName = $('.name', '.adr').text();
var customerName = dealerName.slice(0, - 1);
var customerAddress = $('.street', '.adr').text() + ', ' + $('.locality', '.adr').text() + ', ' + $('.state', '.adr').text() + ', ' + $('.zipCode', '.adr').text();
$("#nameAddress .placeholderName").html(customerName);
$("#nameAddress .placeholderAddress").html(customerAddress);

        var error_address_empty     = 'Please enter a valid address first.';
        var error_invalid_address   = 'This address is invalid. Make sure to enter your street number and city as well?'; 
        var error_google_error      = 'There was a problem processing your request, please try again.';
        var error_no_map_info       = 'Sorry! Map information is not available for this address.';


        var default_address = customerAddress;

        var current_address = null;
        var map               = null;
        var geocoder          = null;
        var gdir                  = null;
        var map_compatible  = false;

        if( GBrowserIsCompatible() ) {
            map_compatible = true;
        }

        function initialize_map() {
            if( map_compatible ) {
                map         = new GMap2(document.getElementById('map_canvas'));        
                geocoder = new GClientGeocoder();
                show_address(default_address);

                map.addControl(new GSmallMapControl());

                map.addControl(new GMapTypeControl());              
            }
        }

        function show_address(address) {
            if( map_compatible && geocoder ) {
                current_address = address;      
                geocoder.getLatLng(
                address,
                function( point ) {
                    if( !point ) {
                        alert(error_no_map_info);
                    } else {
                        map.setCenter(point, 13);
                        var marker = new GMarker(point);
                        map.addOverlay(marker);
                        marker.openInfoWindowHtml("<span style='font-size:14px; font-weight:bold;'>" + customerName + "<br /></span><span style='font-size:12px;'>" + address + "</span>");
                    }
                }
                );
            }
            return false;
        }

        function get_directions() {
            if( map_compatible ) {
                if( document.direction_form.from_address.value == '' ) {
                    alert(error_address_empty);
                    return false;
                }

                document.getElementById('directions').innerHTML = '';

                gdir = new GDirections(map, document.getElementById('directions'));

                GEvent.addListener(gdir, 'error', handleErrors);

                set_directions(document.direction_form.from_address.value, current_address);            
            }
            return false;
        }

        function set_directions(fromAddress, toAddress) {
        gdir.load("from: " + fromAddress + " to: " + toAddress,
                    { "locale": "en" });
        }

        function handleErrors(){
            if( gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS )
                alert(error_invalid_address);
            else if( gdir.getStatus().code == G_GEO_SERVER_ERROR )
                alert(error_google_error);
            else if( gdir.getStatus().code == G_GEO_MISSING_QUERY )
                alert(error_address_empty);
            else 
                alert(error_invalid_address);
        }
});
        window.onload=initialize_map;
</script>
+1  A: 

The entire body of your function is in an if statement that depends on the boolean variable map_compatible being true. Are you sure that it is true?

Try putting an alert before the if statement and see if it runs that way. Maybe print out the value of map_compatible.

If it is not true then you can use a tool like firebug for firefox to step through your javascript and see why it is not being set to true as you expect it to.

Vincent Ramdhanie
i will look into this...right above the if statement i am setting the default_address variable correctly, right?
RyanPitts
it is returning true btw. :)
RyanPitts
+1  A: 

Two problems jump out right away:

  1. initialize_map is not in the global scope (it's defined within the anonymous ready event handler), so you're likely assigning an undefined value to window.onload, as you've placed the assignment itself outside of that function (in the global scope).

  2. Why are you mixing jQuery's ready handler with window.onload? At worst, this is flat-out not going to work - from the jQuery documentation:

    The .ready() method is generally incompatible with the attribute. If load must be used, either do not use .ready() or use jQuery's .load() method to attach load event handlers to the window or to more specific items, like images.

    ...and even at best, it's unnecessary. Use jQuery for both or neither:

    $(document).ready(function(){
    
    
      ...
    
    
      $(window).load(initialize_map);
    
    
      ...
    
    
    });
    
Shog9
there's really no reason why i used both methods other than i edited them at two different times and didn't realize i had done that. Thanks for the tip!
RyanPitts
@Ryan: actually, #1 is most critical - right now, your initialize function is completely inaccessible to the code trying to use it, so there's no way it'll ever be called. You'll have to fix that before anything else - the suggestion I gave for #2 will actually fix both.
Shog9
ok, i'm trying to change the window.onload to a JQuery load to see if that helps. Thanks!
RyanPitts
putting the $(window).load(initialize_map); inside of the .ready worked! Thanks so much!
RyanPitts
would there be a reason why after doing this my get_directions and show_address functions are saying not defined?get_directions is called from a form submit button and show_address is called from another button that centers the map. Could it be because these onclick and onsubmit codes are loading onto the page before the js loads and runs?
RyanPitts
@RyanPitts: Both of those functions are defined within the `ready` handler as well. So you'll have to bind them to their events within that handler just as you have with `initialize_map`. And although it's not strictly necessary, I highly recommend you use jQuery to bind them also, just for the sake of consistency (if you're currently using inline "attribute" event handlers, switching to jQuery binding from `ready` will provide you with a much cleaner, more maintainable setup).
Shog9
@Shog9, Could you perhaps add one or two code examples of how to do what you are talking about? I'm missing something i think.
RyanPitts