Shoplifter20
Shoplifter20

Reputation: 161

Draw GeoJSON on Leaflet

Since I don't find the examples on the Leaflet site very useful, I tried to follow their general tips in order to draw my GeoJSON on map as a track. The thing is, the object is correctly saved, but when I add it to the map, it doesn't show anything. What am I missing here? I'm new to Leaflet. Thank you.

Code:

...

$.ajax('2016-05-04 13-13-36.gpx').done(function(response) {
    geo = toGeoJSON.gpx(response);
});

angular.element($elem[0]).append(angular.element('<div id="trackmap'+ trackmapCount +'" style="width: 100%; height: calc(100% - 25px); border: 1px solid #ccc"></div>'));
trackmaps[trackmapCount] = new L.Map('trackmap'+ trackmapCount +'', {center: new L.LatLng(center[0], center[1]), zoom: 10});
var layer1 = osm.addTo(trackmaps[trackmapCount]);

L.geoJson(geo, {
style: myStyle
}).addTo(trackmaps[trackmapCount]);

Upvotes: 0

Views: 219

Answers (1)

nathansnider
nathansnider

Reputation: 2873

$.ajax is an asynchronous method. This means that geo does not exist until the request completes and the .done callback function is called. You will need to create your L.geoJson object inside the callback:

$.ajax('2016-05-04 13-13-36.gpx').done(function(response) {
  geo = toGeoJSON.gpx(response);
  L.geoJson(geo, {
    style: myStyle
  }).addTo(trackmaps[trackmapCount]);
});

Upvotes: 3

Related Questions