0

I' m having this problem , when I load my page and insert Origin and Destination, after clicking the button "locate" it doesn't show anything in the google map, because it says Response is not an object , so I tried to stamp it with console.log and it says Response=null , but if I reload the page and click fast on Locate , then it draws the route.

Here's the code

function init(){
    var latlng = new google.maps.LatLng(40.635636, 17.942414);
    var mapOptions = { zoom: 12, center: latlng  };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function updateMap(){
    init();

    var originGeocoder = new google.maps.Geocoder();
    var destinationGeocoder = new google.maps.Geocoder();

    var origin = document.getElementById( "origin" ).value + " Brindisi 72100";
    var destination = document.getElementById( "destination" ).value + " Brindisi 72100";


    var directionsService2 = new google.maps.DirectionsService();

    originGeocoder.geocode( { 'address': origin }, function(results, status) {
        if ( status == google.maps.GeocoderStatus.OK ) {
            var startLatLng = results[0].geometry.location;
            var oLat = startLatLng.lat();
            var oLng = startLatLng.lng();
            document.getElementById('cStart').innerHTML = oLat + " " + oLng;
        }
        else{
            alert("Geocode was not successful for the following reason: " + status);
        }      
    });

    //Chiamata asincrona alle API per ottenere Lat e Lng dell' indirizzo di destinazione
    destinationGeocoder.geocode( { 'address': destination }, function(results, status) {
        if ( status == google.maps.GeocoderStatus.OK ) {
            var destLatLng = results[0].geometry.location;
            var dLat = destLatLng.lat();
            var dLng = destLatLng.lng();
            document.getElementById('cDestination').innerHTML = typeof dLat;
            document.getElementById('cDestination').innerHTML = dLat + " " + dLng;
        }
        else{
            alert("Geocode was not successful for the following reason: " + status);
        }        
    });

    //Salva in req[] le varie distanze tra le paline e la destinazione
    singleObjToStop(origin,destination,function(paline,req,reqO){
        console.log("1");
        //Trova la palina più vicina alla destinazione
        calcSingleDis(paline,req,reqO,function(w2,w1){
            console.log("2");
            //Disegna i waypoints(?)
            reqEnd(origin,destination,w1,w2,function(request){
                console.log("3");
                directionsService2.route(request, function(response, status) {
                    console.log("4");
                    console.log(response);
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(response);
                        var route = response.routes[0];
                        var summaryPanel = document.getElementById("distance");
                        summaryPanel.innerHTML = "";
                        // For each route, display summary information.
                        for (var i = 0; i < route.legs.length; i++) {
                            var routeSegment = i + 1;
                            summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
                            summaryPanel.innerHTML += route.legs[i].start_address + " to ";
                            summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
                            summaryPanel.innerHTML += route.legs[i].distance.text + " ";
                            summaryPanel.innerHTML += route.legs[i].duration.text +  "<br /><br />" ;
                        }
                        computeTotalDistance(response);
                    }
                    else{
                        console.log("ENTRA QUA STRONZO");
                        console.log("Fermata partenza = " + w1);
                        console.log("Fermata arrivo = " + w2);
                    }
                });
                directionsDisplay.setMap(map);
            });
        });
    });
}

function singleObjToStop(origin,destination,callback){
    var data=<?php echo $data; ?>;
    var a,b,i=0;
    var paline = new Array();
    var req = new Array(); 
    var reqO = new Array();
    var num = <?php echo $n; ?>;
    $.each(data, function(fieldName, fieldValue) {
        a=fieldValue.geoLat;
        b=fieldValue.geoLong;
        a=parseFloat(a);
        b=parseFloat(b);
        paline[i]=new google.maps.LatLng(a,b);

        req[i] = {
            origin:paline[i],
            destination:destination,
            travelMode: google.maps.TravelMode.WALKING
        };

        reqO[i] = {
            origin:origin,
            destination:paline[i],
            travelMode: google.maps.TravelMode.WALKING
        };

        i++;
        if(i==num){
            callback(paline,req,reqO);
        }
    });
}

