3

My problem is that pointOnMap() runs before xmlPreparer() despite on order. I think it has something to do with using AJAX. parseXML creates object i need . So when i use pointOnMap() it already should be initialized.

On page is first that i see from pointOnMap - 0 and after that from parse ..So it is not in right order .
Thank you for your advices.

var mesta= new Array();


function init() {
    xmlPreparer();
    pointOnMap();   
}

//add source
function xmlPreparer() {   
    $.ajax({
    type: "GET",
    url: "./mesta.xml",
    dataType: "xml",
    success: parseXml
  });
}

function parseXml(xml) {

    var type;
    var name;
    var latitude;
    var longitude;

  $(xml).find("city").each(function()
  {
    type=$(this).find("type").text();
    name=$(this).find("name").text();
    latitude= $(this).find("latitude").text();
    longitude=$(this).find("longitude").text();
    var mesto = {type:type, name:name, latitude:latitude, longtitude:longitude};
    mesta.push(mesto);
  });
    alert(mesta.length);//this prints right size
}

//add source
function pointOnMap() {
alert(mesta.length);//for no reason prints 0 and runs before xmlparser?
$('#dot').css('top', YLatToPixel(0,$('#jpMapa')))
$('#dot').css('left', XLngToPixel(0,$('#jpMapa'))+'px');
}

function YLatToPixel(lat,elem){
var containerHeight=$(elem).height();
lat+=90;
var calculatedHeight=((lat*containerHeight)/180);
return $(elem).offset().top+($(elem).height()-calculatedHeight);
}


function XLngToPixel(lng,elem){
var containerWidth=($(elem).width());
lng=lng+180;
return $(elem).offset().left+((lng*containerWidth)/360);
}
jan
  • 43
  • 6
  • @Ed Cottrell: Have you looked at the accepted answer on that "duplicate"... use `async: false`! Argggh... That answer should be deleted and never used as a duplicate! :) – iCollect.it Ltd May 01 '15 at 16:11

1 Answers1

4

Rework it with jQuery promises like this:

function init() {
    xmlPreparer().then(function(data){
        parseXml(data);
        pointOnMap();   
    });
}

//add source - returns the Ajax promise
function xmlPreparer() {   
   return $.ajax({
    type: "GET",
    url: "./mesta.xml",
    dataType: "xml"
  });
}

Note: the difference between then and done is that then allows for a second fail function to be passed. done is like success: in Ajax and has a matching fail() function so you could also write.

function init() {
    xmlPreparer().done(function(data){
        parseXml(data);
        pointOnMap();   
    }).fail(function(){
        alert("arggh!");
    });
}
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202