-1

I've got this website where customers have their own profile. They each have a map on their profile. When someone is viewing their profile I would like them to have the abillity to press on theese buttons and get directions by car, transit or walking.

The buttons work, and I get the users geo-location. But the thing is, there is never a route found, for some reason.

Is there something wrong with the JS code?

$.get("http://maps.google.no/maps/api/geocode/json?address={{ $company -> forretningsadresse_adresse  }}, {{ $company -> forretningsadresse_postnummer }} {{ $company -> forretningsadresse_poststed }}", function(data) {

            var mapStyle = [];
            var pos = new google.maps.LatLng(data["results"][0]["geometry"]["location"]["lat"], data["results"][0]["geometry"]["location"]["lng"]);
            var myOptions = {
                zoom: 15,
                center: pos,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                styles: mapStyle,
                scrollwheel: true
            };

            map = new google.maps.Map(document.getElementById('map'), myOptions);
            directionsDisplay = new google.maps.DirectionsRenderer();
            directionsDisplay.setMap(map);

            var marker = new google.maps.Marker({
                position: pos,
                map: map,
                animation: google.maps.Animation.DROP,
                title: 'Posisjon'
            });

            mapsBusinessPosition = pos;

        });

        function initMap(pos) {

            var directionsDisplay;
            directionsService = new google.maps.DirectionsService();
            var mapStyle = [];

            var myOptions = {
                zoom: 15,
                center: pos,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                styles: mapStyle,
                scrollwheel: true
            };

            map = new google.maps.Map(document.getElementById('map'), myOptions);

            directionsDisplay = new google.maps.DirectionsRenderer();
            directionsDisplay.setMap(map);

            var marker = new google.maps.Marker({
                position: pos,
                map: map,
                animation: google.maps.Animation.DROP,
                title: 'Posisjon'
            });

            mapsBusinessPosition = pos;
        }

        function getDirections(mode) {

            $("#tripDuration").html("Laster...");

            var userLocation;
            if (navigator.geolocation) {

                navigator.geolocation.getCurrentPosition(function(position) {

                    userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

                    var request = {
                        origin: userLocation,
                        destination: mapsBusinessPosition,
                        travelMode: mode
                    };

                    directionsService.route(request, function(result, status) {
                        if (status == google.maps.DirectionsStatus.OK) {
                            directionsDisplay.setDirections(result);
                            $("#tripDuration").html(result.routes[0].legs[0].duration.text);
                        } else {
                            $("#tripDuration").html("Fant ingen rute");
                        }
                    });
                }, function() {
                    alert("Argh!");
                });

            }

            else {
                alert("Argh!");
            }

        }

And here are the buttons.

<div class="directions">
    <img src="img/transit.png" alt="transit" onclick="getDirections(google.maps.TravelMode.TRANSIT);"/>
    <img src="img/car.png" alt="car" onclick="getDirections(google.maps.TravelMode.DRIVING);"/>
    <img src="img/walking.png" alt="walking" onclick="getDirections(google.maps.TravelMode.WALKING);"/>
    <span id="tripDuration"></span>
</div>

Oh, and the maps works fine at first glance, it's only the directions that wont work.

So what do I do wrong?

Thanks in advance.

Kaizokupuffball
  • 2,703
  • 8
  • 38
  • 58

1 Answers1

0

Your example works for me. To find out what might be causing issues on your side, try to log errors like this:

if (navigator.geolocation) {

            navigator.geolocation.getCurrentPosition(function(position) {

                userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

                var request = {
                    origin: userLocation,
                    destination: mapsBusinessPosition,
                    travelMode: mode
                };

                directionsService.route(request, function(result, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(result);
                        $("#tripDuration").html(result.routes[0].legs[0].duration.text);
                    } else {
                        console.log(status); //Error of Google Maps Directions Service
                        $("#tripDuration").html("Fant ingen rute");
                    }
                });
            }, function(error) { //HERE!!
                console.log(error); //Error of HTML5 geolocation API
            });

}else {
  console.log('Your browser does not support geolocation API'); //HERE!!!
}

And watch javascript console for output. This might give you more clues.

From the top of my head, there are couple of things that might be causing the issue.

  1. You are not running the application from application server, but from file:// url. In this case some browsers are blocking navigator.geolocation requests. More about this in this SO question
  2. You are running your application which is neither localhost nor HTTPS server and you are using Chrome version >= 50. Since version 50 Chrome started blocking navigator.geolocation requests if not secure (HTTPS) server, more about this here.
  3. There is some problem with directionsService. Check status for the information and the list of statuses here to find out what might be causing the error.
Community
  • 1
  • 1
Matej P.
  • 5,303
  • 1
  • 28
  • 44
  • Hmm. I get "ZERO_RESULTS". But thats wrong. When I go to maps.google.com and type in directions from: Henrik Lunds Gate 2, 9900 Kirkenes in Norway, to Tveitanvegen 52, 3946 Porsgrunn also in Norway, I get directions. And the exact same addresses on the profile gives "ZERO_RESULTS". I can also verify that origin and destination are different lat lngs. – Kaizokupuffball May 18 '16 at 21:46
  • 1
    You input Latitude-Longitude coordinate as origin location in your code, not address, same with destination. So trying with addresses on maps.google.com won't help you debug. Also with transit tends to return ZERO_RESULTS more often than other types, did you try driving or walking? Try to console.log(request.origin.toString(), request.destination.toString()); right before making the directionsService.route request and put those coordinates as starting and ending point on maps.google.com and see if it finds route. It shouldn't. – Matej P. May 18 '16 at 23:03
  • Okay so, I think I found the problem. My own position (lat, lng) is located in the middle of the sea, but really, I live on the coast in the top of Norway in Kirkenes. So that might be the problem. – Kaizokupuffball May 19 '16 at 11:53
  • The HTML5 geolocation works better on mobile devices with GPS than desktop computers, so if you are testing on desktop and your app is for mobile, it is probable you will get better results on mobile. Also, you can play around with enableHighAccuracy parameter of HTML geolocation, more info here: http://stackoverflow.com/questions/9053262/geolocation-html5-enablehighaccuracy-true-false-or-best-option . If device won't be able to find results in timeout with high accuracy, you can fall back to lower and inform user, or prompt them to mark/input their location by themselves. – Matej P. May 19 '16 at 12:06