function calcSingleDis(paline, req, reqO, callback) {
    var directionsService = new google.maps.DirectionsService();
    var c = 10000000;
    var w2 = new google.maps.LatLng(0, 0);
    var w1 = new google.maps.LatLng(0, 0);
    var num = <?php echo $n; ?>;
    var j = (num - 1);
    var t;

    var cO = 10000000;
    var numO = <?php echo $n; ?>;
    var jO = 0;
    for (j = 0; j < num; j++) {
        t = 0;
        directionsService.route(req[j], function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                //directionsDisplay.setDirections(response);
                var troute = response.routes[0];
                var dis = parseFloat((troute.legs[0].distance.text).replace(",", "."));

                document.getElementById('test').innerHTML = dis;

                //se distanza minore di quella minore trovata fin ora la cambia
                if (dis < c) {
                    w2 = paline[j - num];
                    c = dis;
                }

                if (t == (num - 1)) {
                    console.log("QUA ENTRA LOL");

                    for (jO = 0; jO < numO; jO++) {
                        console.log("E NON ENTRA MANNAC");
                        t = 0;
                        directionsService.route(reqO[jO], function(response, status) {
                            if (status == google.maps.DirectionsStatus.OK) {
                                console.log("E NON ENTRA MANNAC22222");
                                //directionsDisplay.setDirections(response);
                                var troute = response.routes[0];
                                var disO = parseFloat((troute.legs[0].distance.text).replace(",", "."));

                                document.getElementById('test').innerHTML = dis;

                                //se distanza minore di quella minore trovata fin ora la cambia
                                if (disO < cO) {
                                    w1 = paline[jO - numO];
                                    cO = disO;
                                }

                                if (t == (numO - 1)) {
                                    console.log("W1 = " + w1);
                                    console.log(response);
                                    callback(w2, w1);

                                }
                            }
                            jO++;
                            t++;
                        });
                    }

                }
            }
            j++;
            t++;
        });
    }
}

function reqEnd(origin,destination,w1,w2,callback){
    var request = {
        origin:origin,
        destination:destination,
          waypoints: [{location: w1} , {location: w2}],
          //waypoints: [{location: w2}],
          optimizeWaypoints: true,
        travelMode: google.maps.DirectionsTravelMode.WALKING
    };
    callback(request);
}

function computeTotalDistance(result) {
    var totalDist = 0;
    var totalTime = 0;
    var myroute = result.routes[0];
    for (i = 0; i < myroute.legs.length; i++) {
        totalDist += myroute.legs[i].distance.value;
        totalTime += myroute.legs[i].duration.value;   
    }
    totalDist = totalDist / 1000.
    document.getElementById("total").innerHTML = "total distance is: "+ totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}

google.maps.event.addDomListener( window, 'load', init );
duncan
  • 31,401
  • 13
  • 78
  • 99

2 Answers2

3

The problem is related to the limit of query that you can use with Google Maps API v3. You can take a look here: https://developers.google.com/maps/documentation/business/faq#google_maps_api_services

You probably do lots of requests to the API with your program, while you have quite restrictive limits as you can see from google Q&A.

Applications should throttle requests to avoid exceeding usage limits, bearing in mind these apply to each client ID regardless of how many IP addresses the requests are sent from.

You can throttle requests by putting them through a queue that keeps track of when are requests sent. With a rate limit or 10 QPS (queries per second), on sending the 11th request your application should check the timestamp of the first request and wait until 1 second has passed. The same should be applied to daily limits.

Even if throttling is implemented correctly applications should watch out for responses with status code OVER_QUERY_LIMIT. If such response is received, use the pause-and-retry mechanism explained in the Usage limits exceeded section above to detect which limit has been exceeded.

You could find useful: How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

Community
  • 1
  • 1
Mitro
  • 1,230
  • 8
  • 32
  • 61
0

The Google Maps API provides a geocoder class for geocoding and reverse geocoding dynamically from user input. read more check Geolocation demo here and more HTML5 Geolocation to check here

Sunil Acharya
  • 1,153
  • 5
  • 22
  • 39