views:

56

answers:

1

Hi, im working on a Google Map in javascript(v3). I need to show some markers from XML, for wich i use Jquery.

heres the object and function, might save me time explaining:

    var VX = {
    map:null,
    bounds:null
}
VX.placeMarkers = function(filename) {
    $.get(filename, function(xml) {
        $(xml).find("marker").each(function() {
            var lat         = $(this).find('lat').text();
            var lng         = $(this).find('lng').text();
            var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
            VX.bounds.extend(point);                
            VX.map.fitBounds(VX.bounds);    //this works        
            var marker = new google.maps.Marker({
                position: point,
                map: VX.map,
                zoom: 10,
                center: point
                });
            });
        });
        //VX.map.fitBounds(VX.bounds);      //this shows me the ocean east of africa    
}

So basicaly my problem is that i cant figure out how to do fitbounds from outside of the .each function, and doing it inside the function calls it for every marker wich looks bad.

i declare the bounds when i initialize the map... havent included the entire code because its like 300 lines.

shouldent i be able to use a value that i passed to a global object?

Edit: ah, i was calling it from outside of the get function!

A: 

The second call doesn't work because it is firing before the ajax get() returns.

Place the fitBounds inside the get() handler, but outside the each() function. Like so:

var VX = {
    map:null,
    bounds:null
}
VX.placeMarkers = function(filename) 
{
    $.get
    (
        filename, 
        function(xml) 
        {
            $(xml).find("marker").each
            (
                function() 
                {
                    var lat         = $(this).find('lat').text();
                    var lng         = $(this).find('lng').text();
                    var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));

                    VX.bounds.extend(point);                
                    //VX.map.fitBounds(VX.bounds);    //this works        

                    var marker = new google.maps.Marker
                    ({
                        position: point,
                        map: VX.map,
                        zoom: 10,
                        center: point
                    });
                }
            );
            VX.map.fitBounds(VX.bounds);    //-- This should work.
        }
    );  
    //VX.map.fitBounds(VX.bounds);      //this shows me the ocean east of africa    
}
Brock Adams
wow, thats exactly it!thanks :Dwish i had rep to upvote you :)
Stjerneklar