Открыть карту с маршрутами, предварительно заряженными из массива с помощью Mapbox - PullRequest
0 голосов
/ 04 августа 2020

Я пытаюсь работать с Mapbox (потому что Карты теперь платные), и мой сервис в основном:

  1. Пользователь создает маршрут, касаясь карты *** Сервис принимает координаты и create
  2. Созданный маршрут сохраняется в базе данных (js или php, я понятия не имею, как лучше это сделать)
  3. После закрытия windows, когда пользователь возвращается на веб-сайт, маршруты (шаг 1) будут там.

Моя настоящая проблема - точно показать маршрут, я не могу понять документацию ... Итак, я использую массив для каждого щелчка (и это работает), но как завершить следующий шаг (4)?

Код ниже:

    <script>
      var truckLocation = [-49.3766505877158, -20.80796326493855];
      var warehouseLocation = [-49.3766505877158, -20.80796326493855];
      var lastQueryTime = 0;
      var lastAtRestaurant = 0;
      var keepTrack = [];
      var currentSchedule = [];
      var currentRoute = null;
      var pointHopper = {};
      var pause = true;
      var speedFactor = 50;
      var capturaCoordenada = ['lat,long'];
      var exibeCoordenada ="";




      // Add your access token
      mapboxgl.accessToken = 'personal token';

      // Initialize a map
 
      var map = new mapboxgl.Map({
        container: 'map', // container id
        style: 'mapbox://styles/mapbox/light-v10', // stylesheet location
        center: truckLocation, // starting position
        zoom: 15 // starting zoom
      });
var warehouse = turf.featureCollection([turf.point(warehouseLocation)]);
      map.on('load', function() {
  var marker = document.createElement('div');
  marker.classList = 'onibus';


// Create a new marker
var truckMarker = new mapboxgl.Marker(truckMarker)
.setLngLat(truckLocation)
.addTo(map);
});

