wag*_*325 0 javascript ajax json leaflet
我正在寻找一种使用 AJAX 在传单中使用 JSON 而不是 GeoJSON 的方法。需要使用 JSON 和 AJAX。
\n\n我设法使用 AJAX 调用 JSON 文件。但是,现在我很困惑如何使用 JSON 中的数据在地图上绘制标记。我猜我不能使用 L.geoJson()。
\n\nHTML:
\n\n<div id="map" style="width: 800px; height: 500px"></div>\nRun Code Online (Sandbox Code Playgroud)\n\n这是 JavaScript 文件:
\n\nvar map;\nvar overlay;\n\nvar addPopupsFromLocations = function(locations) {\n var popups = new Array();\n locations.forEach(function(location){\n console.log(\'creating popup for location \' + location.title);\n\n console.log(location.latitude);\n console.log(location.longitude);\n }) ;\n};\n\nfunction init() {\n var map = L.map(\'map\').setView([51.505, -0.09], 13);\n\n L.tileLayer(\'https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png\', {\n maxZoom: 18,\n attribution: \'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, \' +\n \'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, \' +\n \'Imagery \xc2\xa9 <a href="http://mapbox.com">Mapbox</a>\',\n id: \'examples.map-i86knfo3\'\n }).addTo(map);\n }\n\n$(document).ready(function(){\n init();\n $.ajax(\'locations.json\', {\n dataType: \'json\',\n success: addPopupsFromLocations,\n error: function(xhr, st, et) {\n console.warn(et);\n }\n });\n});\nRun Code Online (Sandbox Code Playgroud)\n\n这是 JSON 文件:
\n\n[\n {\n "title": "Weathertop",\n "link": "http://en.wikipedia.org/wiki/Weathertop",\n "latitude": 51.505,\n "longitude": -0.09,\n "imageUrl": "assets/img/location-images/Weathertop.jpg"\n },\n{\n "title": "Rivendell",\n "link": "http://lotr.wikia.com/wiki/Rivendell",\n "latitude": -0.09,\n "longitude": 51.505,\n "imageUrl": "assets/img/location-images/Rivendell2.jpg"\n},\n{\n "title": "Minas Tirith",\n "link": "http://lotr.wikia.com/wiki/Minas_Tirith",\n "latitude": 38.78,\n "longitude": -77.18,\n "imageUrl": "assets/img/location-images/320px-Minas_Tirith.jpg"\n}\n\n]\nRun Code Online (Sandbox Code Playgroud)\n\n安慰:
\n\ncreating popup for location Weathertop\ncustom.js (line 7)\n51.505\ncustom.js (line 9)\n-0.09\ncustom.js (line 10)\ncreating popup for location Rivendell\ncustom.js (line 7)\n-0.09\ncustom.js (line 9)\n51.505\ncustom.js (line 10)\ncreating popup for location Minas Tirith\ncustom.js (line 7)\n38.78\ncustom.js (line 9)\n-77.18\nRun Code Online (Sandbox Code Playgroud)\n
我正在寻找一种使用 AJAX 在传单中使用 JSON 而不是 GeoJSON 的方法。
好的:回顾一些条款,
如果您想使用L.geoJson,您需要重新格式化您的数据,使其符合GeoJSON规范。您可以使用基本的 JavaScript 来完成此操作。
var geojsonFormattedLocations = locations.map(function(location) {
return {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [location.longitude, location.latitude]
},
properties: {
location
}
};
});
Run Code Online (Sandbox Code Playgroud)