如何在Leaflet中制作2点的曲线?

时间:2018-11-27 15:28:48

标签: javascript leaflet maps

例如可以使用以下坐标在传单的2个近点之间绘制一条曲线:

point_1 = (23.634501, -102.552783)

point_2 = (17.987557, -92.929147)

谢谢。

1 个答案:

答案 0 :(得分:0)

正如@Wrokar所暗示的,可以使用Leaflet.curve库来实现。您可以简单地使用此gist提供的代码,并将坐标分别替换为变量latlng1和latlng2中定义的坐标。

var latlng1 = [LATITUDE, LONGTITUDE],
    latlng2 = [LATITUDE, LONGTITUDE];

这是一个有效的示例:

var map = L.map('mapid').setView([51.505, -10], 1);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

var latlngs = [];

var latlng1 = [23.634501, -102.552783],
  latlng2 = [17.987557, -92.929147];

var offsetX = latlng2[1] - latlng1[1],
  offsetY = latlng2[0] - latlng1[0];

var r = Math.sqrt(Math.pow(offsetX, 2) + Math.pow(offsetY, 2)),
  theta = Math.atan2(offsetY, offsetX);

var thetaOffset = (3.14 / 10);

var r2 = (r / 2) / (Math.cos(thetaOffset)),
  theta2 = theta + thetaOffset;

var midpointX = (r2 * Math.cos(theta2)) + latlng1[1],
  midpointY = (r2 * Math.sin(theta2)) + latlng1[0];

var midpointLatLng = [midpointY, midpointX];

latlngs.push(latlng1, midpointLatLng, latlng2);

var pathOptions = {
  color: 'red',
  weight: 3
}

var curvedPath = L.curve(
  [
    'M', latlng1,
    'Q', midpointLatLng,
    latlng2
  ], pathOptions).addTo(map);
body {
  padding: 0px;
  margin: 0px;
}

#mapid {
  height: 300px;
}
<link rel="stylesheet" type="text/css" href="https://unpkg.com/leaflet@1.3.3/dist/leaflet.css">

<script src="https://unpkg.com/leaflet@1.3.3/dist/leaflet.js"></script>

<script src="https://elfalem.github.io/Leaflet.curve/src/leaflet.curve.js"></script>

<div id="mapid"></div>