Приложение для Google Maps API текущего местоположения для центрирования исходной карты и использования в качестве источника в моем приложении. Пункт назначения, по которому нажимается карта - PullRequest
0 голосов
/ 02 мая 2018

Я выделил жирным шрифтом то, что мне нужно, изменил в своем приложении, я не могу понять, как заставить его работать, используя текущее местоположение пользователя на сайте, чтобы центрировать карту и использовать в качестве исходного значения для Направлений API, а также у меня есть статическое значение в качестве пункта назначения, но я хочу изменить его на «нажал»

По сути, не обращайте внимания на путевые точки, но я хочу, чтобы это загружало карту в местоположении пользователей, вводило это значение как ORIGIN, и вместо статического назначения я хочу, чтобы пользователь нажимал, а затем он запускался, давая указания от того, где они находятся, где они нажали

" `var waypts = new Array();
<!-- var directionsService; -->
<!-- var directionsDisplay; -->
var bool = false, bool1 = false;
function initMap() {
  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer;
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6,
    center: {lat: CURRENT LOCATION, lng: CURRENT LOCATION}
  });
  directionsDisplay.setMap(map);
  calculateAndDisplayRoute(directionsService, directionsDisplay);


}

function calculateAndDisplayRoute(directionsService, directionsDisplay) {


  var locations = new Array(I have waypoints I enter here)
  var channel_id = KEY;
    var api_key = 'KEY';
    var bin = [];

    var j=0, k=0;
    for(i=1; i<=locations.length; i++){
        $.getJSON('http://api.thingspeak.com/channels/' + channel_id + '/field/' + i + '/last',
            function(data) { 
                if(data > 0)  {
                    waypts.push({
                      location: '' + locations[j++],
                      stopover: true
                      });
                }
            k++; if(k==locations.length) { show(directionsService, directionsDisplay); }
            });

    }

    function show(directionsService, directionsDisplay){
console.log(waypts);
  directionsService.route({
    origin: 'NEED CURRENT VALUE',
    destination: 'CLICK ON MAP',
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: 'DRIVING'
  }, function(response, status) {
    if (status === 'OK') {
      //document.getElementById('waypoints').innerHTML = response.routes[0].waypoint_order;
      directionsDisplay.setDirections(response);
      var route = response.routes[0];
      var summaryPanel = document.getElementById('directions-panel');
      //summaryPanel.innerHTML = '';
      // For each route, display summary information.
      console.log(route);
      for (var i = 0; i < route.legs.length; i++) {
        var routeSegment = i + 1;
        <!-- summaryPanel.innerHTML += Route.legs[i]; -->
        <!-- document.getElementById("directions-panel").innerHTML= route.legs[i].start_address + '<br>'; -->
        //summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + 
        //'</b><br>';
        //document.getElementById("ul_list").innerHTML+= '<li>'+route.legs[i].start_address +'</li>'; 
        for (var j = 0; j < route.legs[i].steps.length; j++) {
            document.getElementById("ul_list").innerHTML+= '<li>'+route.legs[i].steps[j].instructions +'</li>'; 
        }
        //document.getElementById("ul_list").innerHTML+=  '<li>'+route.legs[i].end_address +'<li>';
        //document.getElementById("#buttet2").innerHTML= route.legs[i].end_address + '<br>'; 
        //summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';

      }
      document.getElementById("ul_list").innerHTML+= '<li>'+route.legs[i].start_address +'</li>'; 
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });

  bool = true;
}

</script>
</body>
</html>`

1 Ответ

0 голосов
/ 02 мая 2018

Вы можете использовать объект HTML5 Geolocation , чтобы получить текущее местоположение пользователя (если браузер поддерживает его, и пользователь предоставил приложению разрешение на использование своего местоположения) в качестве объекта google.maps.LatLng, который может установить как origin для запроса маршрута. Затем вы можете установить click обработчик событий для объекта google.maps.Map, чтобы получить LatLng для местоположения щелчка, а затем вызвать route() метод DirectionsService

Вот простой пример JSBin , который находит местоположение пользователя, но по умолчанию использует Лос-Анджелес, если геолокация не удалась. Происхождение - зеленый круг. Затем вы можете нажать на карту для красного круга, а затем нанесены направления

код:

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map;
      function initMap() {

        var origin = new google.maps.LatLng(34.051659,-118.249085);

        map = new google.maps.Map(document.getElementById('map'), {
          center:  origin,
          zoom: 14,
          gestureHandling: "greedy"
        });

        var marker1 = new google.maps.Marker({
            icon: {path: google.maps.SymbolPath.CIRCLE,
              scale: 5,
              strokeColor: '#338833',
              strokeOpacity: 0.5
            },
            animation:  google.maps.Animation.BOUNCE,
            map: map,
            position: origin,
            title: "start"
        });

        var marker2 = new google.maps.Marker({
            icon: {path: google.maps.SymbolPath.CIRCLE,
              scale: 5,
              strokeColor: '#FF0000',
              strokeOpacity: 0.5
            },
            animation:  google.maps.Animation.BOUNCE,
            map: map,
            title: "finish"
        });

        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            origin = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            map.setCenter(origin);
            marker1.setPosition(origin);
          }, function() {
            alert("Error: The Geolocation service failed. Using default location");
          });
        } else {
          alert("Error: Your browser doesn't support geolocation. Using default location");
        }

        var directionsService = new google.maps.DirectionsService();
        var directionsRenderer = new google.maps.DirectionsRenderer();
        directionsRenderer.setMap(map);

        map.addListener('click', function(event) {
            var destination = event.latLng;
            marker2.setPosition(destination);
            directionsService.route({
                origin: origin,
                destination: destination,
                travelMode: 'DRIVING'
            }, function(response, status) {
              if (status === 'OK') {
            directionsRenderer.setDirections(response);
              } else {
                window.alert('Directions request failed due to ' + status);
              }
            });
        });
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=YOUR_KEY">
    </script>
  </body>
</html>
...