简体   繁体   中英

Mapbox - Trying to add a route between several markers

I am trying to learn JS and creating maps with the Mapbox GL JS and Directions. I managed to add markers to a map, and now I would like to add a route between the markers (1 -> 2 -> 3 -> 4).

After playing around for several time now, I got stuck. The markers are added, but no route is shown.

Would be create if you could help me:)

Thanks, Ben

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.11.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.11.0/mapbox-gl.css' rel='stylesheet' />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <style>
      body {
        margin: 0;
        padding: 0;
      }

      #map {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
      }
      
      .marker {
          background-image: url('mapbox-icon.png');
          background-size: cover;
          width: 50px;
          height: 50px;
          border-radius: 50%;
          cursor: pointer;
        }
    </style>
</head>
<body>

<div id='map'></div>

<script>

mapboxgl.accessToken = 'xxx';

var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/light-v10',
  center: [-122.662323, 45.523751],
  zoom: 11
});

// code from the next step will go here!
var geojson = {
  type: 'FeatureCollection',
  features: [{
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates: [-122.662323, 45.523751]
    },
    properties: {
      title: 'Mapbox',
      description: 'Washington, D.C.'
    }
  },
  {
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates: [-122.692323, 45.523751]
    },
    properties: {
      title: 'Mapbox',
      description: 'San Francisco, California'
    }

  },
    {
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates: [-122.612323, 45.523751]
    },
    properties: {
      title: 'Mapbox',
      description: 'San Francisco, California'
    }

  },
  {
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates: [-122.682323, 45.523751]
    },
    properties: {
      title: 'Mapbox',
      description: 'San Francisco, California'
    }

  }]
};

// add markers to map
geojson.features.forEach(function(marker) {

  // create a HTML element for each feature
  var el = document.createElement('div');
  el.className = 'marker';

  // make a marker for each feature and add to the map
  new mapboxgl.Marker(el)
    .setLngLat(marker.geometry.coordinates)
    .addTo(map);

    
});



map.on('load', () => {
for (i = 0; i < geojson.length; i++) {
  
  for(j = i+1; j < geojson.length; j++) {

    var geomFrom = geojson[i];
    var geomTo = geojson[j];

      $.get(`https://api.mapbox.com/directions/v5/mapbox/driving/` + geomFrom[0] + ',' + geoFrom[1] + ';' + geomTo[0] + ',' + geomTo[1] + `?access_token=${mapboxgl.accessToken}&geometries=geojson`, data => {
   

    map.addLayer({
      id: 'route',
      type: 'line',
      source: {
        type: 'geojson',
        data: {
          type: 'Feature',
          properties: {},
          geometry: data.routes[0].geometry,
        },
      },
      layout: {
        'line-join': 'round',
        'line-cap': 'round',
      },
      paint: {
        'line-color': '#ff7e5f',
        'line-width': 8,
      },
    })
  
  })

  };

 
};


});
</script>

</body>
</html>

There are many issues I have found in the code, but long story short, the source you are creating is wrongly created. To simplify the explanation I had to remove the double for loop and the call to the service to show you how you should create the source for the path.

I have shaped this fiddle creating a path in Portland .

在此处输入图像描述

Here is the relevant js code for the layer you have to create:

      map.addLayer({
        id: 'route',
        type: 'line',
        source: {
          'type': 'geojson',
          'data': {
            'type': 'Feature',
            'properties': {},
            'geometry': {
              'type': 'LineString',
              'coordinates': [
                [
                  -122.68035572839027,
                  45.52729517240144
                ],
                [
                  -122.67657260381876,
                  45.527330174436116
                ],
                [
                  -122.67657129671815,
                  45.52666556739695
                ],
                [
                  -122.67085005715236,
                  45.52677044480427
                ],
                [
                  -122.66645605237485,
                  45.52862702776275
                ],
                [
                  -122.66560830926798,
                  45.52866212597536
                ],
                [
                  -122.66532421497476,
                  45.52712020010674
                ],
                [
                  -122.6654770006126,
                  45.52158881104725
                ],
                [
                  -122.66684678096325,
                  45.51749007039993
                ]
              ],
            },
          }
        },
        layout: {
          'line-join': 'round',
          'line-cap': 'round'
        },
        paint: {
          'line-color': '#888',
          'line-width': 8
        }
      })

Now knowing how this layer needs to be created, you can surely bring back your loops and the call to the service, but as long you are double looping you'll be creating a layer per loop, which is definitely NOT desirable nor recommendable.

I also noted the coords of the your geojson source are repeated and the coords do not correspond to the places indicated, but I ignored them for the sample in the fiddle.

If this answer solves your question about how to add a route between several markers , please mark it as answer accepted , in this way it will also help other users to know it was the right solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM