Как связать определенные координаты LatLng с полилинией без автоматического соединения с другими точками? - PullRequest
0 голосов
/ 27 мая 2019

Я создаю страницу, которая показывает карту мира с маркерами, расположенными в координатах LatLng, и я пытаюсь связать их с Полилиниями. Однако я не хочу, чтобы каждый из них был связан вместе. Например, заданный набор {A, B, C, D, E, F}, ссылки A-> B, B-> C и C-> D, также A-> E.

Когда я пытаюсь сделать D-> F, D-> E волшебным образом появляется, даже если я не указал его.

Первоначально я пытался использовать массив путей по умолчанию, но он не работал, поэтому я использовал другой массив, называемый координатами. Первые несколько полилиний были нарисованы из одной конкретной точки, и у нее не было проблем, но когда я пытаюсь нарисовать из другой точки в другую, это работает, но также появились полилинии, которые я не указал.

$(document).ready(function() {
        // If the browser supports the Geolocation API
        if (typeof navigator.geolocation == "undefined") {
          $("#error").text("Your browser doesn't support the Geolocation API");
      return;
    }
    // Save the positions' history
    var path = [];

    navigator.geolocation.watchPosition(function(position) {
      // Save the current position
      path.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));

      // Create the map
      var myOptions = {
        zoom : 3,
        center : path[0],
        mapTypeId : google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map(document.getElementById("map"), myOptions);

        path.push(new google.maps.LatLng(2.745537, 101.707316)); //mas
        path.push(new google.maps.LatLng(37.460353, 126.440674)); //kor
        path.push(new google.maps.LatLng(34.789594, 135.438084)); //jpn
        path.push(new google.maps.LatLng(-37.665357, 144.840642)); //aus
        path.push(new google.maps.LatLng(55.410343, 37.902312)); //rus
        path.push(new google.maps.LatLng(40.085148, 116.552407)); //chi
        path.push(new google.maps.LatLng(-6.127211, 106.653684)); //ind
        path.push(new google.maps.LatLng(1.364860, 103.991594)); //sin
        path.push(new google.maps.LatLng(40.760284, -73.772304)); //usa
        path.push(new google.maps.LatLng(53.358796, -2.272773)); //uk
        path.push(new google.maps.LatLng(40.498275, -3.567727)); //spa

      // Create the array that will be used to fit the view to the points range and
      // place the markers to the polyline's points
      var latLngBounds = new google.maps.LatLngBounds();
      for(var i = 0; i < path.length; i++) {
        latLngBounds.extend(path[i]);
        // Place the marker
        new google.maps.Marker({
          map: map,
          position: path[i],
          title: "Point " + (i + 1)
        });
      }
      var coordinates = [
        //mas
        {lat:2.745537, lng:101.707316}, {lat:37.460353,lng:126.440674}, //to kor
        {lat:2.745537, lng:101.707316}, {lat:34.789594,lng:135.438084}, //to jpn
        {lat:2.745537, lng:101.707316}, {lat:-37.665357,lng:144.840642}, //to aus
        {lat:2.745537, lng:101.707316}, {lat:40.085148,lng:116.552407}, //to chi
        {lat:2.745537, lng:101.707316}, {lat:-6.127211,lng:106.653684}, //to ind
        {lat:2.745537, lng:101.707316}, {lat:1.364860,lng:103.991594}, //to sin
        {lat:2.745537, lng:101.707316}, {lat:40.498275,lng:-3.567727}, //to spa

        //kor
        {lat:36.460353, lng:126.440674}, {lat:34.789594,lng:135.438084}, //to jpn
        {lat:36.460353, lng:126.440674}, {lat:55.410343,lng:37.902312}, //to rus
        {lat:36.460353, lng:126.440674}, {lat:40.085148,lng:116.552407}, //to chi

      ];
      // Creates the polyline object
      var polyline = new google.maps.Polyline({
        map: map,
        path: coordinates,
        strokeColor: '#0000FF',
        strokeOpacity: 0.7,
        strokeWeight: 1,
        geodesic: true
      });
      // Fit the bounds of the generated points
      //map.fitBounds(latLngBounds);
      polyline.setMap(map);
    },
    function(positionError){
      $("#error").append("Error: " + positionError.message + "<br />");
    },
    {
      enableHighAccuracy: true,
      timeout: 10 * 1000 // 10 seconds
    });
  });

https://imgur.com/KyoSUmu

screenshot of map

Я ожидаю, что точка Южной Кореи соединяется только с Москвой, Китаем, Японией и Малайзией, а не с Испанией.

1 Ответ

0 голосов
/ 27 мая 2019

Вы делаете только одну полилинию. Он соединяет все точки в массиве coordinates. Так происходит из Испании в Корею.

{lat:2.745537, lng:101.707316}, {lat:40.498275,lng:-3.567727}, //to spa

//kor
{lat:36.460353, lng:126.440674}, {lat:34.789594,lng:135.438084}, //to jpn

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

