маркеры обновления mapbox с интервалом в 10 секунд - PullRequest
0 голосов
/ 03 февраля 2020

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

if (!('remove' in Element.prototype)) {
  Element.prototype.remove = function() {
    if (this.parentNode) {
      this.parentNode.removeChild(this);
    }
  };
}

mapboxgl.accessToken = 'pk.eyJ1rsdaseaffghfhdfdhfejU2Y3k1MGJscTNwcWdwbDloOHoxeiJ9.LUcCWLx_eEOpjWjQxW1xgw';

// This adds the map to the page
var map = new mapboxgl.Map({
  // container id specified in the HTML
  container: 'map',
  // style URL
  style: 'mapbox://styles/mapbox/light-v9',
  // initial position in [lon, lat] format

  center: [15.970824, 45.8125225],
  // initial zoom
  zoom: 9
});


stores='https://e-twow.app/gps/geojson.php?acces=96'

map.on('load', () => {
  fetch(stores)
    .then(response => response.json())
    .then((data) => {
      map.addSource("locations", {
        type: 'geojson',
        data: data
      });



      buildLocationList(data);
      function buildLocationList(data) {
  // Iterate through the list of stores
  for(i=0; i < data.features.length; i++) {
    var currentFeature = data.features[i];

    // Shorten data.feature.properties to just `prop` so we're not
    // writing this long form over and over again.
    var prop = currentFeature.properties;

    // Select the listing container in the HTML and append a div
    // with the class 'item' for each store
    var listings = document.getElementById('listings');
    var listing = listings.appendChild(document.createElement('div'));
    listing.className = 'item';
    listing.id = 'listing' + i;

    // Create a new link with the class 'title' for each store
    // and fill it with the store address
    var link = listing.appendChild(document.createElement('a'));
   link.href = '#';
   link.className = 'title';
   link.dataPosition = i;
   link.innerHTML = prop.title;
   // Add an event listener for the links in the sidebar listing
link.addEventListener('click', function(e) {
  // Update the currentFeature to the store associated with the clicked link
  var clickedListing = data.features[this.dataPosition];
  // 1. Fly to the point associated with the clicked link
  flyToStore(clickedListing);
  // 2. Close all other popups and display popup for clicked store
  createPopUp(clickedListing);
  // 3. Highlight listing in sidebar (and remove highlight for all other listings)
  var activeItem = document.getElementsByClassName('active');
  if (activeItem[0]) {
    activeItem[0].classList.remove('active');
  }
  this.parentNode.classList.add('active');
});

    // Create a new div with the class 'details' for each store
    // and fill it with the city and phone number
    var details =listing.appendChild(document.createElement('div'));
    details.innerHTML = prop.title;
    if(prop.phone) {
      details.innerHTML += ' &middot; ' + prop.phoneFormatted;
    }
  }
}

//Function to fly to the correct store
function flyToStore(currentFeature) {
  map.flyTo({
    center: currentFeature.geometry.coordinates,
    zoom: 9
  });
}

//Function to display popup features
function createPopUp(currentFeature) {
  var popUps = document.getElementsByClassName ('mapboxgl-popup');
  // Check if there is already a popup on the map and if so, remove it
  if(popUps[0]) popUps[0].remove();

  var popup = new mapboxgl.Popup({closeOnClick: true})
  .setLngLat(currentFeature.geometry.coordinates)
  .setHTML('<h3>E-TWOW ' + currentFeature.properties.title +'</h3> <h2><a href="https://eou.app/gps/action.php?auth=Rxxxx&location=Los%20Angeles&scooter_id=RO0008&status=1">ON</a></h2>\
  <h2><a href="https://eou.app/gps/action.php?auth=Rxxxxx&location=Los%20Angeles&scooter_id=RO0008&status=1">OFF</a></h2>\
  <h2><a href="https://eou.app/gps/action.php?auth=Rxxxxx&location=Los%20Angeles&scooter_id=RO0008&status=1">ANTI TEFT</a></h2>\
  <h2><a href="https://eou.app/gps/action.php?auth=Rxxxxxx&location=Los%20Angeles&scooter_id=RO0008&status=1">6 KM/H</a></h2>\
  <h2><a href="https://eou.app/gps/action.php?auth=Rxxxxxx&location=Los%20Angeles&scooter_id=RO0008&status=1">12 KM/H</a></h2>\
  <h2><a href="https://eou.app/gps/action.php?auth=Rxxxxxxx&location=Los%20Angeles&scooter_id=RO0008&status=1">20 KM/H</a></h2>\
  <h2><a href="https://eou.app/gps/action.php?auth=Rxxxxxx&location=Los%20Angeles&scooter_id=RO0008&status=1">25 KM/h</a></h2>\
  <h2><a href="https://eou.app/gps/action.php?auth=Rxxxxx&location=Los%20Angeles&scooter_id=RO0008&status=1">30 KM/h</a></h2>')
  .addTo(map);
}

//// Add an event listener for when a user clicks on the map

data.features.forEach(function(marker) {
  // Create a div element for the marker
  var el = document.createElement('div');
  // Add a class called 'marker' to each div
  el.className = 'marker';
  // By default the image for your custom marker will be anchored
  // by its center. Adjust the position accordingly
  // Create the custom markers, set their position, and add to map
  new mapboxgl.Marker(el, { offset: [0, -23] })
    .setLngLat(marker.geometry.coordinates)
    .addTo(map);
    el.addEventListener('click', function(e) {
    var activeItem = document.getElementsByClassName('active');
    // 1. Fly to the point
    flyToStore(marker);
    // 2. Close all other popups and display popup for clicked store
    createPopUp(marker);
    // 3. Highlight listing in sidebar (and remove highlight for all other listings)
    e.stopPropagation();
    if (activeItem[0]) {
      activeItem[0].classList.remove('active');
    }

    var listing = document.getElementById('listing-' + i);
    console.log(listing);
    listing.classList.add('active');
  });
});
    });
});

1 Ответ

0 голосов
/ 18 марта 2020

Мой ответ на это другое сообщение о переполнении стека должно подробно ответить на ваш вопрос. Как отмечено в связанном ответе, есть два способа добавить маркеры на карту Mapbox GL JS - используя источники и слои или добавляя экземпляры объекта Marker. Ваша текущая реализация использует Marker s. Если вы хотите продолжать использовать Marker s вместо источников и слоев, вы можете сохранить все Marker s в виде массива markers и сделать что-то вроде:

/** 
 * The implementation details here will depend on your location database. 
 * The method takes a Marker instance and returns the corresponding location 
 * in the database.
 * @param {Marker} marker
 * @returns {LngLatLike} a LngLatLike describing the corresponding scooter's
 * current location.
 */
function getCurrentLocation(marker) { ... }

window.setInterval(function() {
  markers.forEach(marker => {
    marker.setLngLat(getCurrentLocation(marker))
  }
}, 10000 /* set an interval for every 10 seconds */);

Это будет иметь эффект обновления местоположения каждого маркера на карте каждые 10 секунд без перезагрузки всей карты.

...