利用原型链继承实现
利用在继承父类时,子类中有关父类是共享的,一个改变所有都会改变这一特性来达到鼠标移动时的折线清理。
以下为实例:
<div class="main">
<div class="con">
<div id="start">开始测距</div>
<div id="end">结束测距</div>
</div>
<div class="map" id="map"></div>
</div>
function inheritPrototype(subType, superType) {//继承
var prototype = new superType; //创建对象 继承父亲
prototype.constructor = subType; //增强对象 赋予子
subType.prototype = prototype; //指定对象 子指向父
}
function LineIns() {}//子
function Line() { //父
this.p1 = L.latLng(0, 0);//起点
this.p2 = L.latLng(0, 0);//终点
}
inheritPrototype(LineIns, Line);
LineIns.prototype.setP1 = function(p1) {//set和get
this.p1.lat = p1.lat;
this.p1.lng = p1.lng;
}
LineIns.prototype.getP1 = function() {
return this.p1;
}
LineIns.prototype.setP2 = function(p2) {
this.p2.lat = p2.lat;
this.p2.lng = p2.lng;
}
LineIns.prototype.getP2 = function() {
return this.p2;
}
function DrawLine() {}//子
function Draw() {//父
this.line = L.polyline([
[0, 0]
]);
}
inheritPrototype(DrawLine, Draw);
DrawLine.prototype.setLine = function(line) {
if (map.hasLayer(this.line)) {//移除多余的线
map.removeLayer(this.line);
}
this.line.setLatLngs([line.getP1(), line.getP2()])//setLatLngs用给定的地理点数组替换折线中的所有点。
.bindTooltip("<p>" + (map.distance(line.getP1(), line.getP2()) / 1000).toFixed(2) + "km</p>", {
permanent: true,//添加距离提示
})
.addTo(map)//完成画线
.openTooltip();
}
function sclick(){
map.off('mousemove', mmove);//关闭鼠标移动监听事件
map.off('click', sclick);//关闭第二次点击事件监听
map.on("click", fclick);//再次开始第一次点击事件监听,准备下次画线
var line = new LineIns();//为第二个线创建
var p1 = line.getP1();
var p2 = line.getP2();
}
function mmove(e) {
e.originalEvent.stopPropagation();
var p2 = e.latlng;
var line = new LineIns();//设置子对象
line.setP2(p2);//存放终点p2
var drawLine = new DrawLine();//设置画线子对象划线
drawLine.setLine(line);//开始画线,line的p1和p2是公共的!
map.off('click', fclick);//关闭第一次点击事件监听
map.on('click', sclick);//开始第二次点击事件监听
}
function fclick(e) { //e具有latlng属性,该属性是单击发生的位置。
var p1 = e.latlng;
var line = new LineIns();//创建子对象
line.setP1(p1);//设置起点值
map.off('click', sclick);
map.on('mousemove', mmove);//开始监听鼠标移动事件
}
$('#start').click(function() {//点击开始测距
map.on('click', fclick);
})
$('#end').click(function() {//点击结束测距
map.off('click', fclick);
map.off('click', sclick);
map.off('mousemove', mmove);
var drawLine = new DrawLine();//清除当前折线
if(map.hasLayer(drawLine.line)) {
map.removeLayer(drawLine.line);
}
})