выберите два маркера и проведите линию между ними в листовке

Я очень новичок в листовках.

У меня есть несколько маркеров/круглых маркеров, нанесенных на мою карту в листовке.

теперь мне нужно провести линию между двумя маркерами//обвести маркеры, когда я их выбираю.

Может ли кто-нибудь помочь в этом.

var map = L.map('map').setView([51.49521, -0.10062], 13);
L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: 'Map data &copy; <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://cloudmade.com">CloudMade</a>'
    }).addTo(map);

 // get all 6 points
  var points = new Array(
[51.49346, -0.11518],
[51.49827, -0.06763],
[51.48331, -0.08154],
[51.52284, -0.09974],
[51.51932, -0.06695],
[51.50949, -0.1363]
   );

  // centerpoint
  var centerPoint = new L.LatLng(51.49521, -0.10062);
  var marker1 = L.marker([51.49521, -0.10062]).addTo(map);


  // adding allo points to map
  for (var i =0 ; i < points.length; i++)
  { 
     // here I can use marker also(if solution is possible with markers)
L.circleMarker([points[i][0],points[i][1]]).addTo(map);
var point = new L.LatLng(points[i][0],points[i][1]);
var pointList = [point, centerPoint];

    var firstpolyline = new L.Polyline(pointList, {
    color: 'red',
    weight: 5,
    smoothFactor: 1

   }).addTo(map);
  }

person vaibhav shah    schedule 04.03.2013    source источник


Ответы (1)


Вы должны сохранить выбор (однако это может быть polyline точка или флажок в ваших маркерах). Когда вы выбираете два или более маркера, вы должны добавить точки к вам polyline - он рисует линию на карте, в противном случае вы должны удалить точку из polyline. См. подробности о polyline: http://leafletjs.com/reference.html#polyline.

См. следующий код, например:

// Init map
var map = L.map('map').setView([53.902257, 27.561640], 13);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

// Init selection and lines logic
var selection = [];
var polyline = L.polyline([], {color: 'red'}).addTo(map);

var onClick = function () {
    var index = selection.indexOf(this);
    if (index !== -1) {
        this.setRadius(10);
        selection.splice(index, 1);
        polyline.spliceLatLngs(index, 1);
    } else {
        this.setRadius(25);
        selection.push(this);
        polyline.addLatLng(this.getLatLng())
    }
};

// Init circle markers
L.circleMarker([53.90, 27.56]).on('click', onClick).addTo(map);
L.circleMarker([53.92, 27.60]).on('click', onClick).addTo(map);
L.circleMarker([53.88, 27.60]).on('click', onClick).addTo(map);

// Init selection droping on ESC pressed
L.DomEvent.on(document, 'keydown', function (e) {
    if (e.keyCode === 27) {
        var oldSelection = selection.slice(0);
        for (var i = 0, l = oldSelection.length; i < l; i++) {
            oldSelection[i].fire('click');
        }
    }
});

ОБНОВЛЕНИЕ:

Аналогично, смотрите обновленный код:

var map = L.map('map').setView([51.49521, -0.10062], 13);
L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: 'Map data &copy; <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://cloudmade.com">CloudMade</a>'
}).addTo(map);

// get all 6 points
var points = [
    [51.49346, -0.11518],
    [51.49827, -0.06763],
    [51.48331, -0.08154],
    [51.52284, -0.09974],
    [51.51932, -0.06695],
    [51.50949, -0.1363]
];

// polyline
var selection = [];
var polyline = new L.Polyline([], {
    color: 'red',
    weight: 5,
    smoothFactor: 1
}).addTo(map);

var changeMarkerState = function (marker, select) {
    if (marker instanceof L.CircleMarker) {
        if (select) {
            marker.setRadius(25);
        } else {
            marker.setRadius(10);
        }
    }
    if (marker instanceof L.Marker) {
        if (select) {
            marker.options.title = 'selected';
        } else {
            marker.options.title = 'unselected';
        }
        marker.setIcon(new L.Icon.Default());
    }
};

var onClick = function () {
    var index = selection.indexOf(this);
    if (index !== -1) {
        changeMarkerState(this, false);
        selection.splice(index, 1);
        polyline.spliceLatLngs(index, 1);
    } else {
        changeMarkerState(this, true);
        selection.push(this);
        polyline.addLatLng(this.getLatLng())
    }
};

// centerpoint
var centerPoint = new L.LatLng(51.49521, -0.10062);
var marker1 = L.marker([51.49521, -0.10062],
        {title: 'unselected'}).on('click', onClick).addTo(map);


// adding allo points to map
for (var i = 0, l = points.length; i < l; i++)
{
    // here I can use marker also(if solution is possible with markers)
    L.circleMarker(points[i]).on('click', onClick).addTo(map);
}
person tbicr    schedule 04.03.2013
comment
Он отлично работает отдельно, но почему-то не работает при интеграции с моим скриптом. Позвольте мне просто обновить мой вопрос. - person vaibhav shah; 04.03.2013
comment
В вашем коде вы создаете линию для всех точек от центра. Означает ли now I have to draw line between two markers//circle Markers when I select them., что вы хотите провести линию между центром и точкой, просто если вы выберете (щелкните) точку? - person tbicr; 04.03.2013
comment
Нет, я хочу создать линию между двумя точками (не по центру), когда я выбираю обе точки. Здесь у меня всего 6 точек и 1 центральная точка, поэтому, если я выберу любые 2 точки из этих 6 точек, я смогу провести линию между ними. - person vaibhav shah; 05.03.2013