¿Cómo conectar coordenadas LatLng específicas con polilínea sin que se conecte automáticamente a otros puntos?

5 minutos de lectura

avatar de usuario de cartmanbrahhhhh
brahhhhh

Estoy creando una página que muestra un mapa mundial con marcadores colocados en coordenadas LatLng y estoy tratando de vincularlos con polilíneas. Sin embargo, no quiero que cada uno de ellos esté vinculado entre sí. Por ejemplo, dado un conjunto {A,B,C,D,E,F}, los enlaces son A->B, B->C y C->D, también A->E.

Cuando trato de hacer D->F, D->E aparece mágicamente incluso cuando no lo especifiqué.

Inicialmente probé con la matriz de ruta predeterminada, pero no funcionó, así que usé otra matriz llamada coordenadas. Las primeras polilíneas se dibujaron desde un punto específico y no tuvo problemas, pero cuando trato de dibujar de otro punto a otro, funciona pero también aparecieron polilíneas que no especifiqué.

$(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

captura de pantalla del mapa

Espero que el punto de Corea del Sur solo se conecte a Moscú, China, Japón y Malasia, no a España.

Solo estás haciendo una polilínea. Conecta todos los puntos de la coordinates formación. Entonces va de españa a corea.

{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

La solución más simple, hacer múltiples polilíneas separadas. Convierta su matriz existente en una matriz de matrices, con cada matriz interna que contenga las coordenadas para cada polilínea separada.

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
  ]
];

Luego procese a través de la matriz de nivel superior haciendo polilíneas separadas:

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);
}

violín de prueba de concepto

captura de pantalla del mapa resultante

$(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>

¿Ha sido útil esta solución?