-2

I'm trying to replicate similar functionality in Google Maps where you right click & it gives an option to have directions to/from that point. The struggle I'm having is interacting with the infowindow & passing the lat/longs back.

The listener creates the infowindow fine. but I can;t work out how to pass the lat/longs back into the javascript (either as an origin or destination) so as I can then use it in the directions service. I'll eventually have a second marker which will populate the other value in origin/destination. Once the array has two values I'll call the directions service.

All the examples I've seen have required some form of manual input to define the second part of the address.

I'm still very new to this, so please go easy on me; I've tried my best to provide the most trimmed down sample code to demonstrate my issue.

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>
user3533028
  • 9
  • 1
  • 5
  • Something like [this](http://www.geocodezip.com/v3_MW_example_map4c.html)? – geocodezip Nov 01 '18 at 23:35
  • That's the closest example I've seen, but not quite; that still requires a manual input. Also, I'm unsure how it derives lat & long when you press the links. Finally, no idea why I keep getting downvoted. Is the question not clear enough? – user3533028 Nov 02 '18 at 08:45
  • Running your code snippet generates a script error. And did you watch your javascript console as well for additional errors? Also your question is **unclear** as to what you are having an issue with and how you want it to work. The provided code doesn't contain an implementation of a Directions request. When is this supposed to happen? Following which action? Make your question clear and have your code reflect what you say you are trying to do. That might also prevent people from down-voting. – MrUpsidown Nov 02 '18 at 10:22
  • I thought the script error was because I had omitted my maps API key? At this stage I'm OK with the directions service end of things, hence why it is omitted. I'll work through your answer below and see how I get on. Thanks for your help & feedback. – user3533028 Nov 02 '18 at 11:24
  • Yeah sorry, that script error comes anyway it seems. Don't know why. Anyway you have a working example you can check now and adapt to your needs. – MrUpsidown Nov 02 '18 at 11:29
  • What do you mean by "requires manual input"? Do you want to do "marker to marker" directions? – geocodezip Nov 02 '18 at 14:11
  • He wants point to point as in my answer. Your example requires manual input of either start or end address. – MrUpsidown Nov 02 '18 at 14:33

1 Answers1

1

Here is a simple example of how you can do that, using vanilla Javascript only. Code is commented. That should be enough to understand how it works.

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?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk
"></script>
MrUpsidown
  • 21,592
  • 15
  • 77
  • 131