Reputation: 26018
I am using the gmap3
extension for the Google Maps API
and jQuery
.
I have a .gpx
file that I read via AJAX and get each coordinate and add it to an array. I then return this array to populate my polyline in my map.
In function Test I would do a count of points just before I return it and count is 0.
Here is my function that processes the .gpx file to return the coordinates:
function Test() {
var points = [];
$.ajax({
type: "GET",
url: "gpx/12345.gpx",
dataType: "xml",
success: function (xml) {
$(xml).find("trkpt").each(function () {
var lat = $(this).attr("lat");
var lon = $(this).attr("lon");
var p = new google.maps.LatLng(lat, lon);
points.push(p);
});
}
});
return points;
}
$(document).ready(function () {
var points = Test();
var route1Latlng = new google.maps.LatLng(-33.7610590, 18.9616790);
$('#map_canvas').gmap3({
map: {
options: {
center: route1Latlng,
zoom: 11
}
},
polyline: {
options: {
path: points,
strokeColor: '#FF00AA',
strokeOpacity: .7,
strokeWeight: 4
}
}
});
});
In IE9 the polyline is not drawn, but in FireFox it draws properly.
Upvotes: 1
Views: 785
Reputation: 3485
what was happening was you call test to return the points, as it is an async request it will not hault the execution of the program and will return empty array of points. you were using empty array to plot so your line was not displayig. it will only display once the ajax request is completed. So we wrapper the plotting of marker to another function and call it when the ajax call has been completed.
Try calling a function in the success event of ajax like this
function Test() {
var points = [];
$.ajax({
type: "GET",
url: "gpx/12345.gpx",
dataType: "xml",
success: function (xml) {
$(xml).find("trkpt").each(function () {
var lat = $(this).attr("lat");
var lon = $(this).attr("lon");
var p = new google.maps.LatLng(lat, lon);
points.push(p);
});
drawPolyline(points); //when all the points have been loaded then we call this method
}
});
}
function drawPolyline(pointsTobeDrawn){ // this method gets the points and plots it
var route1Latlng = new google.maps.LatLng(-33.7610590, 18.9616790);
$('#map_canvas').gmap3({
map: {
options: {
center: route1Latlng,
zoom: 11
}
},
polyline: {
options: {
path: pointsTobeDrawn,
strokeColor: '#FF00AA',
strokeOpacity: .7,
strokeWeight: 4
}
}
});
}
$(document).ready(function () {
Test(); // we need only this method as it will plot the markers on success event of it
});
of use ajax false as
$.ajax({
async: false, //dont use quotes here like "false".
type: "GET",
url: "gpx/12345.gpx",
dataType: "xml",
success: function (xml) {
$(xml).find("trkpt").each(function () {
var lat = $(this).attr("lat");
var lon = $(this).attr("lon");
var p = new google.maps.LatLng(lat, lon);
points.push(p);
});
drawPolyline(points);
}
});
if we set async as false then our program will wait for the ajax req to complete its process.
read about how ajax call works and threading for more clarification
Upvotes: 1