Google map API route from current location to marker

Shane G picture Shane G · Mar 23, 2017 · Viewed 17k times · Source

Working with the Google map API and routes or directions. I would like it such that when a user clicks a marker the route from the user's current location to that marker would render.

I have been studying the Google maps API documentation direction services example here.

Here is my attempt at adapting that. To me it seems this should work, so what am I missing? The route or direction between the user's current location and the marker is not rendering.

<!DOCTYPE html>
<html>

<body>

    <h1>My First Google Map</h1>

    <div id="googleMap" style="width:60%;height:800px;"></div>

    <script>
        var myLatLng;

        function geoSuccess(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            var directionsService = new google.maps.DirectionsService;
            var directionsDisplay = new google.maps.DirectionsRenderer;
            myLatLng = {
                lat: latitude,
                lng: longitude
            };
            var mapProp = {
                //            center: new google.maps.LatLng(latitude, longitude), // puts your current location at the centre of the map,
                zoom: 15,
                mapTypeId: 'roadmap',

            };
            var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

            var directionsService = new google.maps.DirectionsService;
            var directionsDisplay = new google.maps.DirectionsRenderer;

            //call renderer to display directions
            directionsDisplay.setMap(map);

            var bounds = new google.maps.LatLngBounds();
            //        var mapOptions = {
            //            mapTypeId: 'roadmap'
            //        };


            // Multiple Markers
            var marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                title: 'My location'
            });
            var markers = [
                ['Ragazzi', 53.201472, -6.111626],
                ['McDonalds', 53.200482, -6.111337],
                ['my location', latitude, longitude]
            ];

            // Info Window Content
            var infoWindowContent = [
                ['<div>' +
                    '<h3>Ragazzi</h3>' +
                    '<p>Cafe eatin place.</p>' + ' <button onclick="calculateAndDisplayRoute(marker, i)"> Get Directions</button>' + '</div>'
                ],
                ['<div class="info_content">' +
                    '<h3>McDonalds</h3>' +
                    '<p>Excellent food establishment, NOT!.</p>' + '<button onclick="calculateAndDisplayRoute(marker, i)"> Get Directions</button>' +
                    '</div>'
                ]
            ];

            // Display multiple markers on a map
            var infoWindow = new google.maps.InfoWindow(),
                marker, i;

            // Loop through our array of markers & place each one on the map
            for (i = 0; i < markers.length; i++) {
                var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
                bounds.extend(position);
                marker = new google.maps.Marker({
                    position: position,
                    map: map,
                    title: markers[i][0]
                });

                // Allow each marker to have an info window
                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                        infoWindow.setContent(infoWindowContent[i][0]);
                        infoWindow.open(map, marker);
                    }
                })(marker, i));

                marker.addListener('click', function() {

                    directionsService.route({
                        // origin: document.getElementById('start').value,
                        origin: myLatLng,
                        destination: marker.getPosition(),
                        travelMode: 'DRIVING'
                    }, function(response, status) {
                        if (status === 'OK') {
                            directionsDisplay.setDirections(response);
                        } else {
                            window.alert('Directions request failed due to ' + status);
                        }
                    });

                });
                // Automatically center the map fitting all markers on the screen
                map.fitBounds(bounds);
            }
        }

        // function calculateAndDisplayRoute(directionsService, directionsDisplay) {
        //     directionsService.route({
        //         // origin: document.getElementById('start').value,
        //         origin: myLatLng,
        //         destination: marker.getPosition(),
        //         travelMode: 'DRIVING'
        //     }, function(response, status) {
        //         if (status === 'OK') {
        //             console.log('all good');
        //             directionsDisplay.setDirections(response);
        //         } else {
        //             window.alert('Directions request failed due to ' + status);
        //         }
        //     });
        // }

        function geoError() {
            alert("Geocoder failed.");
        }

        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
                // alert("Geolocation is supported by this browser.");
            } else {
                alert("Geolocation is not supported by this browser.");
            }
        }
    </script>

    <script async src="https://maps.googleapis.com/maps/api/js?key=api key here"></script>

</body>

</html>

Thanks,

Answer

Shane G picture Shane G · Mar 25, 2017

I have solved this. The problem was the line,

destination: marker.getPosition(),

was not correct. This was giving me the coordinates of my current location and not the marker clicked.

I set the latit and longit in the function that sets the infoWindow, which have been defined as a global variable,

// Allow each marker to have an info window
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {
                    infoWindow.setContent(infoWindowContent[i][0]);
                    infoWindow.open(map, marker);
                    latit = marker.getPosition().lat();
                    longit = marker.getPosition().lng();
                    // console.log("lat: " + latit);
                    // console.log("lng: " + longit);
                }
            })(marker, i));

Then these are set to the destination,

        marker.addListener('click', function() {
            directionsService.route({
                // origin: document.getElementById('start').value,
                origin: myLatLng,

                // destination: marker.getPosition(),
                destination: {
                    lat: latit,
                    lng: longit
                },
                travelMode: 'DRIVING'
            }, function(response, status) {
                if (status === 'OK') {
                    directionsDisplay.setDirections(response);
                } else {
                    window.alert('Directions request failed due to ' + status);
                }
            });

        });

The full code is here on github.

A gh-pages working example.