var coordinates = [
  [
    //mas
    {lat:2.745537, lng:101.707316}, {lat:37.460353,lng:126.440674}, //to kor
    {lat:2.745537, lng:101.707316}, {lat:34.789594,lng:135.438084}, //to jpn
    {lat:2.745537, lng:101.707316}, {lat:-37.665357,lng:144.840642}, //to aus
    {lat:2.745537, lng:101.707316}, {lat:40.085148,lng:116.552407}, //to chi
    {lat:2.745537, lng:101.707316}, {lat:-6.127211,lng:106.653684}, //to ind
    {lat:2.745537, lng:101.707316}, {lat:1.364860,lng:103.991594}, //to sin
    {lat:2.745537, lng:101.707316}, {lat:40.498275,lng:-3.567727}, //to spa
  ],[
    //kor
    {lat:36.460353, lng:126.440674}, {lat:34.789594,lng:135.438084}, //to jpn
    {lat:36.460353, lng:126.440674}, {lat:55.410343,lng:37.902312}, //to rus
    {lat:36.460353, lng:126.440674}, {lat:40.085148,lng:116.552407}, //to chi
  ]
];

Затем обработайте массив верхнего уровня, создав отдельные полилинии:

for (var i=0; i<coordinates.length; i++) {
  // Creates the polyline object
  var polyline = new google.maps.Polyline({
    map: map,
    path: coordinates[i],
    strokeColor: '#0000FF',
    strokeOpacity: 0.7,
    strokeWeight: 1,
    geodesic: true
  });
  // Fit the bounds of the generated points
  polyline.setMap(map);
}

подтверждение концепции скрипки

screenshot of resulting map

$(document).ready(function() {
  // If the browser supports the Geolocation API
  if (typeof navigator.geolocation == "undefined") {
    $("#error").text("Your browser doesn't support the Geolocation API");
    return;
  }
  // Save the positions' history
  var path = [];

  // Create the map
  var myOptions = {
    zoom: 2,
    center: {
      lat: 48.019573,
      lng: 66.923684
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map"), myOptions);

  path.push(new google.maps.LatLng(2.745537, 101.707316)); //mas
  path.push(new google.maps.LatLng(37.460353, 126.440674)); //kor
  path.push(new google.maps.LatLng(34.789594, 135.438084)); //jpn
  path.push(new google.maps.LatLng(-37.665357, 144.840642)); //aus
  path.push(new google.maps.LatLng(55.410343, 37.902312)); //rus
  path.push(new google.maps.LatLng(40.085148, 116.552407)); //chi
  path.push(new google.maps.LatLng(-6.127211, 106.653684)); //ind
  path.push(new google.maps.LatLng(1.364860, 103.991594)); //sin
  path.push(new google.maps.LatLng(40.760284, -73.772304)); //usa
  path.push(new google.maps.LatLng(53.358796, -2.272773)); //uk
  path.push(new google.maps.LatLng(40.498275, -3.567727)); //spa

  // Create the array that will be used to fit the view to the points range and
  // place the markers to the polyline's points
  var latLngBounds = new google.maps.LatLngBounds();
  for (var i = 0; i < path.length; i++) {
    latLngBounds.extend(path[i]);
    // Place the marker
    new google.maps.Marker({
      map: map,
      position: path[i],
      title: "Point " + (i + 1)
    });
  }
  var coordinates = [
    [
      //mas
      {lat:2.745537, lng:101.707316}, {lat:37.460353,lng:126.440674}, //to kor
      {lat:2.745537, lng:101.707316}, {lat:34.789594,lng:135.438084}, //to jpn
      {lat:2.745537, lng:101.707316}, {lat:-37.665357,lng:144.840642}, //to aus
      {lat:2.745537, lng:101.707316}, {lat:40.085148,lng:116.552407}, //to chi
      {lat:2.745537, lng:101.707316}, {lat:-6.127211,lng:106.653684}, //to ind
      {lat:2.745537, lng:101.707316}, {lat:1.364860,lng:103.991594}, //to sin
      {lat:2.745537, lng:101.707316}, {lat:40.498275,lng:-3.567727}, //to spa
    ],[
      //kor
      {lat:36.460353, lng:126.440674}, {lat:34.789594,lng:135.438084}, //to jpn
      {lat:36.460353, lng:126.440674}, {lat:55.410343,lng:37.902312}, //to rus
      {lat:36.460353, lng:126.440674}, {lat:40.085148,lng:116.552407}, //to chi
    ]
  ];
  for (var i = 0; i < coordinates.length; i++) {
    // Creates the polyline object
    var polyline = new google.maps.Polyline({
      map: map,
      path: coordinates[i],
      strokeColor: '#0000FF',
      strokeOpacity: 0.7,
      strokeWeight: 1,
      geodesic: true
    });
    // Fit the bounds of the generated points
    polyline.setMap(map);
  }
});
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="map"></div>
<div id="error"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
...