我正在尋找一種使用AJAX代替GeoJSON的方式。使用JSON和AJAX是必需的。在AJAX中使用JSON代替GeoJSON在使用AJAX的傳單中使用
我設法使用AJAX調用JSON文件。但是,現在我很困惑我如何使用JSON中的數據在地圖上繪製標記。我猜我不能使用L.geoJson()。
HTML:
<div id="map" style="width: 800px; height: 500px"></div>
這是JavaScript文件:
var map;
var overlay;
var addPopupsFromLocations = function(locations) {
var popups = new Array();
locations.forEach(function(location){
console.log('creating popup for location ' + location.title);
console.log(location.latitude);
console.log(location.longitude);
}) ;
};
function init() {
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="http://mapbox.com">Mapbox</a>',
id: 'examples.map-i86knfo3'
}).addTo(map);
}
$(document).ready(function(){
init();
$.ajax('locations.json', {
dataType: 'json',
success: addPopupsFromLocations,
error: function(xhr, st, et) {
console.warn(et);
}
});
});
這是JSON文件:
[
{
"title": "Weathertop",
"link": "http://en.wikipedia.org/wiki/Weathertop",
"latitude": 51.505,
"longitude": -0.09,
"imageUrl": "assets/img/location-images/Weathertop.jpg"
},
{
"title": "Rivendell",
"link": "http://lotr.wikia.com/wiki/Rivendell",
"latitude": -0.09,
"longitude": 51.505,
"imageUrl": "assets/img/location-images/Rivendell2.jpg"
},
{
"title": "Minas Tirith",
"link": "http://lotr.wikia.com/wiki/Minas_Tirith",
"latitude": 38.78,
"longitude": -77.18,
"imageUrl": "assets/img/location-images/320px-Minas_Tirith.jpg"
}
]
控制檯:
creating popup for location Weathertop
custom.js (line 7)
51.505
custom.js (line 9)
-0.09
custom.js (line 10)
creating popup for location Rivendell
custom.js (line 7)
-0.09
custom.js (line 9)
51.505
custom.js (line 10)
creating popup for location Minas Tirith
custom.js (line 7)
38.78
custom.js (line 9)
-77.18