I want to display markers based on the coordinates in my views.py map function but I can’t seem to figure out how to get my javascript to display it.
Here is my views.py function.
def map(request):
# This line works
# data = {'lat':'33.674921', 'lng': '-117.168055'}
# This line doesn't work
data = {'lat':('33.683540', '33.674921'),
'lng':('-117.167930', '-117.168055'),
'desc':('this is some text.', 'this is some text.')}
data = dumps(data)
return render(request, "map.html", {"data": data})
Here is my javascript.
// Where you want to render the map.
var element = document.getElementById('osm-map');
// Height has to be set. You can do this in CSS too.
element.style = 'height:1000px;padding-top:70px;';
// Create Leaflet map on map element.
var map = L.map(element);
// Add OSM tile layer to the Leaflet map.
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// Target's GPS coordinates.
var target = L.latLng('33.8072286', '-116.9717381');
// Set map's center to target with zoom 14.
map.setView(target, 14);
// Place a marker on the same location.
L.marker(target).addTo(map);
// Connect to django views function
var markers = JSON.parse("{{data|escapejs}}");
// Loop through the markers array
for (var i = 0; i < markers.length; i++) {
var lon = markers[i][0];
var lat = markers[i][1];
var popupText = markers[i][2];
var markerLocation = new L.LatLng(lat, lon);
var marker = new L.Marker(markerLocation);
map.addLayer(marker);
marker.bindPopup(popupText);
}
console.log(markers)