| 1 |
L.AjaxGeoJSON = L.GeoJSON.extend({ |
| 2 |
options : { |
| 3 |
type: 'json' // 'json|kml|gpx' |
| 4 |
}, |
| 5 |
|
| 6 |
initialize : function (url, options) { |
| 7 |
L.setOptions(this, options); |
| 8 |
this._url = url; |
| 9 |
this.layer = L.geoJson(null, this.options); |
| 10 |
}, |
| 11 |
|
| 12 |
onAdd : function (map) { |
| 13 |
var _this = this, |
| 14 |
type = this.options.type, |
| 15 |
xhr; |
| 16 |
|
| 17 |
this.map = map; |
| 18 |
|
| 19 |
map.addLayer( this.layer ); |
| 20 |
|
| 21 |
if (!this.request) { |
| 22 |
this.request = xhr = new XMLHttpRequest(); |
| 23 |
|
| 24 |
xhr.onreadystatechange = function () { |
| 25 |
var data; |
| 26 |
if (xhr.readyState === xhr.DONE && |
| 27 |
xhr.status === 200) { |
| 28 |
if (type === 'json') { |
| 29 |
data = JSON.parse( xhr.responseText ); |
| 30 |
} else if (['kml', 'gpx'].indexOf(type) !== -1) { |
| 31 |
data = window.toGeoJSON[ type ]( xhr.responseXML ); |
| 32 |
} |
| 33 |
_this.json = data; |
| 34 |
_this.layer.addData( data ); |
| 35 |
_this.fire('ready'); |
| 36 |
} |
| 37 |
}; |
| 38 |
|
| 39 |
xhr.open('get', this._url, true); |
| 40 |
|
| 41 |
xhr.send(); |
| 42 |
} |
| 43 |
this.fire('add'); |
| 44 |
}, |
| 45 |
|
| 46 |
eachLayer : function (fnc) { |
| 47 |
this.layer.eachLayer( fnc ); |
| 48 |
}, |
| 49 |
|
| 50 |
setStyle : function (style) { |
| 51 |
|
| 52 |
this.layer.setStyle( style ); |
| 53 |
}, |
| 54 |
|
| 55 |
resetStyle : function (layer) { |
| 56 |
this.layer.resetStyle( layer ); |
| 57 |
}, |
| 58 |
|
| 59 |
onRemove : function (map) { |
| 60 |
this.map.removeLayer( this.layer ); |
| 61 |
}, |
| 62 |
|
| 63 |
getBounds : function () { |
| 64 |
return this.layer.getBounds(); |
| 65 |
} |
| 66 |
}); |
| 67 |
|
| 68 |
L.ajaxGeoJson = function( url, options ) { |
| 69 |
return new L.AjaxGeoJSON( url, options ); |
| 70 |
}; |