django data render to JavaScript to make a map polyline with latitude and longitude

Viewed 314

I have a model named MapLocation and inside MapLocation model i have few attributes such as packageid, location_name, latitude and longitude. My goal is to build a map polyline using Lifletjs. for this i need fetch latitude and longitude and render them to template to use lat lng in javascript file. i have multiple lat lng for a specific tour package and i need to run a for loop for this. Here is my views code:

from django.shortcuts import render
from .models import MapLocation
from django.core import serializers
import json
from django.http import HttpResponseRedirect, HttpResponse
from django.core.serializers.json import DjangoJSONEncoder
# Create your views here.


def showthis(request):
json_res = serializers.serialize('json',MapLocation.objects.filter(package_id=1),fields=  ('latitude','longitude'))
context= {'all_objects': json_res}
return render(request, 'test.html', context)

I used serializer to render data in json format, here is my javascript Template code

            var js_list = "{{all_objects|escapejs}}";
            
            var myJSONList = (("{{all_objects}}").replace(/&(l|g|quo)t;/g, function(a,b){
                        return {
                            l   : '<',
                            g   : '>',
                            quo : '"'
                        }[b];
                    }));

            myData = JSON.parse( myJSONList );
            console.log(myData);

after writing these code i get all my data in console, like the layout given below

enter image description here

Now i want to for loop latitude and longitude in here to create a polyline on Map.

var js_list = "{{all_objects|escapejs}}";
        
        var myJSONList = (("{{all_objects}}").replace(/&(l|g|quo)t;/g, function(a,b){
                    return {
                        l   : '<',
                        g   : '>',
                        quo : '"'
                    }[b];
                }));

    myData = JSON.parse( myJSONList );
    console.log(myData);


        var mymap = L.map('mapid').setView([51.505, -0.09], 15);

        L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoiYml0YTYzOSIsImEiOiJja2NsNDQwZGMwMG5iMnB0ZHoxaDJzeXZ0In0.jcSkP5MJWjG3yuRGn8J5og', {
            maxZoom: 18,
            attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
                '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
                'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
            id: 'mapbox/streets-v11',
            tileSize: 512,
            zoomOffset: -1
        }).addTo(mymap);

        

        L.marker([51.52, -0.05]).addTo(mymap)
            .bindPopup("<b>End Point!</b><br />I am a popup.").openPopup();

        L.marker([51.509, -0.08]).addTo(mymap)
            .bindPopup("<b>Start Point!</b><br />I am a popup.").openPopup();


        

        L.polyline([
            [51.509, -0.08], #forloop here to make it dynamic, becaus ethere will be many lat lng based on different tour package
            [51.503, -0.06],
            [51.51, -0.047],
            [51.52, -0.05],
        ],{color: 'red'}).addTo(mymap).bindPopup("I am a polygon.");


        var popup = L.popup();

        function onMapClick(e) {
            popup
                .setLatLng(e.latlng)
                .setContent("You clicked the map at " + e.latlng.toString())
                .openOn(mymap);
        }

        mymap.on('click', onMapClick);

can some one give a proper instruction how can i put all these lat lng dynamically to JavaScript or how can i make a forloop to get, please help me to get ride of this problem.

1 Answers

Use this code. I have created an empty array and push the dynamic data to that array and used to your location . Just copy the code and paste it.

    var polyArr = [];
    myData.map((item) => polyArr.push([item.fields.latitude, item.fields.longitude]));
    L.polyline(polyArr, { color: 'red' }).addTo(mymap).bindPopup('I am a polygon.');

If you are not clear ask me. Hope this helps you. Thank you

Related