I am in search of a method to utilize JSON instead of GeoJSON with leaflet, making use of AJAX. The use of JSON and AJAX is imperative for this task.
I have successfully called a JSON file using AJAX. However, I am now unsure about how to effectively utilize the data from the JSON to plot markers on the map. It seems like using L.geoJson() may not be the solution in this case.
Here is the HTML code snippet:
<div id="map" style="width: 800px; height: 500px"></div>
This is the JavaScript file:
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);
}
});
});
This is the JSON file:
[
{
"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"
}
]
Console:
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