Направления к / от здесь информационного окна в API Карт - PullRequest
0 голосов
/ 02 ноября 2018

Я пытаюсь повторить аналогичную функциональность в Картах Google, где вы щелкаете правой кнопкой мыши, и это дает возможность указать направление к / от этой точки. Моя борьба заключается во взаимодействии с информационным окном и возвращении широты / долготы назад.

Слушатель создает штраф в информационном окне. но я не могу понять, как передать lat / longs обратно в javascript (в качестве источника или места назначения), чтобы затем использовать его в службе указаний. В конечном итоге у меня будет второй маркер, который заполнит другое значение в источнике / пункте назначения. Как только массив получит два значения, я позвоню в службу указателей.

Все примеры, которые я видел, требовали некоторой формы ручного ввода для определения второй части адреса.

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

var mapCanvas = "map-canvas",
	map,
	infowindow = new google.maps.InfoWindow(),
	LocationArr = [],
	o;

google.maps.event.addDomListener(window, "load", function(){
	map = new google.maps.Map(document.getElementById(mapCanvas), {zoom: 13,center: {lat: 53.4723272,lng: -2.2935022}});
    var geocoder = new google.maps.Geocoder;
    google.maps.event.addListener(map, "click", function(o) {
        LocationArr.push(o.latLng);
        var a = new google.maps.Marker({
            position: o.latLng,
            map: map,
        });
		var content =  "<input type='button' name='DirFrom' value='Directions from here' onclick='DirFromHere()' id='Dir_From'>"
					 + "<input type='button' name='DirTo'   value='Directions to here'   onclick='DirToHere()'   id='Dir_To'>"
		infowindow.setContent(content);	
		infowindow.open(map, a);
    });

});
								 
function DirFromHere(LocationArr){
	console.log(LocationArr.length);
}

function DirToHere(LocationArr){
	LocationArr=[];
}
html, body {
	height: 100%;
	width: 100%;
}

#map-canvas {
	position: absolute;
	top:  0%;
	left: 0%;
	width: 100%;
	height: 100%;
}
<html>
	<head>
		<link href="css/styles.css" rel="stylesheet" type="text/css" />
	</head>
	<body>
		<div id="map-canvas"></div>
		<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
		<script src="js/aqrouting.js"></script>
	</body>
</html>

1 Ответ

0 голосов
/ 02 ноября 2018

Вот простой пример того, как вы можете сделать это, используя только ванильный Javascript. Код прокомментирован. Этого должно быть достаточно, чтобы понять, как это работает.

var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map, infowindow;
var start, end, pos;

function initialize() {

  directionsDisplay = new google.maps.DirectionsRenderer();

  // Map options
  var center = new google.maps.LatLng(45.07, 7.67);
  var myOptions = {
    zoom: 12,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: center
  }

  // Create map
  map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
  directionsDisplay.setMap(map);

  // Create infowindow
  infowindow = new google.maps.InfoWindow({
    content: '',
    map: map
  });

  // Listen for map click
  google.maps.event.addListener(map, 'click', function(e) {

    // Save current position
    pos = e.latLng;

    // Set infowindow position and open
    infowindow.setPosition(pos);
    infowindow.open(map)
  });

  // Create infowindow buttons
  let btnFrom = document.createElement("button");
  btnFrom.id = 'directionsFrom';
  btnFrom.innerHTML = 'Directions from here'

  let btnTo = document.createElement("button");
  btnTo.id = 'directionsTo';
  btnTo.innerHTML = 'Directions to here'

  // Add DOM listener to DIRECTIONS FROM button
  google.maps.event.addDomListener(btnFrom, 'click', function() {

    // Set start position
    start = pos;
  });

  // Add DOM listener to DIRECTIONS TO button
  google.maps.event.addDomListener(btnTo, 'click', function() {

    // Set end position
    end = pos;

    // Check that start and end position both are an instance of LatLng
    if ((start instanceof google.maps.LatLng) && (end instanceof google.maps.LatLng)) {

      // We have a start and end position so we can request directions
      getDirections();
    }
  });

  // Add the 2 buttons in a DIV
  let contentDiv = document.createElement('div');
  contentDiv.appendChild(btnFrom);
  contentDiv.appendChild(btnTo);

  // Add the DIV as the infowindow content
  infowindow.setContent(contentDiv);
}

// Make a Directions request and display it on the map
function getDirections() {

  var method = 'DRIVING';
  var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.DirectionsTravelMode[method]
  };

  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);

      // Close infowindow
      infowindow.close();
    }
  });
}

initialize();
#map-canvas {
  height: 150px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js"></script>
...