Using Google Maps API to get travel time data [closed]

匆匆过客 提交于 2019-12-17 05:37:40

问题


All the examples I've come across using google maps api seem to show a map of some kind. I would like to incorporate the data about the estimated travel time by car they give you when you ask for a road description from A to B into a site. And only that data. Is it possible without loading up a map for the end visitor?


回答1:


Yep, this is definitely possible using the API. You can construct a GDirections object without a map or directions div. You can do a load request from A to B and then call the getDuration method to get the total travel time.

First you need to create a directions object:

// no need to pass map or results div since
// we are only interested in travel time.
var directions = new GDirections (); 

Then do your load request to resolve the directions (I have used two latitudes and longitudes as my start and end points, but you can use addresses here as well):

var wp = new Array ();
wp[0] = new GLatLng(32.742149,119.337218);
wp[1] = new GLatLng(32.735347,119.328485);
directions.loadFromWaypoints(wp);

Then you need to listen for the load event so you can call getDuration once the directions have been resolved:

GEvent.addListener(directions, "load", function() {
    $('log').innerHTML = directions.getDuration ().seconds + " seconds";
        });

You can find the whole example here and the JavaScript here. You can check the Google Maps Documentation for more info about the options you can give the GDirections object (like walking distance etc...). You should also listen to the error event for geocoding failures.




回答2:


The above answer is in violation of Google API terms of service, and hence, incorrect.

The Google Maps API only allows you to calculate travel time if it's referenced against a Google Map displayed to the user.

You can't use the API if you don't display a Google Map to the end user of the service.

Update:

Any answer here, that does not show the final results mapped on a google map, is in violation of the aforementioned terms of service and eventually, incorrect.




回答3:


For the record: At this time (year 2015) GDirections, GLatLng, GEvent, etc. are deprecated.


You can use google.maps.DirectionsService class (Google Maps JavaScript API V3)

In the following snippet, location and target are objects containing latitude and longitude coordinates.

1) The google.maps.DirectionsService class admit both LatLng and string values to feed their origin and destination properties.
2) A LatLng is a point in geographical coordinates: latitude and longitude.

var origin = new google.maps.LatLng( location.latitude, location.longitude ); // using google.maps.LatLng class
var destination = target.latitude + ', ' + target.longitude; // using string

var directionsService = new google.maps.DirectionsService();
var request = {
    origin: origin, // LatLng|string
    destination: destination, // LatLng|string
    travelMode: google.maps.DirectionsTravelMode.DRIVING
};

directionsService.route( request, function( response, status ) {

    if ( status === 'OK' ) {
        var point = response.routes[ 0 ].legs[ 0 ];
        $( '#travel_data' ).html( 'Estimated travel time: ' + point.duration.text + ' (' + point.distance.text + ')' );
    }
} );



回答4:


from google.maps.DirectionsRenderer

Distance by using:

directionsDisplay.directions.routes[0].legs[0].distance.text

Duration by using:

directionsDisplay.directions.routes[0].legs[0].duration.text



回答5:


  1. First go here: https://developers.google.com/maps/documentation/distance-matrix/start You need to: Create or select a project, Enable the API and Get an API key Just click on the "Get a Key" and assuming you have a Gmail account you can get everything going (alternatively go to console.developer.google.com after logging in to your gmail account, and create an app, and enable the API, and get the API key there).
  2. Now go to https://developers.google.com/maps/documentation/distance-matrix/intro and follow the details. A couple things to note: use these: &mode=driving&departure_time=now&traffic_model=pessimistic if you want current traffic to influence your drive time. I also used &units=imperial

The duration in traffic is returned only if all of the following are true:

The request includes a departure_time parameter. The request includes a valid API key, or a valid Google Maps APIs Premium Plan client ID and signature. Traffic conditions are available for the requested route. The mode parameter is set to driving.

As of at least May 2019, you are now allowed display the drive time with or without a map.

You can display Distance Matrix API results on a Google Map, or without a map. If you want to display Distance Matrix API results on a map, then these results must be displayed on a Google Map. It is prohibited to use Distance Matrix API data on a map that is not a Google map.

Source: Distance Matrix usage limits, also checkout Google Maps Terms & Conditions

Note that Mapquest doesn't show drive times based on actual traffic.




回答6:


I struggled with this for a long time but finally solved it with an AJAX call (make sure you're linked to jQuery to do this).

 //Pass parameters to a function so your user can choose their travel 
 locations

 function getCommuteTime(departLocation, arriveLocation) {
   //Put your API call here with the parameters passed into it
   var queryURL = 
   "https://maps.googleapis.com/maps/api/distancematrix/json?
   units=imperial&origins=" + departLocation + "&destinations=" + 
   arriveLocation + "&key=YOUR_API_KEY"

  //Ajax retrieves data from the API
  $.ajax({
  url: queryURL,
  method: "GET"
  }).then(function(response) {

    //Navigate through the given object to the data you want (in this 
     case, commute time)
    var commuteTime = response.rows[0].elements[0].duration.text;

    console.log(commuteTime)
   });

  } 


//This is where your user can give you the data you need
$("#addRoute").on("click", function(event) {

event.preventDefault();

var departLocation = $("#departInput").val().trim();
var arriveLocation = $("#arriveInput").val().trim();

//call the above function
getCommuteTime(departLocation, arriveLocation);
  });



回答7:


pseudocode:

  1. DirectionsService.route({A,B}) //get a DirectionsResult here

  2. check distance and duration(travel time) in the DirectionsLeg.//from DirectionsResult.legs

    a route with no waypoints will contain one DirectionsLeg, so that's what you want.



来源:https://stackoverflow.com/questions/1042885/using-google-maps-api-to-get-travel-time-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!