Как вы отслеживаете положение пользователя и проверяете, находятся ли они на маршруте, с помощью Google Maps Javascript API - PullRequest
0 голосов
/ 23 апреля 2020

помогите мне определить ошибки в коде, он ничего не отображает.

Я новичок ie, когда дело доходит до javascript, но я пытаюсь решить эту проблему, которая включает отслеживание позиции пользователя и определение того, находится ли пользователь в пределах нарисованных полилиний. Я планирую включить ОЧЕНЬ больше полилиний, но сейчас я включил только 3. Я собрал этот код, используя идеи из документации Google Maps и стекового потока. Кроме того, я включил библиотеку отслеживания пользователей (находится по адресу: https://chadkillingsworth.github.io/geolocation-marker/), на которую я также ссылаюсь в коде.

var addresses = [
  [[43.647360, -79.399146],[43.646514, -79.403610]],
  [[43.646793, -79.395252],[43.648276, -79.388289]],
  [[43.641363, -79.393197],[43.642779, -79.393827]]
];

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var bounds;
var GeoMarker, pos;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var basel = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = {
    zoom: 14,
    center: basel
  }
 map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
  directionsDisplay.setMap(map);
  bounds = new google.maps.LatLngBounds();
}


var delay = 100;

function calcRoute(start, end, next) {
  console.log("calcRoute('" + start + "','" + end + "',next)");
  var request = {
    origin: start,
    destination: end,
    travelMode: 'BICYCLING'
  };
  directionsService.route(request,
    function(result, status) {
      if (status == 'OK') { 
directionsDisplay = new google.maps.DirectionsRenderer({
          suppressBicyclingLayer: true,
          suppressMarkers: true,
          preserveViewport: true // don't zoom to fit the route
        });
        directionsDisplay.setMap(map);
        directionsDisplay.setDirections(result);
        // combine the bounds of the responses
        bounds.union(result.routes[0].bounds);
        // zoom and center the map to show all the routes
        map.fitBounds(bounds);
      }
      // ====== Decode the error status ======
      else {
        console.log("status=" + status + " (start=" + start + ", end=" + end + ")");
        // === if we were sending the requests to fast, try this one again and increase the delay
        if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
          nextAddress--;
          delay += 100;
          document.getElementById('delay').innerHTML = "delay between requests="+delay;
        } else {
          window.alert('Directions request failed due to' + status);
        }
      }
      next();
    });
}

initialize();

var nextAddress = 0;

// ======= Function to call the next Geocode operation when the reply comes back

function theNext() {
  if (nextAddress < addresses.length) {
    console.log('call calcRoute("' + addresses[nextAddress][0] + '","' + addresses[nextAddress][1] + ') delay=' + delay);
    setTimeout('calcRoute("' + addresses[nextAddress][0] + '","' + addresses[nextAddress][1] + '",theNext)', delay);
    nextAddress++;
  } else {
    map.fitBounds(bounds);
  }
}

// ======= Call that function for the first time =======
theNext();

GeoMarker = new GeolocationMarker();
        GeoMarker.setCircleOptions({fillColor: '#808080'});
        pos = this.getPosition()

        google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
          map.setCenter(this.getPosition());
          pos = this.getPosition()
          map.fitBounds(this.getBounds());
          google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
        });
          alert('There was an error obtaining your position. Message: ' + e.message);
        });

        GeoMarker.setMap(map);
      }

      google.maps.event.addDomListener(window, 'load', initialize);

      if(!navigator.geolocation) {
        alert('Your browser does not support geolocation');
      }
for (k = 0; k < addresses.length; k++) {
 if (google.maps.geometry.poly.isLocationOnEdge(pos, new google.maps.Polyline({path: addresses[k]}), 10e-1)) {
    alert("en route" addresses[k]);
  }
  else {
      alert("not en route" addresses[k]); 
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...