// Create a circle layer
map.on('load', function() {
  map.addSource("points", {
    "type": "geojson",
    "data": warehouseLocation
  })

map.addLayer({
  id: 'warehouse',
  type: 'circle',
  source: {
    data: warehouse,
    type: 'geojson'
  },
  paint: {
    'circle-radius': 20,
    'circle-color': 'white',
    'circle-stroke-color': '#4287f5',
    'circle-stroke-width': 3
  }
});

// Create a symbol layer on top of circle layer
map.addLayer({
  id: 'warehouse-symbol',
  type: 'geojs',
  source: {
    data: warehouse,
    type: 'geojson'
  },
  layout: {
    'icon-image': 'grocery-15',
    'icon-size': 1
  },
  paint: {
    'text-color': '#3887be'
  }
});


// Create an empty GeoJSON feature collection for drop-off locations
var dropoffs = turf.featureCollection([]);

map.addLayer({
  id: 'dropoffs-symbol',
  type: 'symbol',
  source: {
    data: dropoffs,
    type: 'geojson'
  },
  layout: {
    'icon-allow-overlap': true,
    'icon-ignore-placement': true,
    'icon-image': 'marker-15',
  }
});

// Listen for a click on the map
map.on('click', function(e) {
  // When the map is clicked, add a new drop-off point
  // and update the `dropoffs-symbol` layer
  newDropoff(map.unproject(e.point));
  updateDropoffs(dropoffs);
});
function newDropoff(coords) {
  // Store the clicked point as a new GeoJSON feature with
  // two properties: `orderTime` and `key`
  var pt = turf.point(
    [coords.lng, coords.lat],
    {
      orderTime: Date.now(),
      key: Math.random()
    }
  );
  dropoffs.features.push(pt);
}

function updateDropoffs(geojson) {
  map.getSource('dropoffs-symbol')
    .setData(geojson);
}

// Create an empty GeoJSON feature collection, which will be used as the data source for the route before users add any new data
var nothing = turf.featureCollection([]);

map.addSource('route', {
  type: 'geojson',
  data: nothing
});

map.addLayer({
  id: 'routeline-active',
  type: 'line',
  source: 'route',
  layout: {
    'line-join': 'round',
    'line-cap': 'round'
  },
  paint: {
    'line-color': '#3887be',
    'line-width': [
      "interpolate",
      ["linear"],
      ["zoom"],
      12, 3,
      22, 12
    ]
  }
}, 'waterway-label');

// Here you'll specify all the parameters necessary for requesting a response from the Optimization API
function assembleQueryURL() {

  // Store the location of the truck in a variable called coordinates
  var coordinates = [truckLocation];
  var distributions = [];
  keepTrack = [truckLocation];

  // Create an array of GeoJSON feature collections for each point
  var restJobs = objectToArray(pointHopper);

  // If there are any orders from this restaurant
  if (restJobs.length > 0) {

    // Check to see if the request was made after visiting the restaurant
    var needToPickUp = restJobs.filter(function(d, i) {
      return d.properties.orderTime > lastAtRestaurant;
    }).length > 0;

    // If the request was made after picking up from the restaurant,
    // Add the restaurant as an additional stop
    if (needToPickUp) {
      var restaurantIndex = coordinates.length;
      // Add the restaurant as a coordinate
      coordinates.push(warehouseLocation);
      capturaCoordenada = coordinates; //Retorna a coordenada clicada
      capturaCoordenada.push();
     
      // push the restaurant itself into the array
      keepTrack.push(pointHopper.warehouse);
    }

    restJobs.forEach(function(d, i) {
      // Add dropoff to list
      keepTrack.push(d);
      coordinates.push(d.geometry.coordinates);

      // if order not yet picked up, add a reroute
      if (needToPickUp && d.properties.orderTime > lastAtRestaurant) {
        distributions.push(restaurantIndex + ',' + (coordinates.length - 1));
      }
    });
  }
  // Set the profile to `driving`
  // Coordinates will include the current location of the truck,
  return 'https://api.mapbox.com/optimized-trips/v1/mapbox/driving/' + coordinates.join(';') + '?distributions=' + distributions.join(';') + '&overview=full&steps=true&geometries=geojson&source=first&access_token=' + mapboxgl.accessToken;
}

function objectToArray(obj) {
  var keys = Object.keys(obj);
  var routeGeoJSON = keys.map(function(key) {
    return obj[key];
  });
  return routeGeoJSON;
}
function newDropoff(coords) {
  // Store the clicked point as a new GeoJSON feature with
  // two properties: `orderTime` and `key`
  var pt = turf.point(
    [coords.lng, coords.lat],
    {
      orderTime: Date.now(),
      key: Math.random()
    }
  );
  dropoffs.features.push(pt);
  pointHopper[pt.properties.key] = pt;

  // Make a request to the Optimization API
  $.ajax({
    method: 'GET',
    url: assembleQueryURL(),
  }).done(function(data) {
    // Create a GeoJSON feature collection
    var routeGeoJSON = turf.featureCollection([turf.feature(data.trips[0].geometry)]);

    // If there is no route provided, reset
    if (!data.trips[0]) {
      routeGeoJSON = nothing;
    } else {
      // Update the `route` source by getting the route source
      // and setting the data equal to routeGeoJSON
      map.getSource('route')
        .setData(routeGeoJSON);
    }

    if (data.waypoints.length === 12) {

        for (var i = 0; i < capturaCoordenada.length; i++) {
        var lat = capturaCoordenada[lat];
        var long = capturaCoordenada[long];
        exibeCoordenada = exibeCoordenada + "\n" + capturaCoordenada[i] + capturaCoordenada[long]; }
        exibeCoordenada = exibeCoordenada + "\n";
        // for (var i = 0; i < capturaCoordenada.length; i+=2) {
        // var x = capturaCoordenada[i];
        // var y = capturaCoordenada[i+1];
        // exibeCoordenada = exibeCoordenada + "\n" + capturaCoordenada[x] + capturaCoordenada[y]; }
        // exibeCoordenada = exibeCoordenada + "\n";
        window.alert(exibeCoordenada);
        
    }
  });
}
map.addLayer({
  id: 'routearrows',
  type: 'symbol',
  source: 'route',
  layout: {
    'symbol-placement': 'line',
    'text-field': '▶',
    'text-size': [
      "interpolate",
      ["linear"],
      ["zoom"],
      12, 24,
      22, 60
    ],
    'symbol-spacing': [
      "interpolate",
      ["linear"],
      ["zoom"],
      12, 30,
      22, 160
    ],
    'text-keep-upright': false
  },
  paint: {
    'text-color': '#3887be',
    'text-halo-color': 'hsl(55, 11%, 96%)',
    'text-halo-width': 3
  }
}, 'waterway-label');

});     </script>
...