Home > database >  Leaflet with markers and line connection
Leaflet with markers and line connection

Time:10-10

I'm trying to make connect lines between markers with the center of marker over Baghdad (which are generated from JSON data) in leaflet.

Result required :

enter image description here

l have :

enter image description here

How can make it like the first image?

Code :

$(document).ready(function () {

    $.ajax('./api/bgw_route.json?', {
        type: 'GET',
        dataType: 'json',
        success: function () { },
        error: function () { alert('Something wrong . Please try again later !'); }
    }).done(function (data, textStatus, jqXHR) {
        console.log(data)
        
               // layers icons controls 
        var IraqiAirspace = L.layerGroup();
        var in_out = L.layerGroup();
        //      map initilizing   
        var coords = [33, 44];
        var zoomLevel = 4
        var map = new L.Map('map').setView(coords, zoomLevel);
        L.tileLayer('mobile.2.0.2/{z}/{x}/{y}.png', {
            attribution: '',
            maxZoom: 8,
            minZoom: 4,
            zoomControl: false
        }).addTo(map);
        map.addLayer(IraqiAirspace)

        var icon = L.icon({
            iconUrl: 'airport_pin_40_blue.png',
            iconSize:[30,30]
            
        })
        if(data){
            var points=[]
            data.forEach(element => {
                points.push([element.lat,element.lon])
                console.log(points)
                L.marker([element.lat,element.lon], { icon: icon }).addTo(map);
                L.polyline(points).addTo(map)
            });
            // Baghdad marker 
            L.marker([33.262501,44.234444], { icon: icon }).addTo(map)   

        }

    })


})

Data JSON

CodePudding user response:

You are adding all points to a array and from that a polyline instead of creating from every point to the center a new polyline. Change your code to:

if(data){

            // Baghdad marker 
            var center = [33.262501,44.234444];
            L.marker(center, { icon: icon }).addTo(map)   

            data.forEach(element => {
                var point = [element.lat,element.lon];
                L.marker(point , { icon: icon }).addTo(map);
                L.polyline([center, point]).addTo(map)
            });

        }
  • Related