4

我需要使用最短距离在两点之间绘制一条折线。例如,我的位置是纽约,我在中国有一个位置,我想绘制一条连接这两个位置的折线。

我在哪里 - 在这里看小提琴:http: //jsfiddle.net/Vsq4D/1/

问题是,当我画线时,它确实使用了最短距离。在上面的例子中,它从美国画到中国,线向右,绕地球最长的路线,而不是向左,这是最短的路线。

我错过了什么?任何想法如何根据最短距离画线?

地图

非常感谢任何帮助。

HTML:

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />
<!--[if lte IE 8]>
   <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.ie.css" />
<![endif]-->

<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>

<div id="map" style="height:500px;"></div>

JS:

//example user location
var userLocation = new L.LatLng(35.974, -83.496);

var map = L.map('map').setView(userLocation, 1);
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);


var marker = new L.Marker(userLocation);
map.addLayer(marker);

//random locations around the world
var items = [{
    //china
    lat: "65.337",
    lon: "158.027"
}, {
    //colombia
    lat: "2.389",
    lon: "-72.598"
}, {
    //libya
    lat: "24.782",
    lon: "17.402"
}];

drawData();

//draw all the data on the map
function drawData() {
    var item, o;
    //draw markers for all items
    for (item in items) {
        o = items[item];
        var loc = new L.LatLng(o.lat, o.lon);
        createPolyLine(loc, userLocation);
    }
}

//draw polyline
function createPolyLine(loc1, loc2) {

    var latlongs = [loc1, loc2];
    var polyline = new L.Polyline(latlongs, {
        color: 'green',
        opacity: 1,
        weight: 1,
        clickable: false
    }).addTo(map);

    //distance
    var s = 'About ' + (loc1.distanceTo(loc2) / 1000).toFixed(0) + 'km away from you.</p>';

    var marker = L.marker(loc1).addTo(map);
    if (marker) {
        marker.bindPopup(s);
    }
}
4

1 回答 1

3

这是一个可以解决线路问题的工作 jsfiddle 。有一个附加到 LatLng 对象的方法,称为 wrap 应该会有所帮助。我不得不进行一些试验才能让它发挥作用。我定了

if (Math.abs(loc1.lng - loc2.lng) > 180) {
  latlongs = [loc1.wrap(179, -179), loc2];
}

不幸的是,如您所见,中国的标记没有被复制。我向worldCopyJump: true地图对象添加了该选项,但它并没有解决该特定问题。不知道如何解决。

编辑:为了子孙后代,我忘了提到它之前不起作用的原因是因为国际日期变更线的过渡。

于 2013-09-25T16:06:42.000 回答